Prerequisites and Setup
Before integrating Alipay real-name verification, ensure you have completed the following:
- Corporate Alipay Account: A personal account cannot apply for the required APIs. You must log into the Alipay Open Platform with a corporate account.
- Create an App and Obtain Credentials: Create a web/mobile app in the Open Platform. After approval, obtain your
APPID,App Private Key, andAlipay Public Key. - Sign the Required Product: In the "Capability List," find and sign the "Alipay Real-Name Identity Information Verification" API product to gain access.
- WordPress Environment: A functioning WordPress site and basic PHP coding skills.
Note: Alipay interfaces and key generation may change. This guide outlines a general process. Always refer to the latest official Alipay Open Platform documentation. Generate keys using official tools and keep your private key secure.
Integration Overview
The integration involves three core steps:
- Front-End Data Collection: Create a form on your WordPress site (e.g., user profile) to collect the user's real name and ID number.
- Server-Side Verification Request: When the form is submitted, use PHP code to send the data to Alipay's servers for verification, using their SDK or API.
- Process and Return Result: Handle Alipay's response, display a success/failure message to the user, and update their verification status in the database.
Code Implementation Example
This simplified example demonstrates the core server-side logic. It assumes the Alipay PHP SDK is placed in a directory like /wp-content/alipay-sdk/.
Step 1: Create a Front-End Form
Add a form via a theme template (e.g., user-profile.php) or a shortcode:
<form id='alipay-realname-form' method='post' action=''>
<?php wp_nonce_field('verify_realname_action', 'realname_nonce'); ?>
<p>
<label for='real_name'>Real Name:</label>
<input type='text' id='real_name' name='real_name' required />
</p>
<p>
<label for='id_card'>ID Number:</label>
<input type='text' id='id_card' name='id_card' required />
</p>
<p>
<input type='submit' name='submit_realname' value='Submit Verification' />
</p>
</form>
Step 2: Backend Processing and API Call
Add the following logic to your theme's functions.php or a custom plugin file. Key parts include:
<?php
// Include Alipay SDK (adjust path)
require_once get_template_directory() . '/alipay-sdk/aop/request/AlipayUserCertifyOpenInitializeRequest.php';
require_once get_template_directory() . '/alipay-sdk/aop/AopClient.php';
add_action('init', 'handle_realname_verification');
function handle_realname_verification() {
if (!isset($_POST['submit_realname']) || !wp_verify_nonce($_POST['realname_nonce'], 'verify_realname_action')) {
return;
}
$real_name = sanitize_text_field($_POST['real_name']);
$id_card = sanitize_text_field($_POST['id_card']);
$user_id = get_current_user_id();
if (empty($real_name) || empty($id_card) || $user_id == 0) {
wp_die('Incomplete information or not logged in.');
}
// --- Rate Limiting Check ---
$attempts_key = 'realname_verify_attempts_' . $user_id;
$last_attempt_key = 'realname_last_attempt_' . $user_id;
$max_attempts = 5;
$cooldown_seconds = 300; // 5 minutes
$attempts = (int) get_transient($attempts_key);
$last_attempt = (int) get_transient($last_attempt_key);
$current_time = time();
if ($last_attempt && ($current_time - $last_attempt) < $cooldown_seconds) {
$remaining = $cooldown_seconds - ($current_time - $last_attempt);
wp_die('Too many attempts. Please wait ' . ceil($remaining / 60) . ' minutes.');
}
if ($attempts >= $max_attempts) {
wp_die('Daily attempt limit reached. Please try again in 24 hours.');
}
// --- End Rate Limit ---
// 1. Configuration (Replace with your actual credentials)
$appId = 'YOUR_APPID';
$privateKey = 'YOUR_PRIVATE_KEY';
$alipayPublicKey = 'YOUR_ALIPAY_PUBLIC_KEY';
$gatewayUrl = 'https://openapi.alipay.com/gateway.do'; // Production
// $gatewayUrl = 'https://openapi.alipaydev.com/gateway.do'; // Sandbox
// 2. Instantiate AopClient
$aop = new AopClient();
$aop->gatewayUrl = $gatewayUrl;
$aop->appId = $appId;
$aop->rsaPrivateKey = $privateKey;
$aop->alipayrsaPublicKey = $alipayPublicKey;
$aop->format = 'json';
$aop->charset = 'UTF-8';
$aop->signType = 'RSA2';
// 3. Build Request (Example for identity verification)
$bizContent = array(
'identity_param' => array(
'identity_type' => 'CERT_INFO',
'cert_type' => 'IDENTITY_CARD',
'cert_name' => $real_name,
'cert_no' => $id_card
)
// Additional params like 'scene_code' may be required.
);
$request = new AlipayUserCertifyOpenInitializeRequest();
$request->setBizContent(json_encode($bizContent, JSON_UNESCAPED_UNICODE));
// 4. Execute Request
try {
$result = $aop->execute($request);
$responseNode = str_replace('.', '_', $request->getApiMethodName()) . '_response';
$resultCode = $result->$responseNode->code;
// 5. Handle Result
if (!empty($resultCode) && $resultCode == 10000) {
// Success
update_user_meta($user_id, 'realname_verified', 'yes');
// Consider encrypting sensitive data before storage.
delete_transient($attempts_key);
delete_transient($last_attempt_key);
echo 'Verification successful!';
} else {
// Failure
update_user_meta($user_id, 'realname_verified', 'no');
$msg = $result->$responseNode->msg ?? 'Verification failed. Check your information.';
set_transient($attempts_key, $attempts + 1, DAY_IN_SECONDS);
set_transient($last_attempt_key, $current_time, DAY_IN_SECONDS);
echo '' . esc_html($msg) . '';
}
} catch (Exception $e) {
error_log('Alipay API Error: ' . $e->getMessage());
set_transient($attempts_key, $attempts + 1, DAY_IN_SECONDS);
set_transient($last_attempt_key, $current_time, DAY_IN_SECONDS);
echo 'System busy. Please try again later.';
}
}
?>
Security & Compliance Notes: This is a demonstration. In production:
1. HTTPS: Ensure your site uses HTTPS.
2. Sensitive Data: Encrypt sensitive information like ID numbers before storage.
3. Rate Limiting: Implement limits to prevent abuse (example included).
4. Privacy Policy: Inform users their data is sent to Alipay for verification and comply with regulations.
Next Steps and Optimization
- Status Display: Show verification status on the user profile.
- Access Control: Use the
realname_verifieduser meta to restrict content or features. - Use Composer: Manage the SDK via Composer (
composer require alipaysdk/easysdk) for easier updates. - Error Logging: Improve error handling and log issues for debugging.
- Async Notification (Optional): For certain verification flows, configure and handle Alipay's asynchronous notify URL.
Always refer to the Alipay Open Docs for the latest API details during development.