Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize Wechat Code scanning payment by PHP

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces how PHP realizes WeChat scanning code payment, which has certain reference value. Interested friends can refer to it. I hope you will gain a lot after reading this article. Let Xiaobian take you to understand it together.

The code contains four files: createUrl.php, ArrayToXML.php, returnGoodsUrl.php, notifyUrl.php.

Code:

createUrl.php: Create WeChat QR code payment link ```/** * @author chantrans* The function of this page is to generate product QR code link */echo createUrl("12314124");/** * Generate random string */function getNonceStr()$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz 0123456789';$noceStr = "";for ($i = 0; $i

< 32; $i++) {$noceStr .= $chars[ mt_rand(0, strlen($chars) - 1) ];}$oldNonceStr = $noceStr;return $noceStr;/*** 二维码扫码链接构造方式:* weixin://wxpay/bizpayurl?sign=XXXXX&appid=XXXXXX&productid=XXXXXX×tamp=XXXXXX&noncestr=XXXXXX*appid 是字段名称:公众号id;字段来源:商户注册具有支付权限的公众号成功后即可获得;传入方式:由商户直接传入。timestamp 是字段名称:时间戳;字段来源:商户生成从1970 年1 月1 日00:00:00 至今的秒数,即当前的时间;由商户生成后传入。取值范围:32 字符以下noncestr 是字段名称:随机字符串;字段来源:商户生成的随机字符串;取值范围:长度为32 个字符以下。由商户生成后传入。取值范围:32 字符以下productid 是字段名称:商品唯一id;字段来源:商户需要定义并维护自己的商品id,这个id 与一张订单等价,微信后台凭借该id 通过Post商户后台获取交易必须信息。由商户生成后传入。取值范围:32字符以下sign 是字段名称:签名;字段来源:对前面的其他字段与appKey 按照字典序排序后,使用SHA1 算法得到的结果。由商户生成后传入。参与sign 签名的字段包括:appid、timestamp、noncestr、productid 以及appkey。*/function createUrl($productid){$app_id = "wxbce29784bdd01454"; //公众号appid$app_key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";//公众号支付请求中用于加密的密钥Key,可验证商户唯一身份,PaySignKey对应于支付场景中的appKey值。$nonce_str =getNonceStr();$time_stamp = strtotime("now");//对所有需要传入的参数加上appkey作一次key=value字典序的排序$keyvaluestring = "appid=".$app_id."&appkey=".$app_key."&noncestr=".$nonce_str."&productid=".$productid."×tamp=".$time_stamp;$sign = sha1($keyvaluestring)."";$url = "weixin://wxpay/bizpayurl?sign=".$sign."&appid=".$app_id."&productid=".$productid."×tamp=".$time_stamp."&noncestr=".$nonce_str."";return $url;```returnGoodsUrl.php:用户扫描二维码链接后,微信将链接中的商品ID、openId以及其他信息post到该脚本,该脚本负责返回与商品ID对应的商品信息。```include 'ArrayToXML.php';/**** 该脚本为当公众该平台接到Native(原生)支付请求时,会调用此回调URL获取商品信息。*//**(1)OpenId,点击链接准备购买商品的用户openid(3)IsSubscribe,标记用户是否订阅该公众帐号,1 为关注,0 为未关注(5)TimeStamp,时间戳(7)AppSignature,参数的加密签名,是根据2.7 支付签名(paySign)生成方法中所讲的签名方式生成的签名**/$postdata = file_get_contents("php://input");$postObj = simplexml_load_string ( $postdata, 'SimpleXMLElement', LIBXML_NOCDATA );$openId = $postObj->

OpenId;$AppId = $postObj->AppId;$IsSubscribe = $postObj->IsSubscribe;$ProductId = $postObj->ProductId;$TimeStamp = $postObj->TimeStamp;$NonceStr = $postObj->NonceStr;$AppSignature = $postObj->AppSignature;$Signature Method = $postObj-> Signature Method;* Step 2, generate an order number, and store the order information, such as commodity information and user openID, in the database * */function createTradeId(){$curDateTime = date ("YmdHis");//date_default_timezone_set(PRC);$strDate = date("Ymd");$strTime = date("His");//4-digit random number $randNum = rand(1000, 9999);//10-digit sequence number, adjustable.$ strReq = $strTime . $randNum;/* Merchant's order number */$mch_vno = $curDateTime . $strReq;/** *****************//*todo Save order information to database *//** *********************/return $mch_vno;* Step 3: Generate item details pakage* @param string $body Item description * @param string $total_fee Total order amount in cents. * @param string $out_trade_no Order number inside merchant system * @return $package*/function getPackage($body,$total_fee,$out_trade_no){ $ip=$_SERVER["REMOTE_ADDR"];if($ip=="::1"|| empty($ip)){$ip="127.0.0.1";}$banktype = "WX";$fee_type = "1";//fee type, where 1 is the default RMB $input_charset = "GBK";//character set, GBK$notify_url = " www.example.com " will be uniformly used herehttp://xxxxxx.com/Wxpay/notify.html;//After successful payment, the address will be notified $out_trade_no =createTradeId();//order number, the merchant needs to ensure the uniqueness of this field for this merchant $partner = "XXXXXXXX"; //merchant number $spbill_create_ip =$ip;//order generated machine IP$partnerKey = "XXXXX";//this value is different from the above other values: signature needs it, and the final transmission string cannot contain it. This key needs to be preserved by the merchant.// First step: sign the original string, noting that no fields are encoded here. Here is the parameter dictionary sorted according to key=value to form the following string, in the last concatenation of this string key=XXXX. Because the fields here are fixed, you only need to sort them in this order.$ signString = "bank_type=".$ banktype. "&body=".$ body. "&fee_type=".$ fee_type. "&input_charset=".$ input_charset. "¬ify_url=".$ notify_url. "&out_trade_no=".$ out_trade_no. "&partner=".$ partner. "&spbill_create_ip=".$ spbill_create_ip. "&total_fee=".$ total_fee. "&key=".$ partnerKey;$md5SignValue = ("" .strtoupper(md5(($signString))));//echo $md5SignValue;//Then the second step is url transcoding each parameter.$ banktype = encodeURIComponent ($banktype);$body=encodeURIComponent($body);$fee_type=encodeURIComponent ($fee_type);$input_charset = encodeURIComponent ($input_charset);$notify_url = encodeURIComponent ($notify_url);$out_trade_no = encodeURIComponent ($out_trade_no);$partner = encodeURIComponent ($partner);$spbill_create_ip = encodeURIComponent ($spbill_create_ip);$total_fee = encodeURIComponent($total_fee);//Then go to the last step, where you sort the following strings lexicographically according to key=value except sign, and finally concatenate sign=value$completeString = "bank_type=".$ banktype. "&body=".$ body. "&fee_type=".$ fee_type. "&input_charset=".$ input_charset. "¬ify_url=".$ notify_url. "&out_trade_no=".$ out_trade_no. "&partner=".$ partner. "&spbill_create_ip=".$ spbill_create_ip. "&total_fee=".$ total_fee;$completeString = $completeString. "&sign=".$ md5SignValue;$oldPackageString = $completeString; //Remember package, so that you can use return $completeString;function encodeURIComponent($str) {$revert = array ('%21 '=>'! ', '%2A'=>'*', '%27'=>"'", '%28'=>'(', '%29'=>')');return strtr(rawurlencode($str), $revert);/** In order to return Package data, callback URL must return a return data in xml format, such as: 13697450730 For some third-party feel that the product has expired or other errors, can be reflected in RetCode and RetErrMsg, RetCode is 0 indicates correct, you can define other errors; When defining other errors, you can fill in the error message encoded by UTF8 in RetErrMsg, such as "This product has been removed from the shelf", and the client will **/$data=array.("AppId"=>$AppId,"Package"=>getPackage("Test Item",100,"201311291504302501231"),"TimeStamp"=>strtotime(),"NonceStr"=>$NonceStr,"RetCode"=>0,//RetCode = 0 indicates that it is correct, and other errors can be defined; when other errors are defined, you can fill in UTF8 encoded error prompt information in RetErrMsg, such as "This product has been removed from the shelf," and the client will directly prompt it. "RetErrMsg"=>"return correctly","AppSignature"=>$AppSignature,"SignMethod"=>"sha1"//returns the generated xml data echo ArrayToXML:: arratoxml ($data);notifyUrl.php: After the user pays for the goods, the WeChat server will pass important information such as the goods information, payment result, and user's openId to the link in the form of get and post. The script receives these information, and performs delivery processing according to the payment information. Finally, it returns to the WeChat server success to inform them that we have processed this notification. Otherwise, the WeChat server will periodically re-initiate notifications.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report