有關微信公眾號和H5支付的一些記錄
最近項目裏面需要做公眾號和H5支付的功能,根據自己的體驗,整理了一下,做個記錄。
首先我解釋一下,為什麽有公眾號支付還要做H5支付?因為不確定每個用戶在公眾號上打開網站,所以另外做了H5支付。
以下是官方的解釋:
H5支付是指商戶在微信客戶端外的移動端網頁展示商品或服務,用戶在前述頁面確認使用微信支付時,商戶發起本服務呼起微信客戶端進行支付。
主要用於觸屏版的手機瀏覽器請求微信支付的場景。可以方便的從外部瀏覽器喚起微信支付。
提醒:H5支付不建議在APP端使用,如需要在APP中使用微信支付,請接APP支付,文檔詳見微信支付開發文檔。
既然是公眾號支付,準備工作要做好:
必須是認證的服務號才能支付,詳細接口權限見官方文檔:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433401084。
1.登陸公眾號:
2.
3.登陸商戶平臺(pay.weixin.qq.com)
在開發配中設置如下:
H5支付直接填寫服務器的域名即可。
JSAPI授權目錄這裏需要註意,如果支付授權目錄沒有設置正確,在請求JSAPI時,會提示“-1當前頁面的url未註冊”的錯誤。”
首先要看你支付的當前頁面URL,
比如是:http://www.xxx.com/wxpay/jsapi.php
你就必須填寫:http://www.xxx.com/wxpay/
假如是:http://www.xxx.com/wxpay/order/id/56.html
你就必須寫: http://www.xxx.com/wxpay/order/id/
假如是:http://www.xxx.com/wxpay/order?id=56
你就必須寫:http://www.xxx.com/wxpay/order/
下面是代碼部分:
下載好官方的sdk,我是放到網站的根目錄,看網上有把SDK進行集成封裝好的,大家可自行搜索。
1.在lib----->下的Wxpay.Config.php文件中,填好APPID、MCHID、KEY(操作密碼)、APPSECRET(公眾帳號secert)
設置證書:
在配置文件的最後最好加上回調地址(當時我沒有設置報錯了,想不起來是什麽錯誤了,沒及時記錄……)
2.寫一個驗證token的方法(代碼是網上找的,順便找了一下有關token的登陸介紹:http://blog.csdn.net/resilient/article/details/72673222)
1 <?php 2 /** 3 * wechat php test 4 */ 5 //define your token 6 define("TOKEN", "shendai"); 7 $wechatObj = new wechatCallbackapiTest(); 8 $wechatObj->valid(); 9 10 class wechatCallbackapiTest 11 { 12 public function valid() 13 { 14 $echoStr = $_GET["echostr"]; 15 //valid signature , option 16 if ($this->checkSignature()) 17 { 18 echo $echoStr; 19 exit; 20 } 21 } 22 public function responseMsg() 23 { 24 //get post data, May be due to the different environments 25 $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; 26 //extract post data 27 if (!empty($postStr)) 28 { 29 $postObj = simplexml_load_string($postStr, ‘SimpleXMLElement‘, LIBXML_NOCDATA); 30 $fromUsername = $postObj->FromUserName; 31 $toUsername = $postObj->ToUserName; 32 $keyword = trim($postObj->Content); 33 $time = time(); 34 $textTpl = "<xml> 35 <ToUserName><![CDATA[%s]]></ToUserName> 36 <FromUserName><![CDATA[%s]]></FromUserName> 37 <CreateTime>%s</CreateTime> 38 <MsgType><![CDATA[%s]]></MsgType> 39 <Content><![CDATA[%s]]></Content> 40 <FuncFlag>0</FuncFlag> 41 </xml>"; 42 if (!empty($keyword)) 43 { 44 $msgType = "text"; 45 $contentStr = "Welcome to wechat world!"; 46 $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); 47 echo $resultStr; 48 } 49 else 50 { 51 echo "Input something..."; 52 } 53 } 54 else 55 { 56 echo ""; 57 exit; 58 } 59 } 60 private function checkSignature() 61 { 62 $signature = $_GET["signature"]; 63 $timestamp = $_GET["timestamp"]; 64 $nonce = $_GET["nonce"]; 65 $token = TOKEN; 66 $tmpArr = array($token, $timestamp, $nonce); 67 sort($tmpArr); 68 $tmpStr = implode($tmpArr); 69 $tmpStr = sha1($tmpStr); 70 if ($tmpStr == $signature) 71 { 72 return true; 73 } 74 else 75 { 76 return false; 77 } 78 } 79 80 81 } 82 83 ?>View Code
有關微信公眾號和H5支付的一些記錄