WeChat Pay became increasingly popular very quickly, and many WordPress site owners wanted to add it as a payment method. The official WeChat SDK can be difficult to use, but Omnipay makes the integration much easier. The omnipay-wechatpay package, created by Lokielse, provides a more consistent payment API for PHP developers.
This article shows the basic process for adding native QR code WeChat payments to WordPress.
Step 1: install Omnipay WechatPay with Composer
If Composer is already configured for your theme or plugin, install the gateway package with:
composer require lokielse/omnipay-wechatpay
After installation, load the autoloader and configure the WeChat payment gateway:
require_once dirname(__FILE__) . '/../vendor/autoload.php';
use Omnipay\\Omnipay;
function get_wechat_gateway() {
$gateway = Omnipay::create('WechatPay_Native');
$gateway->setAppId('your-app-id');
$gateway->setMchId('your-merchant-id');
$gateway->setApiKey('your-api-key');
$gateway->setNotifyUrl('https://example.com/wechat_return/');
return $gateway;
}
You could create the gateway object inline where you need it, but wrapping it in a function makes configuration and debugging much easier when the gateway is used in multiple places.
Step 2: submit order data and generate the QR code
The next step is to send the order information to the WeChat gateway, receive the payment data in response, and convert it into a QR code that the user can scan with WeChat.
The example below uses WordPress Dispatcher to create a custom URL, but you could also use a custom page template or the WordPress Ajax API.
new Dispatch(array(
'wechat_charge' => function ($request) {
$total_fee = trim($_GET['amount']);
$tn = order_no();
$params = array(
'out_trade_no' => $tn,
'notify_url' => 'https://example.com/wechat_return/',
'body' => 'Online payment',
'total_fee' => $total_fee,
);
$response = get_wechat_gateway()->purchase($params)->send();
if ($response->isSuccessful()) {
$codeUrl = $response->getCodeUrl();
// Convert $codeUrl into a QR code image and display it.
}
}
));
Step 3: handle the WeChat gateway notification
The last step is to verify the payment status and update the order accordingly. In a real project you would normally save the order before payment begins, then use the callback to mark it as paid.
new Dispatch(array(
'wechat_return' => function ($request) {
$gateway = get_wechat_gateway();
$response = $gateway->completePurchase(array(
'request_params' => file_get_contents('php://input')
))->send();
if ($response->isPaid()) {
echo 'Payment successful';
// Update your order here.
}
}
));
Omnipay also has gateways for Alipay and UnionPay, so once you are comfortable with this general pattern, adding other payment methods becomes much easier as well.
