WeChat Pay V3 Integration in PHP: Complete Backend Implementation
This article explains how to upgrade to WeChat Pay V3 in PHP, covering composer installation, configuration file setup, a table of payment methods, example usage for mini‑program payments, and a full reusable Wechat class with signing, verification, and refund functions.
The WeChat Pay interface has been upgraded to version V3, and the article shows how to update a PHP project to use the new API.
Installation can be done via Composer:
<code>composer require fengkui/pay</code>A configuration array must be filled with the merchant's credentials:
<code>$wechatConfig = [
'xcxid' => '', // Mini‑program appid
'appid' => '', // WeChat Pay appid
'mchid' => '', // Merchant ID
'key' => '', // apiV3key
'appsecret' => '', // Public account secret
'notify_url' => '', // Callback URL
'redirect_url' => '', // Redirect URL for public account payments
'serial_no' => '', // Certificate serial number
'cert_client' => './cert/apiclient_cert.pem', // Certificate for refunds/red packets
'cert_key' => './cert/apiclient_key.pem', // Merchant private key
'public_key' => './cert/public_key.pem', // Platform public key
];</code>The article lists the supported payment methods in a table (JSAPI, APP, H5, Native, Mini‑program, Query, Close, Refund, Notify).
Example usage for a mini‑program payment:
<code>require_once './vendor/autoload.php';
$config = [];
$order = [
'order_sn' => time(),
'total_amount' => 1,
'body' => 'Test product',
'openid' => '',
];
$wechat = new fengkui\Pay\Wechat($config);
$re = $wechat->xcx($order);
die(json_encode($re));
</code>A full Wechat.php class is provided, containing methods for unified order, query, close, JSAPI, APP, H5, native scan, notification handling, refund, signature generation, signature verification, certificate retrieval, and decryption. Key methods include:
<code>public static function unifiedOrder($order, $type = false) { ... }
public static function query($orderSn, $type = false) { ... }
public static function app($order = [], $log = false) { ... }
public static function h5($order = [], $log = false) { ... }
public static function xcx($order = [], $log = false, $type = true) { ... }
public static function refund($order) { ... }
protected static function createAuthorization($url, $data = [], $method = 'POST') { ... }
public static function makeSign($data) { ... }
public static function verifySign($data, $sign, $serial) { ... }
public static function decryptToString($associatedData, $nonceStr, $ciphertext) { ... }
</code>References to additional documentation are listed at the end of the article.
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.