近來公司項目要求用到微信H5開發,由於微信開發文檔到處都是坑,我也走了很多彎路,如今就把H5支付的過程記錄一下,已備後用!!php
首先 先去商戶平臺申請開通 H5支付!!!! html
咱們從微信官方下載H5支付demo,(忘記了沒有demo,本身寫吧,蛋疼!)微信H5支付文檔請點擊這裏(爲了方便查看我用了_blank)。web
官方是給咱們提供了案例的你們能夠移步查看--->微信官方體驗連接:http://wxpay.wxutil.com/mch/pay/h5.v2.php,請在微信外瀏覽器打開。api
官方提供的流程,你們能夠看看是否是你想要的樣子,以防止寫錯 https://pay.weixin.qq.com/wiki/doc/api/H5.php?chapter=15_3數組
大概思路:前臺傳過來參數後臺接收好比金額(注意這裏的金額,微信傳的是分),訂單號,客戶端ip(獲取客戶端ip方法,官方給的方法不對,請查看個人另外一篇)等。瀏覽器
用到的最重要的接口是 統一下單 微信
$subject = $data['subject']; //商品描述
$total_amount = $data['total_amount']*100; //金額 $additional = $data['additional']; ////附加數據 $order_id = $data['order_id']; ////訂單號 $nonce_str=MD5($order_id);//隨機字符串 $spbill_create_ip = $data['spbill_create_ip']; //終端ip
//以上參數接收沒必要糾結,按照正常接收就行,相信你們都看得懂
//$spbill_create_ip = '118.144.37.98'; //終端ip測試 $trade_type = 'MWEB';//交易類型 具體看API 裏面有詳細介紹 $notify_url = 'http://xy.xxx.com/medias/public/index.php/home/Wxh5pay/notify_url'; //回調地址 $scene_info ='{"h5_info":{"type":"Wap","wap_url":"http://www.123.com","wap_name":"測試支付"}}'; //場景信息 //對參數按照key=value的格式,並按照參數名ASCII字典序排序生成字符串 $signA = "appid=$appid&body=$subject&mch_id=$mch_id&nonce_str=$nonce_str¬ify_url=$notify_url&out_trade_no=$order_id
&scene_info=$scene_info&spbill_create_ip=$spbill_create_ip&total_fee=$total_amount&trade_type=$trade_type"; $strSignTmp = $signA."&key=$key"; //拼接字符串 $sign = strtoupper(MD5($strSignTmp)); // MD5 後轉換成大寫 $post_data = "<xml> <appid>$appid</appid> <body>$subject</body> <mch_id>$mch_id</mch_id> <nonce_str>$nonce_str</nonce_str> <notify_url>$notify_url</notify_url> <out_trade_no>$order_id</out_trade_no> <scene_info>$scene_info</scene_info> <spbill_create_ip>$spbill_create_ip</spbill_create_ip> <total_fee>$total_amount</total_fee> <trade_type>$trade_type</trade_type> <sign>$sign</sign> </xml>";//拼接成XML 格式 $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";//微信傳參地址 $dataxml = $this->http_post($url,$post_data); //後臺POST微信傳參地址 同時取得微信返回的參數,http_post方法請看下文 $objectxml = (array)simplexml_load_string($dataxml, 'SimpleXMLElement', LIBXML_NOCDATA); //將微信返回的XML 轉換成數組 if($objectxml['return_code'] == 'SUCCESS') { if($objectxml['result_code'] == 'SUCCESS'){//若是這兩個都爲此狀態則返回mweb_url,詳情看‘統一下單’接口文檔 return $objectxml['mweb_url']; //mweb_url是微信返回的支付鏈接要把這個鏈接分配到前臺 } if($objectxml['result_code'] == 'FAIL'){
return $err_code_des = $objectxml['err_code_des'];
}}
你們可使用以上工具,檢測您的簽名是否是正確。微信開發
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;
}
以上就是微信H5支付,電腦支付請使用PC掃碼支付,原理相似,看文檔便可app