public function wxWapPay(){
$out_trade_no = $_GET['out_trade_no']; //商家订单号
$total_fee = $_GET['total_fee']*100; //商品价格 单位为分
$time = time();
$nonce_str = xxx; //随机字符串 不多于32位
$appid = xxx; //appid
$mch_id = xxx; //商户号
$key = xxx; //支付密钥
$notify_url = xxx; //回调地址
$body = "app支付"; //描述
$scene_info = '{"h5_info": {"type":"Wap","wap_url": "http://www.xxx.cn","wap_name": "订单支付"}}';
$spbill_create_ip = $this->get_client_ip(); //获取ip
$trade_type = "MWEB"; //固定的
// 下面的参数含义直接看文档
$tmpArr = array(
'appid' =>$appid,
'attach' =>$out_trade_no,
'body' =>$body,
'mch_id' =>$mch_id,
'nonce_str' =>$nonce_str,
'notify_url'=>$notify_url,
'spbill_create_ip'=>$spbill_create_ip,
'out_trade_no'=>$out_trade_no,
'scene_info'=>$scene_info,
'total_fee' =>$total_fee,
'trade_type'=>'MWEB'
);
//签名逻辑官网有说明,签名步骤就不解释了
ksort($tmpArr);
$buff = "";
foreach ($tmpArr as $k => $v)
{
$buff .= $k . "=" . $v . "&";
}
$buff = trim($buff, "&");
$stringSignTemp=$buff."&key=".$key;
$sign = strtoupper(MD5($stringSignTemp)); // MD5 后转换成大写
$xml = "<xml>
<appid>".$appid."</appid>
<attach>".$out_trade_no."</attach>
<body>".$body."</body>
<mch_id>".$mch_id."</mch_id>
<nonce_str>".$nonce_str."</nonce_str>
<notify_url>".$notify_url."</notify_url>
<out_trade_no>".$out_trade_no."</out_trade_no>
<spbill_create_ip>".$spbill_create_ip."</spbill_create_ip>
<total_fee>".$total_fee."</total_fee>
<trade_type>MWEB</trade_type>
<scene_info>".$scene_info."</scene_info>
<sign>".$sign."</sign>
</xml> ";
$posturl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
$res = $this->http_post($posturl,$xml);
//dump($res);exit;
$objectxml = (array)simplexml_load_string($res, 'SimpleXMLElement', LIBXML_NOCDATA); //将微信返回的XML 转换成数组
if($objectxml['result_code'] == 'SUCCESS'){
header('location:'.$objectxml['mweb_url']);
echo "<a href=".$objectxml['mweb_url'].">点击支付</a>";
}
}
public function http_post($url, $data) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$res = curl_exec($ch);
curl_close($ch);
return $res;
}
public function get_client_ip($type = 0) {
$type = $type ? 1 : 0;
$ip = 'unknown';
if ($ip !== 'unknown') return $ip[$type];
if($_SERVER['HTTP_X_REAL_IP']){//nginx 代理模式下,获取客户端真实IP
$ip=$_SERVER['HTTP_X_REAL_IP'];
}elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {//客户端的ip
$ip = $_SERVER['HTTP_CLIENT_IP'];
}elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {//浏览当前页面的用户计算机的网关
$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
$pos = array_search('unknown',$arr);
if(false !== $pos) unset($arr[$pos]);
$ip = trim($arr[0]);
}elseif (isset($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];//浏览当前页面的用户计算机的ip地址
}else{
$ip=$_SERVER['REMOTE_ADDR'];
}
// IP地址合法验证
$long = sprintf("%u",ip2long($ip));
$ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
return $ip[$type];
}