H5支付要求商戶(hù)在統(tǒng)一下單接口中上傳用戶(hù)真實(shí)ip地址“spbill_create_ip”,為保證微信端獲取的用戶(hù)ip地址與商戶(hù)端獲取的一致,提供了以下獲取用戶(hù)ip的指引,希望對(duì)大家有所幫助。
在商戶(hù)的前端接入層沒(méi)有做代理的情況下獲取ip的方式比較簡(jiǎn)單,直接獲取'REMOTE_ADDR '即可。
在有代理的情況下,因?yàn)橐婵蛻?hù)端去訪(fǎng)問(wèn)服務(wù)器,所以,當(dāng)請(qǐng)求包經(jīng)過(guò)反向代理后,在代理服務(wù)器這里這個(gè)IP數(shù)據(jù)包的IP包頭做了修改,最終后端WEB服務(wù)器得到的數(shù)據(jù)包的頭部源IP地址是代理服務(wù)器的IP地址。這樣一來(lái),后端服務(wù)器的程序就無(wú)法獲取用戶(hù)的真實(shí)ip。
nginx有代理的情況:
在nginx中配置中加入
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Real-Port $remote_port;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
Apache有代理的情況:
vi /usr/local/apache/conf/httpd.conf
Include conf/extra/httpd-remoteip.conf
vi /usr/local/apache/conf/extra/httpd-remoteip.conf
LoadModule remoteip_module modules/mod_remoteip.so
RemoteIPHeader X-Forwarded-For
RemoteIPinternalProxy 127.0.0.1
代碼示例
string GetClientIp(CgiInput * poInput)
{
string client_ip = "";
string strClientIPList;
GetHttpHeader("X-Forwarded-For", strClientIPList);
if (strClientIPList.empty())
{
GetHttpHeader("X-Real-IP", strClientIPList);
}
if (!strClientIPList.empty())
{
size_t iPos = strClientIPList.find(",");
if (iPos != std::string::npos)
{
client_ip = strClientIPList.substr(iPos);
} else
{
client_ip = strClientIPList;
}
}
if (client_ip.empty())
{
GetHttpHeader("PROXY_FORWARDED_FOR", strClientIPList);
// 做下兼容
if (strClientIPList.empty())
{
client_ip = getRemoteAddr();
} else
{
size_t iPos = strClientIPList.find(",");
if (iPos != std::string::npos)
{
client_ip = strClientIPList.substr(iPos);
} else
{
client_ip = strClientIPList;
}
}
}
if (!MMPayCommFunc::IsIp(client_ip))
client_ip = getRemoteAddr();
return client_ip;
}