The function of php is very powerful. In this article, we mainly share with you the php back-end implementation of the WeChat applet payment code. The front-end: relatively simple, just make a network request on the corresponding payment event:
WeChat mini program payment backend PHP (2)
view_moneysure:function(){ var code = this.data.code; console.log('code是' +code) wx.request({ url: 'https://...com/pay.php',//这个链接是后端写的 header: { 'Content-Type': 'application/x-www-form-urlencoded' }, data: { code: code, }, method: 'POST', success: function (response) { console.log( response.data); // 发起支付 wx.requestPayment({ 'appId': response.data.appId, 'timeStamp': response.data.timeStamp, 'nonceStr': response.data.nonceStr, 'package': response.data.package, 'signType': 'MD5', 'paySign': response.data.paySign, 'success': function (res) { wx.showToast({ title: '支付成功' }); console.log(res); }, 'fail': function (res) { console.log(res) } }); }, fail: function (res) { console.log(res) } }) },
Backend code:
1. pay.php //Backend address requested by the mini program
<?php /** * Created by PhpStorm. * User: UFO * Date: 17/7/18 * Time: 下午5:31 */ require_once ('WxPay.Api.php'); class WXPay { function index() { // 初始化值对象 $input = new WxPayUnifiedOrder(); // 文档提及的参数规范:商家名称-销售商品类目 $input->SetBody("testceshi"); // 订单号应该是由小程序端传给服务端的,在用户下单时即生成,demo中取值是一个生成的时间戳 $input->SetOut_trade_no(time().''); // 费用应该是由小程序端传给服务端的,在用户下单时告知服务端应付金额,demo中取值是1,即1分钱 $input->SetTotal_fee("1"); $input->SetNotify_url("https://...com/notify.php");//需要自己写的notify.php $input->SetTrade_type("JSAPI"); // 由小程序端传给后端或者后端自己获取,写自己获取到的, $input->SetOpenid('UdhncondJcnkJnjknkcssdcAbckn'); //$input->SetOpenid($this->getSession()->openid); // 向微信统一下单,并返回order,它是一个array数组 $order = WxPayApi::unifiedOrder($input); // json化返回给小程序端 header("Content-Type: application/json"); echo $this->getJsApiParameters($order); } private function getJsApiParameters($UnifiedOrderResult) { //判断是否统一下单返回了prepay_id if(!array_key_exists("appid", $UnifiedOrderResult) || !array_key_exists("prepay_id", $UnifiedOrderResult) || $UnifiedOrderResult['prepay_id'] == "") { throw new WxPayException("参数错误"); } $jsapi = new WxPayJsApiPay(); $jsapi->SetAppid($UnifiedOrderResult["appid"]); $timeStamp = time(); $jsapi->SetTimeStamp("$timeStamp"); $jsapi->SetNonceStr(WxPayApi::getNonceStr()); $jsapi->SetPackage("prepay_id=" . $UnifiedOrderResult['prepay_id']); $jsapi->SetSignType("MD5"); $jsapi->SetPaySign($jsapi->MakeSign()); $parameters = json_encode($jsapi->GetValues()); return $parameters; } //这里是服务器端获取openid的函数 // private function getSession() { // $code = $this->input->post('code'); // $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.WxPayConfig::APPID.'&secret='.WxPayConfig::APPSECRET.'&js_code='.$code.'&grant_type=authorization_code'; // $response = json_decode(file_get_contents($url)); // return $response; // } } $WxPay = new WXPay(); $WxPay->index();
2. WeChat SDK download link: https://pay.weixin.qq.com/wiki/doc/api/download/WxpayAPI_php_v3.zip
Unzip and you can see it in the lib folder:
Place it in a directory accessible to the server.
Configure the account information in WxPayConfig.php:
class WxPayConfig { //=======【基本信息设置】===================================== // /** * TODO: 修改这里配置为您自己申请的商户信息 * 微信公众号信息配置 * * APPID:绑定支付的APPID(必须配置,开户邮件中可查看) * * MCHID:商户号(必须配置,开户邮件中可查看) * * KEY:商户支付密钥,参考开户邮件设置(必须配置,登录商户平台自行设置) * 设置地址:https://pay.weixin.qq.com/index.php/account/api_cert * * APPSECRET:公众帐号secert(仅JSAPI支付的时候需要配置, 登录公众平台,进入开发者中心可设置), * 获取地址:https://mp.weixin.qq.com/advanced/advanced?action=dev&t=advanced/dev&token=2005451881&lang=zh_CN * @var string */ const APPID = 'wx123456789...';//这里填上自己的对应信息 const MCHID = '14151666888'; const KEY = '11223344556677889900'; const APPSECRET = '828bfsdibfsiubfikdbfik'; const NOTIFY_URL='https://...com/notify.php';
Note:
encountered a signature error during the period, which has been bad. Use the WeChat payment interface signature verification tool to verify There is nothing wrong with the verification. As mentioned on the Internet, I have checked all the omitted and wrongly written parameters, but it keeps returning
<return_code><![CDATA[FAIL]]></return_code>
<return_msg></return_msg>
这样的信息,最后解决办法是:重置了KEY (商户支付密钥),重置的和之前的一模一样,但竟然就可以了...
. The main problems are signature errors. Just check carefully. For example, the XML format is incorrect, and the MD5 encrypted Number of digits, dictionary sorting is not arranged properly, parameters are missing, etc...
https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=9_1&index=1
3. Finally, attach notify.php
<?php /** * Created by PhpStorm. * User: UFO * Date: 17/7/13 * Time: 下午6:42 */ require_once ('WxPay.Api.php'); require_once ('WxPay.Notify.php'); class PayNotifyCallBack extends WxPayNotify { //查询订单 public function Queryorder($transaction_id) { $input = new WxPayOrderQuery(); $input->SetTransaction_id($transaction_id); $result = WxPayApi::orderQuery($input); 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; } //重写回调处理函数 public function NotifyProcess($data, &$msg) { $notfiyOutput = array(); if(!array_key_exists("transaction_id", $data)){ $msg = "输入参数不正确"; return false; } //查询订单,判断订单真实性 if(!$this->Queryorder($data["transaction_id"])){ $msg = "订单查询失败"; return false; } return true; } } $notify = new PayNotifyCallBack(); $notify->Handle(false);
Welcome to leave a message to exchange corrections!
Related recommendations:
PHP implementation app to evoke Alipay payment code
##Development example of PHP UnionPay online payment interface
Realize WeChat scan code payment php code sharing
The above is the detailed content of PHP implements WeChat applet payment code sharing. For more information, please follow other related articles on the PHP Chinese website!

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 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.

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 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.

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

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.


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

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.

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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.

Atom editor mac version download
The most popular open source editor