search
HomeBackend DevelopmentPHP TutorialHow to implement WeChat scan code payment in PHP

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 = &#39;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789&#39;;
 $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 posts the product ID, openId and other information in the link to the script, and the script is responsible for returning the product information corresponding to the product ID.

<?php
include &#39;ArrayToXML.php&#39;;
header(&#39;Content-Type:text/xml&#39;);
/***
 * 该脚本为当公众该平台接到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, &#39;SimpleXMLElement&#39;, 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(&#39;%21&#39;=>&#39;!&#39;, &#39;%2A&#39;=>&#39;*&#39;, &#39;%27&#39;=>"&#39;", &#39;%28&#39;=>&#39;(&#39;, &#39;%29&#39;=>&#39;)&#39;);
 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 transmit important information such as product information, payment results, and the user's openId in get and post methods. Go to the link, the script receives this information, and performs shipping processing based on the payment information, and finally returns 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, &#39;SimpleXMLElement&#39;, 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 the 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 entire content of this article, I hope it will be helpful to everyone's study.


Related recommendations:

PHP implementation of back-end UnionPayDetailed explanation of payment and refund examples

QQ, WeChat and PaymentHow to use PHP to implement the three-in-one payment code

PHP to implement APP WeChat PaymentCase Analysis

The above is the detailed content of How to implement WeChat scan code payment in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

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 in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

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: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

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.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

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.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)