Home Backend Development PHP Tutorial How to use PHP to develop the payment function of WeChat official account

How to use PHP to develop the payment function of WeChat official account

Oct 27, 2023 am 10:57 AM
WeChat public account php development Payment function

How to use PHP to develop the payment function of WeChat official account

How to use PHP to develop the payment function of WeChat official account

With the rapid development of mobile payment, WeChat payment, as one of the most mainstream payment methods in China, has become A necessary payment method for many businesses and individuals. When developing a WeChat public account, if the payment function can be integrated, it will provide users with a more convenient payment method and bring more benefits to the enterprise. This article will introduce how to use PHP to develop the payment function of WeChat official accounts and provide specific code examples.

First of all, we need to understand the basic process of WeChat official account payment. It is mainly divided into the following steps:

  1. The user initiates a payment request in the WeChat official account.
  2. The official account sends the payment request to the WeChat payment platform.
  3. The WeChat payment platform returns the prepayment transaction session ID (prepay_id).
  4. The public account uses prepay_id to generate a signature and returns it to the front end.
  5. The front-end calls up the WeChat payment interface, and the user completes the payment operation.
  6. The WeChat payment platform sends payment result notifications to the public account.
  7. The official account verifies the validity of the notification and processes the payment results.

Next, we will implement the specific code for these steps.

The first step is for the user to initiate a payment request in the WeChat official account. We need to add a payment button to the front-end interface and trigger a payment request when the button is clicked. The specific code is as follows:

<button id="payBtn">支付</button>
<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
<script>
    document.getElementById('payBtn').addEventListener('click', function() {
        // 调用后端接口获取支付参数
        fetch('/getPayParams.php', {
            method: 'GET'
        })
        .then(response => response.json())
        .then(data => {
            // 调起微信支付界面
            wx.chooseWXPay({
                appId: data.appId,
                timestamp: data.timestamp,
                nonceStr: data.nonceStr,
                package: data.package,
                signType: data.signType,
                paySign: data.paySign,
                success: function(res) {
                    // 支付成功后的操作
                },
                cancel: function(res) {
                    // 用户取消支付
                },
                fail: function(res) {
                    // 支付失败
                }
            });
        });
    });
</script>
Copy after login

In the above code, we use the JS-SDK provided by WeChat to trigger the WeChat payment interface by calling the wx.chooseWXPay method.

In the second step, the official account sends the payment request to the WeChat payment platform. We need to write code on the backend that receives payment requests and sends them to the WeChat payment platform. The specific code is as follows:

<?php
// 获取参数
$totalFee = $_GET['totalFee']; // 支付金额,单位为分,例如100表示1元

// 构造请求数据
$data = [
    'appid' => '公众号的AppID',
    'mch_id' => '商户号',
    'nonce_str' => uniqid(), // 随机字符串
    'body' => '支付测试', // 商品描述
    'out_trade_no' => time(), // 商户订单号
    'total_fee' => $totalFee, // 支付金额
    'spbill_create_ip' => $_SERVER['REMOTE_ADDR'], // 终端IP
    'notify_url' => '支付结果通知的接收地址',
    'trade_type' => 'JSAPI', // 交易类型
    'openid' => '用户的openid'
];

// 生成签名
$data['sign'] = md5(http_build_query($data) . '&key=商户的Key');

// 将请求数据转为XML格式
$xmlData = '<xml>';
foreach ($data as $key => $value) {
    $xmlData .= "<$key>$value</$key>";
}
$xmlData .= '</xml>';

// 发送请求
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.mch.weixin.qq.com/pay/unifiedorder');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);

// 解析支付结果
$responseData = simplexml_load_string($response, null, LIBXML_NOCDATA);
if ($responseData->return_code == 'SUCCESS' && $responseData->result_code == 'SUCCESS') {
    $prepayId = $responseData->prepay_id; // 获取预支付交易会话标识
    // 构造返回数据
    $returnData = [
        'appId' => '公众号的AppID',
        'timeStamp' => time(),
        'nonceStr' => uniqid(),
        'package' => 'prepay_id=' . $prepayId,
        'signType' => 'MD5'
    ];
    $returnData['paySign'] = md5(http_build_query($returnData) . '&key=商户的Key');

    echo json_encode($returnData);
} else {
    echo '支付请求失败';
}
?>
Copy after login

In the above code, we first obtain the payment amount and other parameters passed by the front end, then construct the request data, and send the request to the unified order interface of the WeChat payment platform through cURL. Next, we parse the payment result and, if the payment request is successful, return the prepayment transaction session ID (prepay_id) to the front end.

The third step is to open the WeChat payment interface on the front end. The previous code has already implemented this function, we do not need additional code.

The fourth step is that the WeChat payment platform sends payment result notification to the public account. We need to write code on the backend of the official account to receive and process payment result notifications. The specific code is as follows:

<?php
// 接收支付结果通知
$xmlData = file_get_contents('php://input');
$responseData = simplexml_load_string($xmlData, null, LIBXML_NOCDATA);

// 验证通知的有效性
if ($responseData->return_code == 'SUCCESS' && $responseData->result_code == 'SUCCESS') {
    // 处理支付结果
    // do something
    // 返回处理结果给微信支付平台
    echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
} else {
    echo '支付结果通知验证失败';
}
?>
Copy after login

In the above code, we first obtain the XML data of the payment result notification, then parse the data and verify the validity of the notification. If the verification is passed, the payment result is processed, and finally the processing result is returned to the WeChat payment platform.

With the above code, we can use PHP to develop the payment function of WeChat official account. Of course, in the actual development process, factors such as security and user experience also need to be considered and optimized accordingly.

To summarize, using PHP to develop the payment function of WeChat official account requires completing the following steps: add a payment button in the front-end interface and trigger a payment request, the back-end receives the payment request and sends it to the WeChat payment platform, the front-end Open the WeChat payment interface, and the backend receives and processes payment result notifications. Through the code implementation of the above steps, we can easily implement the payment function of WeChat official account.

The above is the detailed content of How to use PHP to develop the payment function of WeChat official account. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use Memcache in PHP development? How to use Memcache in PHP development? Nov 07, 2023 pm 12:49 PM

In web development, we often need to use caching technology to improve website performance and response speed. Memcache is a popular caching technology that can cache any data type and supports high concurrency and high availability. This article will introduce how to use Memcache in PHP development and provide specific code examples. 1. Install Memcache To use Memcache, we first need to install the Memcache extension on the server. In CentOS operating system, you can use the following command

How to use Laravel to develop an online ordering system based on WeChat public account How to use Laravel to develop an online ordering system based on WeChat public account Nov 02, 2023 am 09:42 AM

How to use Laravel to develop an online ordering system based on WeChat official accounts. With the widespread use of WeChat official accounts, more and more companies are beginning to use them as an important channel for online marketing. In the catering industry, developing an online ordering system based on WeChat public accounts can improve the efficiency and sales of enterprises. This article will introduce how to use the Laravel framework to develop such a system and provide specific code examples. Project preparation First, you need to ensure that the Laravel framework has been installed in the local environment. OK

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to implement version control and code collaboration in PHP development? How to implement version control and code collaboration in PHP development? Nov 02, 2023 pm 01:35 PM

How to implement version control and code collaboration in PHP development? With the rapid development of the Internet and the software industry, version control and code collaboration in software development have become increasingly important. Whether you are an independent developer or a team developing, you need an effective version control system to manage code changes and collaborate. In PHP development, there are several commonly used version control systems to choose from, such as Git and SVN. This article will introduce how to use these tools for version control and code collaboration in PHP development. The first step is to choose the one that suits you

How to use PHP to develop the coupon function of the ordering system? How to use PHP to develop the coupon function of the ordering system? Nov 01, 2023 pm 04:41 PM

How to use PHP to develop the coupon function of the ordering system? With the rapid development of modern society, people's life pace is getting faster and faster, and more and more people choose to eat out. The emergence of the ordering system has greatly improved the efficiency and convenience of customers' ordering. As a marketing tool to attract customers, the coupon function is also widely used in various ordering systems. So how to use PHP to develop the coupon function of the ordering system? 1. Database design First, we need to design a database to store coupon-related data. It is recommended to create two tables: one

How to use PHP to develop the member points function of the grocery shopping system? How to use PHP to develop the member points function of the grocery shopping system? Nov 01, 2023 am 10:30 AM

How to use PHP to develop the member points function of the grocery shopping system? With the rise of e-commerce, more and more people choose to purchase daily necessities online, including grocery shopping. The grocery shopping system has become the first choice for many people, and one of its important features is the membership points system. The membership points system can attract users and increase their loyalty, while also providing users with an additional shopping experience. In this article, we will discuss how to use PHP to develop the membership points function of the grocery shopping system. First, we need to create a membership table to store users

WeChat official account has added a new picture modification function: up to 3 pictures can be deleted or replaced WeChat official account has added a new picture modification function: up to 3 pictures can be deleted or replaced Mar 04, 2024 pm 05:40 PM

According to reliable sources, the WeChat official account has added a new image modification function today. Users can enter through the "Modify" entrance of the WeChat official account. Afterwards, they only need to click on the image in the official account article to delete or replace it. Up to 100 modifications are supported. 3 pictures. It is reported that users only need to click on the picture that needs to be modified, and two functional options of "Replace" and "Modify" will pop up. Select "Replace", and the picture library will pop up for the next step of selecting a new picture; select "Delete", The original image will turn gray and a "Deleted" mark will appear in the upper right corner. Once completed, just "Submit changes" as before. For more information, please pay attention to this site.

How to improve search engine rankings with PHP cache development How to improve search engine rankings with PHP cache development Nov 07, 2023 pm 12:56 PM

How to improve search engine rankings through PHP cache development Introduction: In today's digital era, the search engine ranking of a website is crucial to the website's traffic and exposure. In order to improve the ranking of the website, an important strategy is to reduce the loading time of the website through caching. In this article, we'll explore how to improve search engine rankings by developing caching with PHP and provide concrete code examples. 1. The concept of caching Caching is a technology that stores data in temporary storage so that it can be quickly retrieved and reused. for net

See all articles