Introduction
Alipay's official SDK has been updated, and legacy interfaces are gradually being deprecated. This guide will walk you through integrating the official Alipay PHP SDK for PC website payments into WooCommerce. This method is secure, standardized, and avoids reinventing the wheel.
Prerequisites
Before you begin, ensure you have the following:
- A live WordPress site with WooCommerce installed.
- A corporate Alipay account with the "PC Website Payment" product activated.
- Your Alipay Open Platform APPID, Application Private Key, and Alipay Public Key.
- A server environment supporting PHP 7.0+ and Composer for dependency management.
Integration Steps
Step 1: Install the Official Alipay SDK via Composer
In your WooCommerce theme or custom plugin directory, run the following command. It's recommended to do this within a custom plugin to prevent code loss during theme updates.
composer require alipaysdk/easysdk:^2.0
After installation, a vendor folder will be generated.
Step 2: Create a Custom Payment Gateway Plugin
Create a new folder in wp-content/plugins/, e.g., alipay-pc-for-woocommerce, and create the main plugin file alipay-pc-for-woocommerce.php.
<?php
/**
* Plugin Name: WooCommerce Alipay PC Gateway
* Description: Integrates Alipay's new PC website payment into WooCommerce.
* Version: 1.0.0
* Author: Your Name
*/
// Ensure WooCommerce is active
if (!in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
return;
}
add_action('plugins_loaded', 'init_alipay_pc_gateway');
function init_alipay_pc_gateway() {
if (!class_exists('WC_Payment_Gateway')) {
return;
}
class WC_Gateway_Alipay_PC extends WC_Payment_Gateway {
// Class definition to be filled in next step
}
}
// Add the new gateway to WooCommerce's payment methods list
add_filter('woocommerce_payment_gateways', 'add_alipay_pc_gateway');
function add_alipay_pc_gateway($gateways) {
$gateways[] = 'WC_Gateway_Alipay_PC';
return $gateways;
}
Step 3: Implement the Payment Gateway Class
Fill in the core code for the class created in the previous step. Below is a concise but complete key implementation.
class WC_Gateway_Alipay_PC extends WC_Payment_Gateway {
public function __construct() {
$this->id = 'alipay_pc';
$this->icon = ''; // Optional: Alipay logo URL
$this->has_fields = false;
$this->method_title = 'Alipay (PC Website Payment)';
$this->method_description = 'Process payments via the official Alipay SDK for PC websites.';
$this->supports = array('products');
$this->init_form_fields();
$this->init_settings();
$this->title = $this->get_option('title');
$this->description = $this->get_option('description');
$this->app_id = $this->get_option('app_id');
$this->merchant_private_key = $this->get_option('merchant_private_key');
$this->alipay_public_key = $this->get_option('alipay_public_key');
add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'));
add_action('woocommerce_api_wc_gateway_alipay_pc', array($this, 'check_alipay_response'));
}
public function init_form_fields() {
$this->form_fields = array(
'enabled' => array(
'title' => 'Enable/Disable',
'type' => 'checkbox',
'label' => 'Enable Alipay PC Website Payment',
'default' => 'yes'
),
'title' => array(
'title' => 'Title',
'type' => 'text',
'description' => 'Payment method title the customer sees during checkout.',
'default' => 'Alipay',
'desc_tip' => true
),
'app_id' => array(
'title' => 'APPID',
'type' => 'text',
'required' => true
),
'merchant_private_key' => array(
'title' => 'Merchant Private Key',
'type' => 'textarea',
'description' => 'Enter your application private key (remove -----BEGIN/END PRIVATE KEY----- and ensure no line breaks).',
'required' => true
),
'alipay_public_key' => array(
'title' => 'Alipay Public Key',
'type' => 'textarea',
'description' => 'Enter the Alipay public key (remove -----BEGIN/END PUBLIC KEY----- and ensure no line breaks).',
'required' => true
)
);
}
public function process_payment($order_id) {
$order = wc_get_order($order_id);
require_once(__DIR__ . '/vendor/autoload.php');
try {
$config = new AlipayEasySDKKernelConfig();
$config->protocol = 'https';
$config->gatewayHost = 'openapi.alipay.com';
$config->signType = 'RSA2';
$config->appId = $this->app_id;
$config->merchantPrivateKey = $this->merchant_private_key;
$config->alipayPublicKey = $this->alipay_public_key;
$config->notifyUrl = home_url('/wc-api/wc_gateway_alipay_pc/');
AlipayEasySDKKernelFactory::setOptions($config);
$result = AlipayEasySDKPaymentPageClient::pay()->pay(
$order->get_order_number(),
sprintf('%.2f', $order->get_total()),
'Purchase Goods',
home_url('/checkout/order-received/')
);
if ($result->code == '10000') {
$order->update_status('pending', 'Awaiting customer payment');
WC()->cart->empty_cart();
return array(
'result' => 'success',
'redirect' => $result->body
);
} else {
wc_add_notice('Payment request failed: ' . $result->msg, 'error');
return;
}
} catch (Exception $e) {
wc_add_notice('Payment gateway error: ' . $e->getMessage(), 'error');
return;
}
}
public function check_alipay_response() {
$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
if (empty($data)) parse_str($raw, $data);
require_once(__DIR__ . '/vendor/autoload.php');
$config = new AlipayEasySDKKernelConfig();
$config->protocol = 'https';
$config->gatewayHost = 'openapi.alipay.com';
$config->signType = 'RSA2';
$config->appId = $this->app_id;
$config->merchantPrivateKey = $this->merchant_private_key;
$config->alipayPublicKey = $this->alipay_public_key;
AlipayEasySDKKernelFactory::setOptions($config);
try {
$verify = AlipayEasySDKKernelFactory::payment()->common()->verifyNotify($data);
if ($verify) {
$out_trade_no = $data['out_trade_no'];
$trade_status = $data['trade_status'];
$order = wc_get_order($out_trade_no);
if ($trade_status == 'TRADE_SUCCESS' || $trade_status == 'TRADE_FINISHED') {
$order->payment_complete();
$order->add_order_note('Alipay payment successful. Trade No: ' . $data['trade_no']);
} else if ($trade_status == 'WAIT_BUYER_PAY') {
$order->update_status('pending');
} else if ($trade_status == 'TRADE_CLOSED') {
$order->update_status('cancelled', 'Alipay transaction closed');
}
echo 'success';
} else {
echo 'fail';
}
} catch (Exception $e) {
echo 'fail';
}
exit;
}
}
Step 4: Configuration and Testing
1. In the WordPress admin, go to Plugins and activate your "WooCommerce Alipay PC Gateway" plugin.
2. Navigate to WooCommerce -> Settings -> Payments, find "Alipay (PC Website Payment)", and click "Manage".
3. Enter your APPID, Merchant Private Key, and Alipay Public Key from the Alipay Open Platform.
4. Save changes.
5. Create a test order, select "Alipay", and you should be redirected to the Alipay payment page. Using the Alipay sandbox for initial testing is highly recommended.
Important Notes
- Key Format: Ensure private and public keys are entered as plain strings without header/footer markers or line breaks.
- Asynchronous Notification: Your server must be publicly accessible for Alipay to send notifications and update order status.
- Error Debugging: Enable
WP_DEBUGlogging or add custom logging to troubleshoot SDK initialization or payment issues. - Production Environment: After successful testing, switch the gateway configuration and APPID to Alipay's production environment.
By following these steps, you can reliably integrate Alipay's PC website payment into your WooCommerce store using the official PHP SDK.