search
HomeBackend DevelopmentPHP TutorialDetailed explanation of PHP WeChat payment examples

Detailed explanation of PHP WeChat payment examples

Jun 01, 2018 pm 04:33 PM
phpExampleDetailed explanation

This article mainly introduces PHP WeChat payment examples in detail, including PHP WeChat payment source code and PHP WeChat refund source code. It has certain reference value. Interested friends can refer to it

The specific content is as follows

1.JSapi payment demo (click on WeChat client)

<?php
/**
 * JS_API支付demo
 * ====================================================
 * 在微信浏览器里面打开H5网页中执行JS调起支付。接口输入输出数据格式为JSON。
 * 成功调起支付需要三个步骤:
 * 步骤1:网页授权获取用户openid
 * 步骤2:使用统一支付接口,获取prepay_id
 * 步骤3:使用jsapi调起支付
*/
 include_once("../WxPayPubHelper/WxPayPubHelper.php");
 
 //使用jsapi接口
 $jsApi = new JsApi_pub();

 //=========步骤1:网页授权获取用户openid============
 //通过code获得openid
 if (!isset($_GET[&#39;code&#39;]))
 {
 //触发微信返回code码
 $url = $jsApi->createOauthUrlForCode(WxPayConf_pub::JS_API_CALL_URL);
 Header("Location: $url"); 
 }else
 {
 //获取code码,以获取openid
  $code = $_GET[&#39;code&#39;];
 $jsApi->setCode($code);
 $openid = $jsApi->getOpenId();
 }
 
 //=========步骤2:使用统一支付接口,获取prepay_id============
 //使用统一支付接口
 $unifiedOrder = new UnifiedOrder_pub();
 
 //设置统一支付接口参数
 //设置必填参数
 //appid已填,商户无需重复填写
 //mch_id已填,商户无需重复填写
 //noncestr已填,商户无需重复填写
 //spbill_create_ip已填,商户无需重复填写
 //sign已填,商户无需重复填写
 $unifiedOrder->setParameter("openid","$openid");//商品描述
 $unifiedOrder->setParameter("body","贡献一分钱");//商品描述
 //自定义订单号,此处仅作举例
 $timeStamp = time();
 $out_trade_no = WxPayConf_pub::APPID."$timeStamp";
 $unifiedOrder->setParameter("out_trade_no","$out_trade_no");//商户订单号 
 $unifiedOrder->setParameter("total_fee","1");//总金额
 $unifiedOrder->setParameter("notify_url",WxPayConf_pub::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();
 //echo $jsApiParameters;
?>

2. Native payment mode one demo (static link QR code scanned with WeChat)

<?php
/**
 * Native(原生)支付模式一demo
 * ====================================================
 * 模式一:商户按固定格式生成链接二维码,用户扫码后调微信
 * 会将productid和用户openid发送到商户设置的链接上,商户收到
 * 请求生成订单,调用统一支付接口下单提交到微信,微信会返回
 * 给商户prepayid。
 * 本例程对应的二维码由native_call_qrcode.php生成;
 * 本例程对应的响应服务为native_call.php;
 * 需要两者配合使用。
*/
 include_once("../WxPayPubHelper/WxPayPubHelper.php");

 //设置静态链接
 $nativeLink = new NativeLink_pub(); 
 
 //设置静态链接参数
 //设置必填参数
 //appid已填,商户无需重复填写
 //mch_id已填,商户无需重复填写
 //noncestr已填,商户无需重复填写
 //time_stamp已填,商户无需重复填写
 //sign已填,商户无需重复填写
 $product_id = WxPayConf_pub::APPID."static";//自定义商品id
 $nativeLink->setParameter("product_id","$product_id");//商品id
 //获取链接
 $product_url = $nativeLink->getUrl();

 //使用短链接转换接口
 $shortUrl = new ShortUrl_pub();
 //设置必填参数
 //appid已填,商户无需重复填写
 //mch_id已填,商户无需重复填写
 //noncestr已填,商户无需重复填写
 //sign已填,商户无需重复填写
 $shortUrl->setParameter("long_url","$product_url");//URL链接
 //获取短链接
 $codeUrl = $shortUrl->getShortUrl();
 
?>

3.native payment mode two demo (Dynamic link QR code scanned with WeChat)

 <?php
/**
 * Native(原生)支付-模式二-demo
 * ====================================================
 * 商户生成订单,先调用统一支付接口获取到code_url,
 * 此URL直接生成二维码,用户扫码后调起支付。
 * 
*/
 include_once("../WxPayPubHelper/WxPayPubHelper.php");

 //使用统一支付接口
 $unifiedOrder = new UnifiedOrder_pub();
 
 //设置统一支付接口参数
 //设置必填参数
 //appid已填,商户无需重复填写
 //mch_id已填,商户无需重复填写
 //noncestr已填,商户无需重复填写
 //spbill_create_ip已填,商户无需重复填写
 //sign已填,商户无需重复填写
 $unifiedOrder->setParameter("body","贡献一分钱");//商品描述
 //自定义订单号,此处仅作举例
 $timeStamp = time();
 $out_trade_no = WxPayConf_pub::APPID."$timeStamp";
 $unifiedOrder->setParameter("out_trade_no","$out_trade_no");//商户订单号 
 $unifiedOrder->setParameter("total_fee","1");//总金额
 $unifiedOrder->setParameter("notify_url",WxPayConf_pub::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[&#39;return_msg&#39;]."<br>";
 }
 elseif($unifiedOrderResult["result_code"] == "FAIL")
 {
 //商户自行增加处理流程
 echo "错误代码:".$unifiedOrderResult[&#39;err_code&#39;]."<br>";
 echo "错误代码描述:".$unifiedOrderResult[&#39;err_code_des&#39;]."<br>";
 }
 elseif($unifiedOrderResult["code_url"] != NULL)
 {
 //从统一支付接口获取到code_url
 $code_url = $unifiedOrderResult["code_url"];
 //商户自行增加处理流程
 //......
 }

?>

4. Payment query interface demo

<?php
/**
 * 订单查询-demo
 * ====================================================
 * 该接口提供所有微信支付订单的查询。
 * 当支付通知处理异常或丢失的情况,商户可以通过该接口查询订单支付状态。
 * 
*/
 include_once("../WxPayPubHelper/WxPayPubHelper.php");
 
 //退款的订单号
 if (!isset($_POST["out_trade_no"]))
 {
 $out_trade_no = " ";
 }else{
  $out_trade_no = $_POST["out_trade_no"];

 //使用订单查询接口
 $orderQuery = new OrderQuery_pub();
 //设置必填参数
 //appid已填,商户无需重复填写
 //mch_id已填,商户无需重复填写
 //noncestr已填,商户无需重复填写
 //sign已填,商户无需重复填写
 $orderQuery->setParameter("out_trade_no","$out_trade_no");//商户订单号 
 //非必填参数,商户可根据实际情况选填
 //$orderQuery->setParameter("sub_mch_id","XXXX");//子商户号 
 //$orderQuery->setParameter("transaction_id","XXXX");//微信订单号
 
 //获取订单查询结果
 $orderQueryResult = $orderQuery->getResult();
 
 //商户根据实际情况设置相应的处理流程,此处仅作举例
 if ($orderQueryResult["return_code"] == "FAIL") {
 echo "通信出错:".$orderQueryResult[&#39;return_msg&#39;]."<br>";
 }
 elseif($orderQueryResult["result_code"] == "FAIL"){
 echo "错误代码:".$orderQueryResult[&#39;err_code&#39;]."<br>";
 echo "错误代码描述:".$orderQueryResult[&#39;err_code_des&#39;]."<br>";
 }
 else{
 echo "交易状态:".$orderQueryResult[&#39;trade_state&#39;]."<br>";
 echo "设备号:".$orderQueryResult[&#39;device_info&#39;]."<br>";
 echo "用户标识:".$orderQueryResult[&#39;openid&#39;]."<br>";
 echo "是否关注公众账号:".$orderQueryResult[&#39;is_subscribe&#39;]."<br>";
 echo "交易类型:".$orderQueryResult[&#39;trade_type&#39;]."<br>";
 echo "付款银行:".$orderQueryResult[&#39;bank_type&#39;]."<br>";
 echo "总金额:".$orderQueryResult[&#39;total_fee&#39;]."<br>";
 echo "现金券金额:".$orderQueryResult[&#39;coupon_fee&#39;]."<br>";
 echo "货币种类:".$orderQueryResult[&#39;fee_type&#39;]."<br>";
 echo "微信支付订单号:".$orderQueryResult[&#39;transaction_id&#39;]."<br>";
 echo "商户订单号:".$orderQueryResult[&#39;out_trade_no&#39;]."<br>";
 echo "商家数据包:".$orderQueryResult[&#39;attach&#39;]."<br>";
 echo "支付完成时间:".$orderQueryResult[&#39;time_end&#39;]."<br>";
 } 
 }

 //商户自行增加处理流程
 //......
 
?>

5. Billing interface demo

<?php
/**
 * 对账单接口demo
 * ====================================================
 * 商户可以通过该接口下载历史交易清单。
*/
 include_once("../WxPayPubHelper/WxPayPubHelper.php");

 //对账单日期
 if (!isset($_POST["bill_date"])){
 $bill_date = "20140814";
 }
 else{
  $bill_date = $_POST["bill_date"];
 
 //使用对账单接口
 $downloadBill = new DownloadBill_pub();
 //设置对账单接口参数
 //设置必填参数
 //appid已填,商户无需重复填写
 //mch_id已填,商户无需重复填写
 //noncestr已填,商户无需重复填写
 //sign已填,商户无需重复填写
 $downloadBill->setParameter("bill_date","$bill_date");//对账单日期 
 $downloadBill->setParameter("bill_type","ALL");//账单类型 
 //非必填参数,商户可根据实际情况选填
 //$downloadBill->setParameter("device_info","XXXX");//设备号 
 
 //对账单接口结果
 $downloadBillResult = $downloadBill->getResult();
 echo $downloadBillResult[&#39;return_code&#39;];
 
 if ($downloadBillResult[&#39;return_code&#39;] == "FAIL") {
 echo "通信出错:".$downloadBillResult[&#39;return_msg&#39;];
 }else{
 print_r(&#39;<pre class="brush:php;toolbar:false">&#39;);
 echo "【对账单详情】"."</br>";
 print_r($downloadBill->response);
 print_r(&#39;
');  }  }   ?>

6. Refund interface demo

<?php
/**
 * 退款申请接口-demo
 * ====================================================
 * 注意:同一笔单的部分退款需要设置相同的订单号和不同的
 * out_refund_no。一笔退款失败后重新提交,要采用原来的
 * out_refund_no。总退款金额不能超过用户实际支付金额(现
 * 金券金额不能退款)。
*/

 include_once("../WxPayPubHelper/WxPayPubHelper.php");

 //输入需退款的订单号
 if (!isset($_POST["out_trade_no"]) || !isset($_POST["refund_fee"]))
 {
 $out_trade_no = " ";
 $refund_fee = "1";
 }else{
  $out_trade_no = $_POST["out_trade_no"];
  $refund_fee = $_POST["refund_fee"];
 //商户退款单号,商户自定义,此处仅作举例
 $out_refund_no = "$out_trade_no"."$time_stamp";
 //总金额需与订单号out_trade_no对应,demo中的所有订单的总金额为1分
 $total_fee = "1";
 
 //使用退款接口
 $refund = new Refund_pub();
 //设置必填参数
 //appid已填,商户无需重复填写
 //mch_id已填,商户无需重复填写
 //noncestr已填,商户无需重复填写
 //sign已填,商户无需重复填写
 $refund->setParameter("out_trade_no","$out_trade_no");//商户订单号
 $refund->setParameter("out_refund_no","$out_refund_no");//商户退款单号
 $refund->setParameter("total_fee","$total_fee");//总金额
 $refund->setParameter("refund_fee","$refund_fee");//退款金额
 $refund->setParameter("op_user_id",WxPayConf_pub::MCHID);//操作员
 //非必填参数,商户可根据实际情况选填
 //$refund->setParameter("sub_mch_id","XXXX");//子商户号 
 //$refund->setParameter("device_info","XXXX");//设备号 
 //$refund->setParameter("transaction_id","XXXX");//微信订单号
 
 //调用结果
 $refundResult = $refund->getResult();
 
 //商户根据实际情况设置相应的处理流程,此处仅作举例
 if ($refundResult["return_code"] == "FAIL") {
 echo "通信出错:".$refundResult[&#39;return_msg&#39;]."<br>";
 }
 else{
 echo "业务结果:".$refundResult[&#39;result_code&#39;]."<br>";
 echo "错误代码:".$refundResult[&#39;err_code&#39;]."<br>";
 echo "错误代码描述:".$refundResult[&#39;err_code_des&#39;]."<br>";
 echo "公众账号ID:".$refundResult[&#39;appid&#39;]."<br>";
 echo "商户号:".$refundResult[&#39;mch_id&#39;]."<br>";
 echo "子商户号:".$refundResult[&#39;sub_mch_id&#39;]."<br>";
 echo "设备号:".$refundResult[&#39;device_info&#39;]."<br>";
 echo "签名:".$refundResult[&#39;sign&#39;]."<br>";
 echo "微信订单号:".$refundResult[&#39;transaction_id&#39;]."<br>";
 echo "商户订单号:".$refundResult[&#39;out_trade_no&#39;]."<br>";
 echo "商户退款单号:".$refundResult[&#39;out_refund_no&#39;]."<br>";
 echo "微信退款单号:".$refundResult[&#39;refund_idrefund_id&#39;]."<br>";
 echo "退款渠道:".$refundResult[&#39;refund_channel&#39;]."<br>";
 echo "退款金额:".$refundResult[&#39;refund_fee&#39;]."<br>";
 echo "现金券退款金额:".$refundResult[&#39;coupon_refund_fee&#39;]."<br>";
 }
 }
 
?>

7. Refund query interface demo

<?php
/**
 * 退款申请接口-demo
 * ====================================================
 * 
 * 
*/
 include_once("../WxPayPubHelper/WxPayPubHelper.php");

 //要查询的订单号
 if (!isset($_POST["out_trade_no"]))
 {
 $out_trade_no = " ";
 }else{
  $out_trade_no = $_POST["out_trade_no"];
 
 //使用退款查询接口
 $refundQuery = new RefundQuery_pub();
 //设置必填参数
 //appid已填,商户无需重复填写
 //mch_id已填,商户无需重复填写
 //noncestr已填,商户无需重复填写
 //sign已填,商户无需重复填写
 $refundQuery->setParameter("out_trade_no","$out_trade_no");//商户订单号
 // $refundQuery->setParameter("out_refund_no","XXXX");//商户退款单号
 // $refundQuery->setParameter("refund_id","XXXX");//微信退款单号
 // $refundQuery->setParameter("transaction_id","XXXX");//微信退款单号
 //非必填参数,商户可根据实际情况选填
 //$refundQuery->setParameter("sub_mch_id","XXXX");//子商户号 
 //$refundQuery->setParameter("device_info","XXXX");//设备号 
 
 //退款查询接口结果
 $refundQueryResult = $refundQuery->getResult();
 
 //商户根据实际情况设置相应的处理流程,此处仅作举例
 if ($refundQueryResult["return_code"] == "FAIL") {
 echo "通信出错:".$refundQueryResult[&#39;return_msg&#39;]."<br>";
 }
 else{
 echo "业务结果:".$refundQueryResult[&#39;result_code&#39;]."<br>";
 echo "错误代码:".$refundQueryResult[&#39;err_code&#39;]."<br>";
 echo "错误代码描述:".$refundQueryResult[&#39;err_code_des&#39;]."<br>";
 echo "公众账号ID:".$refundQueryResult[&#39;appid&#39;]."<br>";
 echo "商户号:".$refundQueryResult[&#39;mch_id&#39;]."<br>";
 echo "子商户号:".$refundQueryResult[&#39;sub_mch_id&#39;]."<br>";
 echo "设备号:".$refundQueryResult[&#39;device_info&#39;]."<br>";
 echo "签名:".$refundQueryResult[&#39;sign&#39;]."<br>";
 echo "微信订单号:".$refundQueryResult[&#39;transaction_id&#39;]."<br>";
 echo "商户订单号:".$refundQueryResult[&#39;out_trade_no&#39;]."<br>";
 echo "退款笔数:".$refundQueryResult[&#39;refund_count&#39;]."<br>";
 echo "商户退款单号:".$refundQueryResult[&#39;out_refund_no&#39;]."<br>";
 echo "微信退款单号:".$refundQueryResult[&#39;refund_idrefund_id&#39;]."<br>";
 echo "退款渠道:".$refundQueryResult[&#39;refund_channel&#39;]."<br>";
 echo "退款金额:".$refundQueryResult[&#39;refund_fee&#39;]."<br>";
 echo "现金券退款金额:".$refundQueryResult[&#39;coupon_refund_fee&#39;]."<br>";
 echo "退款状态:".$refundQueryResult[&#39;refund_status&#39;]."<br>";
 }
 } 
?>

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

phpHow to combine redis to achieve high concurrency in posting and Weibo posts

phpHow to combine redis to achieve high concurrency in posting and posting on Weibo

Detailed explanation of the case of PHP Ajax detecting whether the network is normal

The above is the detailed content of Detailed explanation of PHP WeChat payment examples. 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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)