


PHP: Things related to the development of WeChat payment service providers
Project background
It is not a big project. We use WeChat service provider to manage multiple sub-merchant, and use the service provider’s interface to replace the sub-merchant. Only after placing an order can the service provider's background receive a callback.
The usage scenario is web scan code payment
Preparation
The domain name should belong to the service provider Set the "webpage authorized domain name" in the official account (I wonder if this operation is required?)
Set the callback address in the payment service provider's background (sub-merchant should not need to set it)
Project use apache php is the background service, download the official paid php demo (native)
We will play directly according to the directory structure of the demo, and directly put the decompressed example and lib directories into the server root directory
In the example directory, create the cert directory, go to the service provider's backend-account center-api security, download the certificate, and put it in this directory
In the example directory, create the logs directory for WeChat payment Log class writes log files
Since WeChat payment requires https, check the access log in the logs directory under the apache directory, the ssl_request.txt file, and at the bottom, you can see whether the callback address has been requested
Note
The official demo has two ways to scan the QR code to pay. The first method is no longer available, so the second one is used.
The official demo , there will be a bug that cannot display the QR code. The example page is native.php
print print_r($result); This will display errors, mainly about curl errors, which can be solved by Baidu yourself
Configuration
Add a public method to the interface object in WxPay.Config.Interface.php public abstract function GetSubMchId(); //Get the sub-merchant id in WxPay.Config In .php, configure the required parameters, use Baidu by yourself, and add a method public function GetSubMchId(){ return '8888888888'; //Return the sub-merchant number by vbyzc } In lib/WxPay.Api.php, under the unified In the single method unifiedOrder, add $inputObj->SetSub_mch_id($config->GetSubMchId());//Sub-merchant number by vbyzc in each place where the order needs to be queried, and the payment page will be called back in real time This method must be used to set the sub-merchant id on the request page that detects the order payment status:
$input->SetSub_mch_id($config->GetSubMchId()); Note that there may be no $config object in some places. Please introduce WxPay.Config.php and initialize: $config = new WxPayConfig();
Part of the code
Scan code page: native.php
<?php /** * * example目录下为简单的支付样例,仅能用于搭建快速体验微信支付使用 * 样例的作用仅限于指导如何使用sdk,在安全上面仅做了简单处理, 复制使用样例代码时请慎重 * 请勿直接直接使用样例对外提供服务 * **/ require_once "../lib/WxPay.Api.php"; require_once "WxPay.NativePay.php"; require_once 'log.php'; //初始化日志 $logHandler= new CLogFileHandler("logs/".date('Y-m-d').'.log'); $log = Log::Init($logHandler, 15); //模式一 //官方不再提供模式一支付方式 $notify = new NativePay(); //模式二 /** * 流程: * 1、调用统一下单,取得code_url,生成二维码 * 2、用户扫描二维码,进行支付 * 3、支付完成之后,微信服务器会通知支付成功 * 4、在支付成功通知中需要查单确认是否真正支付成功(见:notify.php) */ $out_trade_no = "vbyzc_for_jstx".date("YmdHis"); $input = new WxPayUnifiedOrder(); $input->SetBody("test_body"); $input->SetAttach("test_Attach");//成功支付的回调里会返回这个 $input->SetOut_trade_no($out_trade_no);//自定义订单号 $input->SetTotal_fee("1"); // 金额 $input->SetTime_start(date("YmdHis")); // $input->SetTime_expire(date("YmdHis", time() + 500)); $input->SetGoods_tag("test_goodsTag"); $input->SetNotify_url("https://service.ktfqs.com/example/wx_pay_callback.php"); $input->SetTrade_type("NATIVE"); $input->SetProduct_id("123456789"); //此id为二维码中包含的商品ID,商户自行定义。 $result = $notify->GetPayUrl($input); $url2 = $result["code_url"]; echo "<div>这是返回:$url2</div>"; print_r($result); ?> <html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>扫码支付</title> <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script> </head> <body> <div style="margin-left: 10px;color:#556B2F;font-size:30px;font-weight: bolder;">扫描支付模式二</div><br/> <div> 订单编号<input id="out_trade_no" type="hidden" value="<?php echo $out_trade_no;?>"> </div> <img src="/static/imghwm/default1.png" data-src="qrcode.php?data=<?php echo urlencode($url2);? alt="PHP: Things related to the development of WeChat payment service providers" >" class="lazy" alt="模式二扫码支付" style="max-width:90%"/> <div>支付提示:<span id="query_result" style="color: red">WAITING...</span></div> <script> var t1; var sum=0; $(document).ready(function () { t1=setInterval("ajaxstatus()", 4000); }); function ajaxstatus() { sum++; if(sum>100){ window.clearInterval(t1);return false;} if ($("#out_trade_no").val() != 0) { $.post("orderqueryajax.php", { out_trade_no:$("#out_trade_no").val() }, function (data) { data = $.trim(data); $("#query_result").html(data); if (data=="SUCCESS") { $("#query_result").html("哈哈哈!!支付成功,即将跳转..."); window.clearInterval(t1) <?php // 插入php代码 /* if (isset($_POST['history_go']) && $_POST['history_go'] == 3){ echo 'window.setTimeout("history.go(-3);",2000);'; }else{ echo 'window.setTimeout("history.go(-2);",2000);'; } */ ?> } }); } } </script> </body> </html>
Query and return the order status page: orderqueryajax.php
<?php /** * * ajax异步查询订单是否完成 * **/ require_once "../lib/WxPay.Api.php"; require_once 'log.php'; require_once "WxPay.Config.php"; //初始化日志 $logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log'); $log = Log::Init($logHandler, 15); $v = $_POST["out_trade_no"]; if(isset($v) && $v != ""){ $out_trade_no = $v; $config = new WxPayConfig(); $input = new WxPayOrderQuery(); $input->SetOut_trade_no($out_trade_no); $input->SetSub_mch_id($config->GetSubMchId());//子商户号 by vbyzc $result = WxPayApi::orderQuery($config, $input); if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){//返回查询结果 echo $result['trade_state']; }else{ echo "FAIL"; } } ?>
Callback page: notify.php
<?php date_default_timezone_set('PRC'); /** * * example目录下为简单的支付样例,仅能用于搭建快速体验微信支付使用 * 样例的作用仅限于指导如何使用sdk,在安全上面仅做了简单处理, 复制使用样例代码时请慎重 * 请勿直接直接使用样例对外提供服务 * **/ // 链接数据库 include_once('../include/conn_db.php'); include_once('../include/db_class.php'); mysql_connect(HOST,NAME,PASS) or die(mysql_error()); mysql_select_db(DBNAME); mysql_query('SET NAMES '.CODEPAGE); require_once "../lib/WxPay.Api.php"; require_once '../lib/WxPay.Notify.php'; require_once "WxPay.Config.php"; require_once 'log.php'; //初始化日志 $logHandler= new CLogFileHandler("logs/".date('Y-m-d').'.log'); $log = Log::Init($logHandler, 15); class PayNotifyCallBack extends WxPayNotify { //查询订单 public function Queryorder($transaction_id) { $input = new WxPayOrderQuery(); $config = new WxPayConfig(); $input->SetTransaction_id($transaction_id); $input->SetSub_mch_id($config->GetSubMchId()); //设置子商户号 by vbyzc $result = WxPayApi::orderQuery($config, $input); Log::DEBUG("query:" . json_encode($result)); if(array_key_exists("return_code", $result) && array_key_exists("result_code", $result) && $result["return_code"] == "SUCCESS" && $result["result_code"] == "SUCCESS") { return true; } return false; } /** * * 回包前的回调方法 * 业务可以继承该方法,打印日志方便定位 * @param string $xmlData 返回的xml参数 * **/ public function LogAfterProcess($xmlData) { Log::DEBUG("call back, return xml:" . $xmlData); return; } //重写回调处理函数 /** * @param WxPayNotifyResults $data 回调解释出的参数 * @param WxPayConfigInterface $config * @param string $msg 如果回调处理失败,可以将错误信息输出到该方法 * @return true回调出来完成不需要继续回调,false回调处理未完成需要继续回调 */ public function NotifyProcess($objData, $config, &$msg) { $data = $objData->GetValues(); //TODO 1、进行参数校验 if(!array_key_exists("return_code", $data) ||(array_key_exists("return_code", $data) && $data['return_code'] != "SUCCESS")) { //TODO失败,不是支付成功的通知 //如果有需要可以做失败时候的一些清理处理,并且做一些监控 $msg = "异常异常"; return false; } if(!array_key_exists("transaction_id", $data)){ $msg = "输入参数不正确"; return false; } //TODO 2、进行签名验证 try { $checkResult = $objData->CheckSign($config); if($checkResult == false){ //签名错误 Log::ERROR("签名错误..."); return false; } } catch(Exception $e) { Log::ERROR(json_encode($e)); } //TODO 3、处理业务逻辑 Log::DEBUG("call back JSON:" . json_encode($data)); $notfiyOutput = array(); /* 返回的格式 { "appid": "wxa664cef2fee1b641", //调用接口提交的公众账号ID "attach": "test",//附加数据,在查询API和支付通知中原样返回,该字段主要用于商户携带订单的自定义数据 (使用SetAttach设置的) "bank_type": "LQT",//不知什么鬼东西 "cash_fee": "1",// 金额 "fee_type": "CNY",//货币类型 "is_subscribe": "N",//不知什么鬼东西 "mch_id": "154133502151",// 商户号(服务商) "nonce_str": "jw0bvddz275qyvxnpdfoaam55h3dw6uk",//微信返回的随机字符串 "openid": "opnVE5pDPx2hWAoLLxyQW5KQt8GA",// 用户openid(应该是对于绑定的公从号) "out_trade_no": "vbyzc_for_jstx20190701010509",// 发起订单时自定义订单号 "result_code": "SUCCESS",// 业务结果 "return_code": "SUCCESS",// 此字段是通信标识,非交易标识,交易是否成功需要查看result_code来判断 "sign": "80E46C6CC50C25E6B5099AE4E03DA3C6FEFD5B172A99B03A56FAC4A9E11EC8F3",// "sub_mch_id": "154172463171",// 子商户id "time_end": "20190701090530",// 交易结束时间?? "total_fee": "1",// 总金额 "trade_type": "NATIVE",// 支付方式 "transaction_id": "4200000301201907011310094985" // 微信支付单号 } */ //查询订单,判断订单真实性 if(!$this->Queryorder($data["transaction_id"])){ $msg = "订单查询失败"; Log::DEBUG("vbyzc run to here : order querySelect faild!!!!!" ); return false; } // 根据微信官方原代码的业务流程,应该是如下: // 支会成功后微信会不断请求回调,在上面的代码 应该是包函了回调回应的代码, // 如果成功回应,微信支付应该就停止请求回调,才能执行下面的代码 Log::DEBUG("vbyzc run to here :<<<<<<<<<<<<<<start to mysql record" ); $openid = $data['openid'];// 微信用户 $trade_no = $data['transaction_id'];// 微信支付单号 $mch_id = $data['mch_id'];// 商户号 $sub_mch_id = $data['sub_mch_id'];// 子商户id $trade_status = $data['result_code'];// 业务结果 $total_amount = $data['total_fee'];// 总金额 $out_trade_no = $data['out_trade_no'];// 商户自定义订单号 $cmd = "insert into myorder(openid,trade_no,mch_id,sub_mch_id,trade_status,total_amount,out_trade_no,datetime) values ('$openid','$trade_no','$mch_id','$sub_mch_id','$trade_status',$total_amount,'$out_trade_no',NOW())"; mysql_query($cmd); Log::DEBUG("vbyzc run to here :end to mysql record>>>>>>>>>>" ); return true; } } $config = new WxPayConfig(); Log::DEBUG("begin notify"); $notify = new PayNotifyCallBack(); $notify->Handle($config, false); ?>
For more PHP related technical articles, please visit PHP Tutorial Column for learning!
The above is the detailed content of PHP: Things related to the development of WeChat payment service providers. For more information, please follow other related articles on the PHP Chinese website!

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.

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft