Use Omnipay Alipay in WordPress to Implement Alipay Payments

Alipay’s official API can be frustrating to work with, especially inside a WordPress project. Omnipay improves the experience by giving different payment gateways a more consistent PHP interface. Thanks to Lokielse’s Alipay support, we can use the same general Omnipay workflow for Alipay inside WordPress.

Step 1: install and configure Omnipay Alipay

Install the package with Composer:

composer require omnipay-alipay

Then load the autoloader and configure your Alipay gateway:

require_once dirname(__FILE__) . '/../vendor/autoload.php';

use Omnipay\\Omnipay;

function get_gate_way() {
    $gateway = Omnipay::create('Alipay_Express');
    $gateway->setPartner('your-partner-id');
    $gateway->setKey('your-security-key');
    $gateway->setSellerEmail('your-seller@example.com');

    return $gateway;
}

Step 2: create the order and redirect the user to Alipay

Next, prepare the order data, including the order number, amount, and subject, then create the purchase request and redirect the user to Alipay.

new Dispatch(array(
    'online_charge' => function ($request) {
        $amount = trim($_POST['amount']);
        $tn = 'p4' . order_no();

        $options = array(
            'out_trade_no' => $tn,
            'subject' => 'Online Recharge',
            'total_fee' => $amount,
            'return_url' => home_url('/order_return/'),
            'notify_url' => home_url('/order_notify/'),
        );

        $response = get_gate_way()->purchase($options)->send();
        $response->redirect();
    }
));

Step 3: verify the return data and process the order

When Alipay redirects the user back to your site, verify the returned data and then update your order according to the payment status.

new Dispatch(array(
    'order_return' => function ($request) {
        $options = array(
            'request_params' => $_REQUEST,
        );

        $gateway = get_gate_way();
        $response = $gateway->completePurchase($options)->send();

        if ($response->isSuccessful() && $response->isTradeStatusOk()) {
            echo 'Payment successful';
            // Update the order here.
        } else {
            echo 'Payment failed';
        }
    }
));

This example only covers the general Omnipay Alipay flow. In a real project, you would still need to connect the gateway result to your own order storage and business logic. The good news is that once you understand this pattern, the same idea can be applied to other domestic payment gateways such as WeChat Pay and UnionPay.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *