PHP WeChat development: How to implement JSAPI payment
May 13, 2023 pm 07:21 PMWith the development of mobile Internet, WeChat has become an indispensable part of people's lives, and more and more merchants choose to conduct business on the WeChat platform. Implementing WeChat payment function is very necessary for merchants. This article will introduce how to use PHP to implement JSAPI payment.
First of all, we need to understand what JSAPI payment is. JSAPI is a kind of payment function of WeChat official account. It calls WeChat payment interface through JS to realize payment. The advantage of JSAPI payment is that users only need to pay in WeChat without jumping to other pages, which is more convenient.
Next, we need to make some preparations:
- Register a WeChat merchant platform account and complete real-name authentication
- Create a WeChat official account and complete official account authentication
- Get the application ID (APPID) and merchant number (MCHID) of WeChat payment
- Generate APISecret key
After completing the above preparations, we need to download WeChat Unification For the PHP SDK of the payment API, you can search for "wechatpay-GuzzleHttp" on GitHub, download it and put it in the root directory of the project.
Next, we need to write PHP code to implement JSAPI payment. First, you need to introduce the file:
require_once 'wechatpay-GuzzleHttp/autoload.php'; use WeChatPayGuzzleMiddlewareUtilPemUtil; use WeChatPayGuzzleMiddlewareWeChatPayMiddleware; use GuzzleHttpClient; use GuzzleHttpHandlerStack;
Then, you need to set the relevant parameters and create the GuzzleHttpClient object:
// 設(shè)置相關(guān)參數(shù) $appid = "xxxxxxxxx"; // 微信支付的應(yīng)用ID(APPID) $mchid = "xxxxxxxxx"; // 商戶號(MCHID) $apiKey = "xxxxxxxxx"; // APISecret密鑰 $notifyUrl = "http://example.com/notify.php"; // 異步通知URL // 創(chuàng)建GuzzleHttpClient對象 $stack = HandlerStack::create(); $privateKey = PemUtil::loadPrivateKey('file://path/to/your/key.pem'); // 加載私鑰文件 $wechatpayMiddleware = WeChatPayMiddleware::builder() ->withMerchant($appid, $mchid, $apiKey) ->withNotifyUrl($notifyUrl) ->withKey($privateKey) ->build(); $stack->push($wechatpayMiddleware, 'wechatpay'); $client = new Client(['handler' => $stack, 'verify' => false]);
In the above code, we use a third-party PHP library "wechatpay-GuzzleHttp", It encapsulates the WeChat payment API and implements request and response processing through middleware.
Then, we need to write code to obtain the user's openid:
// 獲取用戶的openid $code = $_GET['code']; // 通過微信OAuth2.0授權(quán)獲取的code $accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$secret}&code={$code}&grant_type=authorization_code"; $accessTokenResponse = $client->get($accessTokenUrl); $accessTokenBody = $accessTokenResponse->getBody()->getContents(); $accessToken = json_decode($accessTokenBody, true)['access_token']; $openid = json_decode($accessTokenBody, true)['openid'];
In the above code, we obtain the user's access_token and openid through OAuth2.0 authorization, which will be used in the subsequent payment process. openid.
Finally, we need to write the JSAPI payment code:
// 支付 $request = $client->request('POST', 'https://api.mch.weixin.qq.com/pay/unifiedorder', [ 'xml' => [ 'body' => '商品描述', 'out_trade_no' => '商戶訂單號', 'fee_type' => 'CNY', 'total_fee' => '1', 'spbill_create_ip' => $_SERVER['REMOTE_ADDR'], 'notify_url' => $notifyUrl, 'trade_type' => 'JSAPI', 'openid' => $openid, 'sign_type' => 'MD5', 'nonce_str' => uniqid(), 'appid' => $appid, 'mch_id' => $mchid, ], ]); $response = $request->getBody()->getContents(); $xml = simplexml_load_string($response, 'SimpleXMLElement', LIBXML_NOCDATA); $resultCode = json_decode(json_encode($xml), true)['result_code']; if ($resultCode == 'SUCCESS') { $prepayId = json_decode(json_encode($xml), true)['prepay_id']; $jsapiConfig = [ 'appId' => $appid, 'timestamp' => time(), 'nonceStr' => uniqid(), 'package' => "prepay_id={$prepayId}", 'signType' => 'MD5', ]; $jsapiConfig['paySign'] = sign($jsapiConfig, $apiKey); // 生成簽名 $jsapiConfig['debug'] = true; // 開啟調(diào)試模式 $jsapiConfigJson = json_encode($jsapiConfig); $jsapi = <<<EOF <script> wx.config({}); // 微信JS-SDK配置 wx.ready(function() { wx.chooseWXPay({ timestamp: '{$jsapiConfig['timestamp']}', nonceStr: '{$jsapiConfig['nonceStr']}', package: '{$jsapiConfig['package']}', signType: '{$jsapiConfig['signType']}', paySign: '{$jsapiConfig['paySign']}', success: function(res) { // 支付成功調(diào)用的函數(shù) }, fail: function(res) { // 支付失敗調(diào)用的函數(shù) } }); }); </script> EOF; echo $jsapi; // 輸出JSAPI支付代碼 } // 生成簽名 function sign($data, $apiKey) { ksort($data); $query = urldecode(http_build_query($data) . "&key={$apiKey}"); return strtoupper(md5($query)); }
In the above code, we use the "chooseWXPay" function in WeChat JS-SDK to implement the payment function. Specifically, we obtain the prepayment transaction session ID (prepay_id) by calling the WeChat Pay unified order API, and then pass the generated jsapi parameters into the chooseWXPay function to call up the WeChat payment interface for payment.
So far, we have successfully implemented JSAPI payment. To summarize, the following steps need to be completed to implement JSAPI payment:
- Register a WeChat merchant platform account and complete real-name authentication
- Create a WeChat official account and complete official account authentication
- Obtain the application ID (APPID) and merchant number (MCHID) of WeChat payment
- Generate APISecret key
- Download the PHP SDK of WeChat unified payment API and introduce relevant files
- Get The user's openid
- Calling the WeChat payment unified ordering API to generate the prepayment transaction session ID (prepay_id)
- Calling up the WeChat payment interface through the chooseWXPay function
Hope this article The introduction can help PHP developers quickly implement JSAPI payment functions.
The above is the detailed content of PHP WeChat development: How to implement JSAPI payment. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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)

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

Realizing love animation effects through Java code In the field of programming, animation effects are very common and popular. Various animation effects can be achieved through Java code, one of which is the heart animation effect. This article will introduce how to use Java code to achieve this effect and give specific code examples. The key to realizing the heart animation effect is to draw the heart-shaped pattern and achieve the animation effect by changing the position and color of the heart shape. Here is the code for a simple example: importjavax.swing.

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

PHP Game Requirements Implementation Guide With the popularity and development of the Internet, the web game market is becoming more and more popular. Many developers hope to use the PHP language to develop their own web games, and implementing game requirements is a key step. This article will introduce how to use PHP language to implement common game requirements and provide specific code examples. 1. Create game characters In web games, game characters are a very important element. We need to define the attributes of the game character, such as name, level, experience value, etc., and provide methods to operate these

"Development Suggestions: How to Use the ThinkPHP Framework to Implement Asynchronous Tasks" With the rapid development of Internet technology, Web applications have increasingly higher requirements for handling a large number of concurrent requests and complex business logic. In order to improve system performance and user experience, developers often consider using asynchronous tasks to perform some time-consuming operations, such as sending emails, processing file uploads, generating reports, etc. In the field of PHP, the ThinkPHP framework, as a popular development framework, provides some convenient ways to implement asynchronous tasks.

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

Implementing the sliding delete function in WeChat mini programs requires specific code examples. With the popularity of WeChat mini programs, developers often encounter problems in implementing some common functions during the development process. Among them, the sliding delete function is a common and commonly used functional requirement. This article will introduce in detail how to implement the sliding delete function in the WeChat applet and give specific code examples. 1. Requirements analysis In the WeChat mini program, the implementation of the sliding deletion function involves the following points: List display: To display a list that can be slid and deleted, each list item needs to include
