Implementing WeChat Mini Program Recharge Functionality with PHP
This article explains how to develop a recharge feature for WeChat Mini Programs using PHP, covering the setup of payment parameters, generating prepay orders, invoking wx.requestPayment, and handling payment callbacks with example code.
With the rapid growth of WeChat Mini Programs, many businesses are adding recharge capabilities for virtual goods or balance top‑ups. This guide shows how to implement such a recharge function using PHP on the server side.
Creating the Application and Obtaining Payment Parameters
First, register a Mini Program on the WeChat Pay platform, create an application, and obtain essential credentials such as App ID, Merchant ID, and API key. These values are required in the subsequent server‑side code.
Generating a Prepay Order
When a user selects an amount and initiates payment, the backend must call the WeChat Pay unifiedorder API to create a prepay order. The following PHP example uses cURL to send the required XML payload and retrieve the prepay_id needed by the Mini Program.
<code><?php
$url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
$data = array(
'appid' => 'YOUR_APPID',
'mch_id' => 'YOUR_MCH_ID',
'nonce_str' => uniqid(),
'body' => '充值余额',
'out_trade_no' => uniqid(),
'total_fee' => 100, // amount in cents
'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
'notify_url' => 'http://yourdomain.com/notify.php',
'trade_type' => 'JSAPI',
'openid' => $_SESSION['openid'],
);
// Convert parameters to XML
$xml = "<xml>";
foreach ($data as $key => $value) {
$xml .= "<{$key}>{$value}</{$key}>";
}
$xml .= "</xml>";
// Send HTTP request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
// Parse XML response
$xml = simplexml_load_string($result);
if ($xml->return_code == 'SUCCESS' && $xml->result_code == 'SUCCESS') {
$prepay_id = $xml->prepay_id; // obtain prepay order ID
// return prepay_id and other parameters to Mini Program
} else {
// handle payment failure
}
?>
</code>Invoking Mini Program Payment
On the client side, use the wx.requestPayment API to launch the payment UI, passing the timestamp, nonce, package (containing the prepay_id), sign type, and pay sign returned from the server.
<code>wx.requestPayment({
'timeStamp': 'YOUR_TIMESTAMP',
'nonceStr': 'YOUR_NONCESTR',
'package': 'prepay_id=YOUR_PREPAYID',
'signType': 'MD5',
'paySign': 'YOUR_PAYSIGN',
'success': function(res) {
// payment succeeded, update user balance
},
'fail': function(res) {
// payment failed, show error
}
});
</code>Processing the Payment Result
The notify_url endpoint receives asynchronous XML notifications from WeChat Pay. The PHP script reads the raw POST data, parses the XML, and if the payment succeeded, updates the user's balance or records the transaction, then replies with a success XML to acknowledge the notification.
<code><?php
$data = file_get_contents("php://input");
$xml = simplexml_load_string($data);
if ($xml->return_code == 'SUCCESS' && $xml->result_code == 'SUCCESS') {
// Update user balance, record recharge, etc.
$response = array(
'return_code' => 'SUCCESS',
'return_msg' => 'OK'
);
echo arrayToXml($response);
} else {
// Log failure, take appropriate actions
}
?>
</code>These steps provide a basic implementation of a recharge feature for WeChat Mini Programs using PHP. In production, additional security checks, error handling, and environment‑specific configurations should be considered.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.