近來公司項目要求用到微信H5開發,因爲微信開發文檔處處都是坑,我也走了不少彎路,現在就把H5支付的過程記錄一下,已備後用!!
首先 先去商戶平臺申請開通 H5支付!!!!
我們從微信官方下載H5支付demo,(忘記了沒有demo,自己寫吧,蛋疼!)微信H5支付文檔請點擊這裏(爲了方便查看我用了_blank)。
官方是給我們提供了案例的大家可以移步查看—>微信官方體驗鏈接:http://wxpay.wxutil.com/mch/pay/h5.v2.php,請在微信外瀏覽器打開。
官方提供的流程,大家可以看看是不是你想要的樣子,以防止寫錯 https://pay.weixin.qq.com/wiki/doc/api/H5.php?chapter=15_3
大概思路:前臺傳過來參數後臺接收比如金額(注意這裏的金額,微信傳的是分),訂單號,客戶端ip(獲取客戶端ip方法,官方給的方法不對,請查看我的另一篇)等。
用到的最重要的接口是 統一下單
複製代碼
$subject = total_amount = $data[‘total_amount’]*100; //金額
$additional = $data[‘additional’]; ////附加數據
$order_id = $data[‘order_id’]; ////訂單號
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=KaTeX parse error: Expected 'EOF', got '&' at position 11: scene_info&̲spbill_create_i…spbill_create_ip&total_fee=KaTeX parse error: Expected 'EOF', got '&' at position 13: 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’];
}}
複製代碼
微信支付接口簽名校驗工具:https://pay.weixin.qq.com/wiki/doc/api/H5.php?chapter=20_1
大家可以使用以上工具,檢測您的簽名是不是正確。
function http_post($url, $data) {
ch, CURLOPT_URL,ch, CURLOPT_HEADER,0);
curl_setopt(ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
ch);
curl_close($ch);
return $res;
}
以上就是微信H5支付,電腦支付請使用PC掃碼支付,原理類似,看文檔即可