


Sample code sharing for php to implement WeChat scan code payment
Recently I scanned the QR code on the WeChat web page to pay, but I was confused when I read the official documents. In fact, it is very simple to scan the QR code to pay, but it is very troublesome to point to the official website. I think if there is an example, it will be much easier. Let me share an example with you
The code contains four files createUrl.php, ArrayToXML.php, returnGoodsUrl.php, notifyUrl.php.
createUrl.php: Create a WeChat QR code payment link
<?php /** * @author chantrans * 本页面的作用是生成商品二维码链接 */ //测试 echo createUrl("12314124"); /** * 产生随机字符串 */ function getNonceStr() { $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; $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: After the user scans the QR code link, WeChat will store the product ID, openId and other information in the link The information is posted to this script, which is responsible for returning the product information corresponding to the product ID.
<?php include 'ArrayToXML.php'; header('Content-Type:text/xml'); /*** * 该脚本为当公众该平台接到Native(原生)支付请求时,会调用此回调URL获取商品信息。 */ /** 第一步:接收微信服务器post过来的信息 (1)OpenId,点击链接准备购买商品的用户openid (2)AppId,公众帐号的appid (3)IsSubscribe,标记用户是否订阅该公众帐号,1 为关注,0 为未关注 (4)ProductId,第三方的商品ID号 (5)TimeStamp,时间戳 (6)NonceStr,随机串 (7)AppSignature,参数的加密签名,是根据2.7 支付签名(paySign)生成方法中所讲的签名方式生成的签名 (8)SignMethod,签名方式,目前只支持“SHA1”。该字段不参与签名 **/ $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; $SignMethod = $postObj->SignMethod; /** * 第二步,生成订单号,并且和商品信息,用户openID等订单信息保存在数据库中 * */ function createTradeId(){ $curDateTime = date("YmdHis"); //date_default_timezone_set(PRC); $strDate = date("Ymd"); $strTime = date("His"); //4位随机数 $randNum = rand(1000, 9999); //10位序列号,可以自行调整。 $strReq = $strTime . $randNum; /* 商家的定单号 */ $mch_vno = $curDateTime . $strReq; /********************/ /*todo 保存订单信息到数据库中*/ /********************/ return $mch_vno; } /** * 第三步:生成商品详情pakage * @param string $body 商品描述 * @param string $total_fee 订单总金额,单位为分。 * @param string $out_trade_no 商户系统内部的订单号 * @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";//费用类型,这里1为默认的人民币 $input_charset = "GBK";//字符集,这里将统一使用GBK $notify_url = "http://xxxxxx.com/Wxpay/notify.html";//支付成功后将通知该地址 $out_trade_no =createTradeId();//订单号,商户需要保证该字段对于本商户的唯一性 $partner = "XXXXXXXX"; //商户号 $spbill_create_ip =$ip;//订单生成的机器IP $partnerKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXX";//这个值和以上其他值不一样是:签名需要它,而最后组成的传输字符串不能含有它。这个key是需要商户好好保存的。 //首先第一步:对原串进行签名,注意这里不要对任何字段进行编码。这里是将参数按照key=value进行字典排序后组成下面的字符串,在这个字符串最后拼接上key=XXXX。 由于这里的字段固定,因此只需要按照这个顺序进行排序即可。 $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; //然后第二步,对每个参数进行url转码。 $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); //然后进行最后一步,这里按照key=value除了sign外进行字典序排序后组成下列的字符串,最后再串接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; //记住package,方便最后进行整体签名时取用 return $completeString; } //模拟js中的encodeURIComponent方法 function encodeURIComponent($str) { $revert = array('%21'=>'!', '%2A'=>'*', '%27'=>"'", '%28'=>'(', '%29'=>')'); return strtr(rawurlencode($str), $revert); } /** 第四步: 为了返回Package 数据,回调URL 必须返回一个xml 格式的返回数据,形如: <xml> <AppId><![CDATA[wwwwb4f85f3a797777]]></AppId> <Package><![CDATA[a=1&url=http%3A%2F%2Fwww.qq.com]]></Package> <TimeStamp> 1369745073</TimeStamp> <NonceStr><![CDATA[iuytxA0cH6PyTAVISB28]]></NonceStr> <RetCode>0</RetCode> <RetErrMsg><![CDATA[ok]]></ RetErrMsg> <AppSignature><![CDATA[53cca9d47b883bd4a5c85a9300df3da0cb48565c]]> </AppSignature> <SignMethod><![CDATA[sha1]]></ SignMethod > </xml> 对于一些第三方觉得商品已经过期或者其他错误的情况,可以在RetCode 和 RetErrMsg 中体现出来,RetCode 为0 表明正确,可以定义其他错误;当定义其他错误时, 可以在RetErrMsg 中填上UTF8 编码的错误提示信息,比如“该商品已经下架”,客户端会 直接提示出来。 **/ $data=array( "AppId"=>$AppId, "Package"=>getPackage("测试商品",100,"201311291504302501231"), "TimeStamp"=>strtotime(), "NonceStr"=>$NonceStr, "RetCode"=>0, //RetCode 为0 表明正确,可以定义其他错误;当定义其他错误时,可以在RetErrMsg 中填上UTF8 编码的错误提示信息, 比如“该商品已经下架”,客户端会直接提示出来。 "RetErrMsg"=>"正确返回", "AppSignature"=>$AppSignature, "SignMethod"=>"sha1" ); //返回生成的xml数据 echo ArrayToXML::arrtoxml($data);
notifyUrl.php: After the user pays for the product, the WeChat server will transfer important information such as product information, payment results, and the user's openId to the link in get and post methods. The script receives this information and Do the shipping process based on the payment information, and finally return it to the WeChat server success to inform them that we have processed this notification. Otherwise, the WeChat server will re-initiate notifications periodically.
<? /** 后台通知通过请求中的notify_url 进行,采用post 机制。返回通知中的参数一致,url包含如下内容: 见【微信公众号支付】公众号支付接口文档V2.2.pdf 中通知接口部分 同时,在postData 中还将包含xml 数据。数据如下: <xml> <OpenId><![CDATA[111222]]></OpenId> <AppId><![CDATA[wwwwb4f85f3a797777]]></AppId> <IsSubscribe>1</IsSubscribe> <TimeStamp> 1369743511</TimeStamp> <NonceStr><![CDATA[jALldRTHAFd5Tgs5]]></NonceStr> <AppSignature><![CDATA[bafe07f060f22dcda0bfdb4b5ff756f973aecffa]]> </AppSignature> <SignMethod><![CDATA[sha1]]></ SignMethod > </xml> 商户需要对这些参数进行保存和判断用户的支付状态 */ // 获取微信通知接口postData信息 $postdata = file_get_contents("php://input"); $postObj = simplexml_load_string ( $postdata, 'SimpleXMLElement', LIBXML_NOCDATA ); $trade_state =$_GET ["trade_state"];//支付状态 $out_trade_no = $_GET ["out_trade_no"];//订单号 /***************** Todo 还有很多其他参数需要保存起来,参数列表详见文档 **************************/ if($trade_state==0){ echo "success"; }else{ echo "false"; }
ArrayToXML.php: The function of this script is to convert array into xml.
<?php class ArrayToXML { /** * @param array $arr * @return string XML */ public static function arrtoxml($arr,$dom=0,$item=0) { if (!$dom){ $dom = new DOMDocument("1.0"); } if(!$item){ $item = $dom->createElement("xml"); $dom->appendChild($item); } foreach ($arr as $key=>$val){ $itemx = $dom->createElement(is_string($key)?$key:"item"); $item->appendChild($itemx); if (!is_array($val)){ $text = $dom->createTextNode($val); $itemx->appendChild($text); }else { self::arrtoxml($val,$dom,$itemx); } } return $dom->saveXML(); } }
The above is the detailed content of Sample code sharing for php to implement WeChat scan code payment. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.
