1. What to say first
1. The opening date of WeChat payment for our official account is September 22, so the applicable document version number is v3.3.6. At that time, I accidentally got a v2.7 document from WeChat customer service, and I was so excited For a day, I crawled out of puddles and fell into urine puddles, which made people miserable. Only when I found the relevant people later did I get the truth. But now it can also be downloaded on the public platform~ I hope everyone can avoid this pit. !
2. The most important point: This article is suspected of being a soft advertisement, please read with caution! Help your friends to write comments here first~~~
2. You need to go to these places to pick up the parameters
1. Log in to the WeChat public account management backend mp.weixin.qq.com, find the Developer Center in the left menu bar, click on the picture below to see the AppID and AppSecret:
2. After WeChat payment is approved, Tenpay will send 3 emails to the applicant’s mailbox. My family previously opened an account through Tenpay for the main site payment interface, but this A new Tenpay account was issued this time, but what is surprising is that this time WeChat payment does not require a deposit. I don’t know why?
Click on the email from weixinpay to see the account information. Download and save the pem format file in the attachment to the web server. Please note the absolute path of the file, which will be used in the following code:
3. Log in to the WeChat merchant platform (mch.weixin.qq.com) and set the merchant payment key Key:
4. Log in to the WeChat public account management backend mp.weixin.qq.com, set up payment configuration, payment test, payment whitelist
3. Find the parameters to configure the class class WxPayConf
class WxPayConf
{
//=======[Basic information settings]================== ===================
//The unique identifier of the WeChat official account. After passing the review, check
in the email sent by WeChatconst APPID = "Fill in the AppID" seen in 1;
//AcceptorID, Identity Identification
const MCHID = "Fill in the MCHID" seen in 2, 2;
//Merchant Payment KeyKey. After passing the review, check ( in the email sent by WeChat. If there is no , , you can log in to the WeChat merchant platform to set up )
const KEY = "Fill in the key set in 2. 3";
//JSAPIObtain openid. After review, you can view
const APPSECRET = "Fill in the AppSecret" seen in 2. 1;
//=======[JSAPIPath Settings]====== =============================
//Get access_tokenJump in the process uri, by jumping Pass code into jsapipayment page
const JS_API_CALL_URL = "http://www.xxx.com/wxpay/js_api_call.php";
//=======[Certificate path setting]================== ===================
//Certificate path,Note that the absolute path should be filled in
const SSLCERT_PATH = "Fill in the pem files downloaded from 22 The path placed on the server ";
const SSLKEY_PATH = "Fill in the pem files downloaded from 22 The path placed on the server ";
//=======[Asynchronous notificationurlSettings]===== ==============================
//Asynchronous notificationurl, the merchant sets it according to the actual development process
const NOTIFY_URL = http://www.xxxx.com/wxpay/notify_url.php;
}
4. JSAPI payment
WeChat JS API can only be used in WeChat’s built-in browser, and calls from other browsers are invalid.
The following code is the JS API payment demo officially provided by WeChat
include_once("WxPayHelper/WxPayHelper.php");
//使用jsapi接口 $jsApi = new JsApi(); //=========步骤1:网页授权获取用户openid============ //通过code获得openid if(!isWeixin()){ echo "请在微信内扫描二维码"; exit; } if (!isset($_GET['code'])) { //触发微信返回code码 $url = $jsApi->createOauthUrlForCode(WxPayConf::JS_API_CALL_URL."); Header("Location: $url"); }else { //获取code码,以获取openid $code = $_GET['code']; $jsApi->setCode($code); $openid = $jsApi->getOpenId(); } if(empty($order)){ echo "数据错误!"; exit; } } //=========步骤2:使用统一支付接口,获取prepay_id============ //使用统一支付接口 $unifiedOrder = new UnifiedOrder(); //设置统一支付接口参数 //设置必填参数 //appid已填,商户无需重复填写 //mch_id已填,商户无需重复填写 //noncestr已填,商户无需重复填写 //spbill_create_ip已填,商户无需重复填写 //sign已填,商户无需重复填写 $unifiedOrder->setParameter("openid","$openid");//商品描述 $unifiedOrder->setParameter("body","test");//商品描述 //自定义订单号,此处仅作举例 $timeStamp = time(); $out_trade_no = timeStamp; $total_fee = 1; $unifiedOrder->setParameter("out_trade_no","$out_trade_no");//商户订单号 $unifiedOrder->setParameter("total_fee",$total_fee);//总金额 $unifiedOrder->setParameter("notify_url",WxPayConf::NOTIFY_URL);//通知地址 $unifiedOrder->setParameter("trade_type","JSAPI");//交易类型 //非必填参数,商户可根据实际情况选填 //$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号 //$unifiedOrder->setParameter("device_info","XXXX");//设备号 //$unifiedOrder->setParameter("attach","XXXX");//附加数据 //$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间 //$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间 //$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记 //$unifiedOrder->setParameter("openid","XXXX");//用户标识 //$unifiedOrder->setParameter("product_id","XXXX");//商品ID $prepay_id = $unifiedOrder->getPrepayId(); //=========步骤3:使用jsapi调起支付============ $jsApi->setPrepayId($prepay_id); $jsApiParameters = $jsApi->getParameters(); function isWeixin(){ $agent = strtolower($_SERVER['HTTP_USER_AGENT']); $is_weixin = strpos($agent, 'micromessenger') ? true : false ; if($is_weixin){ return true; }else{ return false; } } ?> <html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <title>微信安全支付</title> <script type="text/javascript"> //调用微信JS api 支付 function jsApiCall() { WeixinJSBridge.invoke( 'getBrandWCPayRequest', <?php echo $jsApiParameters; ?>, function(res){ WeixinJSBridge.log(res.err_msg); //alert(res.err_code+res.err_desc+res.err_msg); } ); } function callpay() { if (typeof WeixinJSBridge == "undefined"){ if( document.addEventListener ){ document.addEventListener('WeixinJSBridgeReady', jsApiCall, false); }else if (document.attachEvent){ document.attachEvent('WeixinJSBridgeReady', jsApiCall); document.attachEvent('onWeixinJSBridgeReady', jsApiCall); } }else{ jsApiCall(); } } </script> </head> <body onload=""> </br> </br> </br> </br> <div align="center"> <button style="width: 210px; height: 30px; background-color: #FE6714; border: 0px #FE6714 solid; cursor: pointer; color: white; font-size: 16px;" type="button" onclick="callpay()">贡献一下</button> </div> </body> </html>
Modify the WeChat payment parameters to those you applied for, then upload the webpage to the WeChat payment directory, Use the public account Reply the web address to the test account. Users can realize a JS API payment.
5. NATIVE payment
Using the official demo, the native payment mode 2 is completed
The following code is provided by WeChat official naticepayment demo
include_once("WxPayHelper/WxPayHelper.php");
//使用统一支付接口 $unifiedOrder = new UnifiedOrder(); //设置统一支付接口参数 //设置必填参数 //appid已填,商户无需重复填写 //mch_id已填,商户无需重复填写 //noncestr已填,商户无需重复填写 //spbill_create_ip已填,商户无需重复填写 //sign已填,商户无需重复填写 $unifiedOrder->setParameter("body","贡献一分钱");//商品描述 //自定义订单号,此处仅作举例 $timeStamp = time(); $out_trade_no = WxPayConf::APPID."$timeStamp"; $unifiedOrder->setParameter("out_trade_no","$out_trade_no");//商户订单号 $unifiedOrder->setParameter("total_fee","1");//总金额 $unifiedOrder->setParameter("notify_url",WxPayConf::NOTIFY_URL);//通知地址 $unifiedOrder->setParameter("trade_type","NATIVE");//交易类型 //非必填参数,商户可根据实际情况选填 //$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号 //$unifiedOrder->setParameter("device_info","XXXX");//设备号 //$unifiedOrder->setParameter("attach","XXXX");//附加数据 //$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间 //$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间 //$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记 //$unifiedOrder->setParameter("openid","XXXX");//用户标识 //$unifiedOrder->setParameter("product_id","XXXX");//商品ID //获取统一支付接口结果 $unifiedOrderResult = $unifiedOrder->getResult(); //商户根据实际情况设置相应的处理流程 if ($unifiedOrderResult["return_code"] == "FAIL") { //商户自行增加处理流程 echo "通信出错:".$unifiedOrderResult['return_msg']."<br>"; } elseif($unifiedOrderResult["result_code"] == "FAIL") { //商户自行增加处理流程 echo "错误代码:".$unifiedOrderResult['err_code']."<br>"; echo "错误代码描述:".$unifiedOrderResult['err_code_des']."<br>"; } elseif($unifiedOrderResult["code_url"] != NULL) { //从统一支付接口获取到code_url $code_url = $unifiedOrderResult["code_url"]; //商户自行增加处理流程 //...... } ?> <!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>微信安全支付</title> </head> <body> <div align="center" id="qrcode"> </div> <div align="center"> <p>订单号:<?php echo $out_trade_no; ?></p> </div> <div align="center"> <form action="./order_query.php" method="post"> <input name="out_trade_no" type='hidden' value="<?php echo $out_trade_no; ?>"> <button type="submit" >查询订单状态</button> </form> </div> <br> <div align="center"> <form action="./refund.php" method="post"> <input name="out_trade_no" type='hidden' value="<?php echo $out_trade_no; ?>"> <input name="refund_fee" type='hidden' value="1"> <button type="submit" >申请退款</button> </form> </div> <br> <div align="center"> <a href="../index.php">返回首页</a> </div> </body> <script src="./qrcode.js"></script> <script> if(<?php echo $unifiedOrderResult["code_url"] != NULL; ?>) { var url = "<?php echo $code_url;?>"; //参数1表示图像大小,取值范围1-10;参数2表示质量,取值范围'L','M','Q','H' var qr = qrcode(10, 'M'); qr.addData(url); qr.make(); var wording=document.createElement('p'); wording.innerHTML = "扫我,扫我"; var code=document.createElement('DIV'); code.innerHTML = qr.createImgTag(); var element=document.getElementById("qrcode"); element.appendChild(wording); element.appendChild(code); } </script> </html>
6. Problems in calling WxPayHelper.php
During development, the wxPayHeler.php provided by the official demo had some problems, resulting in a sign error.
You need to modify 3 when using jpapi to pay
You can check whether you need to modify it according to the version you downloaded
Post the modified code here
Congratulations~ You have the super endurance to read this stinky article -_-. If you think it is a little bit helpful to you, please don’t like it. Save that point. If you can, please visit our store (www.wsyu.com) and prepare a beautiful necklace and bracelet for your girlfriend (I always firmly believe that programmers have girlfriends!!!) Or an anklet, once she’s happy, you won’t have to masturbate at night!
Or follow our official account:
We are currently working on the WeChat store interface. Welcome to join the group: 204689062 for discussion~
I don’t really like to follow trends. While everyone has been using WeChat to send information, I still stick to the usual communication methods, phone calls, text messages and emails. This is not because I don’t accept new things, because I know that in the process of information transmission, the more intermediate links there are, the worse the security of the information. Fetion is not as good as text messages, text messages are not as good as phone calls, mobile phones are not as good as landlines, and landlines are not as good as face-to-face meetings. It is better to chat at home than in a cafe. When the government strictly requires the real-name system on the Internet, WeChat records your mobile phone number, location, and your relatives and friends. . . When all are caught in one fell swoop, any “real-name system” will pale in comparison. Something like this happened when I was using Fetion: The Fetion system recommended my ex-girlfriend’s number to my wife: You two have a common friend. After being deceived by friends, you can see that all the friends around you are using WeChat to contact you about playing games and other matters. If you don’t add WeChat, they won’t take you to play. So, I also changed my mobile phone and logged into WeChat. Unexpectedly, when I went on a date with a friend to play ball for the first time after using WeChat, I received rumors that WeChat would charge a fee. When I looked online, I found that the issue of WeChat charging has already become a hot mess: Tencent, the manufacturer of WeChat, hurriedly came out to refute the rumors; the chairman of China Mobile, who was directly impacted by WeChat, also went shirtless and talked about "WeChat and other OTT services have indeed caused Miao Wei, the competent government department and Minister of the Ministry of Industry and Information Technology, publicly stated that the Ministry of Industry and Information Technology is currently coordinating the operators' WeChat charges, and "charging fees other than data traffic is also reasonable"; official media that is consistent with the government They also found cases of foreign charges and exaggerated them; however, netizens who were accustomed to free services simply did not accept other charges other than data traffic charges. For a time, everyone was unanimously talking about "charges." Experts, whether they are charging or anti-charging, are using a lot of professional terms such as OTT (value-added services) and signaling channels to try to explain to everyone the rights and wrongs of WeChat. But apart from people in the industry who can understand these things, even I, who have been working in Beijing Postal Service for 8 years, can’t understand it. I once asked IT experts about this: You always say that WeChat occupies the signaling channel. If you think the signaling channel is congested, then use one of the other seven channels for signaling. Ridiculed by experts: Stop being a foreigner and use another channel for signaling? Wouldn't the voice be affected? ! Voice is the foundation of mobile operators! It can be seen that mobile operators have a love-hate relationship with data services. More data will inevitably impact traditional voice calls, and they are unwilling to give up traditional call traffic. Now they still stick to the voice position and ignore the general trend of data business development. If this continues, mobile operators may become the next Kodak. In fact, for WeChat's charging, there are not so many professional terms, and there is no need to find any theoretical basis or foreign experience. Whether to charge or not, and how much to charge, all depend on the game and consensus reached between the buyers and sellers providing goods and services. As far as WeChat is concerned, Tencent is the service provider, we are all users, and mobile operators are the intermediaries that deliver this service. Therefore, in this service chain, there can be three paid services: Charge 1: Tencent collects from users (seller relationship); Charge 2: Tencent pays to operators (seller intermediaries), Charge 3: Operators collect from users (Buyer's Agent). Among these three contingent charging items, the two items that are directly related to users are "Charging 1" and "Charging 3". "Charging 3" is already being collected, whether it is the total monthly subscription or calculation For traffic, users have already paid fees to the operators; for "Charge 1", Tencent has repeatedly stated that it will not charge fees at present. So, what do we as users have to worry about? What other bricks need to be thrown? Therefore, the only thing that needs to be discussed is "charge 2" - the access fee charged by operators to Tencent. Logically speaking, this charge is possible and appropriate. However, this must be done under fair conditions and without discrimination. Operators cannot only charge for Tencent’s WeChat, but must have a clear charging standard for all OTT products that operators access. That is to say, if Tencent WeChat charges fees, the same charging standards must be adopted for Skype, FeiChat, Yixin, etc. Of course, Tencent also has the right to choose not to pay for operator charges. For example, it may say no to a certain operator's charges and thus not use the network provided by that operator. In this way, since Tencent does not use the operator's network, Tencent may lose some WeChat users who use the operator's network. At the same time, the operator's data traffic business will be affected, and some For mobile phones...the rest of the text>>