Introduction
Integrating mobile phone number verification into your WordPress site can significantly enhance user registration authenticity and security, helping to prevent malicious sign-ups and spam. Tencent Cloud offers a convenient SMS verification code service. This guide will walk you through integrating Tencent Cloud SMS into WordPress to implement phone number verification. (Note: You must have an active Tencent Cloud account with SMS service permissions enabled via the console.)
Prerequisites
Before you begin, ensure you have the following:
- Tencent Cloud Account: Register and log in at Tencent Cloud.
- SMS Service Enabled: Navigate to the "SMS" product in the console and enable it.
- Create an Application (SDK AppID) and Signature: In the SMS console, create an application to obtain your SDK AppID and App Key. Also, apply for an SMS signature (identifies the sender).
- Create an SMS Template: Create a template for sending verification codes and note its Template ID. The template should contain a variable like
{1}or{code}for the code.
Integration Steps
1. Install the Tencent Cloud PHP SDK
Install the SDK on your WordPress server using Composer. If your theme or plugin has its own composer.json, run the command in that directory. Alternatively, you can download the SDK source code manually.
composer require tencentcloud/tencentcloud-sdk-php
2. Create a Custom Functionality File
Encapsulate the core logic in a custom plugin or your theme's functions.php file. The example below includes functions for sending and verifying codes.
<?php
// Include the SDK autoloader (adjust path as needed)
require_once 'path/to/vendor/autoload.php';
use TencentCloudCommonCredential;
use TencentCloudCommonProfileClientProfile;
use TencentCloudCommonProfileHttpProfile;
use TencentCloudSmsV20210111SmsClient;
use TencentCloudSmsV20210111ModelsSendSmsRequest;
// Configuration constants (replace with your actual credentials)
define('TENCENT_SMS_SECRET_ID', 'Your_SecretId');
define('TENCENT_SMS_SECRET_KEY', 'Your_SecretKey');
define('TENCENT_SMS_SDK_APP_ID', 'Your_SDK_AppID');
define('TENCENT_SMS_SIGN_NAME', 'Your_Signature');
define('TENCENT_SMS_TEMPLATE_ID', 'Your_Template_ID');
// Temporary storage for codes (use Transients API or DB in production)
$sms_verification_codes = array();
/**
* Send SMS verification code.
* @param string $phone_number Phone number (with country code, e.g., +8613712345678)
* @return array Result
*/
function send_sms_verification_code($phone_number) {
try {
$cred = new Credential(TENCENT_SMS_SECRET_ID, TENCENT_SMS_SECRET_KEY);
$httpProfile = new HttpProfile();
$httpProfile->setEndpoint('sms.tencentcloudapi.com');
$clientProfile = new ClientProfile();
$clientProfile->setHttpProfile($httpProfile);
$client = new SmsClient($cred, 'ap-guangzhou', $clientProfile);
$req = new SendSmsRequest();
$req->SmsSdkAppId = TENCENT_SMS_SDK_APP_ID;
$req->SignName = TENCENT_SMS_SIGN_NAME;
$req->TemplateId = TENCENT_SMS_TEMPLATE_ID;
$req->PhoneNumberSet = array('+86' . $phone_number); // Example for China
$code = str_pad(strval(rand(0, 999999)), 6, '0', STR_PAD_LEFT);
$req->TemplateParamSet = array($code);
$resp = $client->SendSms($req);
$result = json_decode($resp->toJsonString(), true);
if ($result['SendStatusSet'][0]['Code'] == 'Ok') {
global $sms_verification_codes;
$sms_verification_codes[$phone_number] = array(
'code' => $code,
'expire' => time() + 300
);
return array('success' => true, 'message' => 'Code sent successfully');
} else {
return array('success' => false, 'message' => 'Send failed: ' . $result['SendStatusSet'][0]['Message']);
}
} catch (Exception $e) {
return array('success' => false, 'message' => 'Exception: ' . $e->getMessage());
}
}
/**
* Verify the SMS code.
* @param string $phone_number Phone number
* @param string $user_input_code User-input code
* @return bool Verification result
*/
function verify_sms_code($phone_number, $user_input_code) {
global $sms_verification_codes;
if (isset($sms_verification_codes[$phone_number])) {
$record = $sms_verification_codes[$phone_number];
if (time() <= $record['expire'] && $user_input_code === $record['code']) {
unset($sms_verification_codes[$phone_number]);
return true;
}
}
return false;
}
?>
3. Create Frontend Interface
Add phone number and code input fields, plus a "Get Code" button to your registration/login page. Here's a simplified HTML and AJAX example.
<form id="sms-verify-form">
<label for="phone">Phone Number:</label>
<input type="tel" id="phone" name="phone" required /><br/>
<label for="sms-code">Verification Code:</label>
<input type="text" id="sms-code" name="sms_code" required />
<button type="button" id="get-sms-code">Get Code</button><br/>
<button type="submit">Verify</button>
</form>
<div id="sms-message"></div>
<script>
jQuery(document).ready(function($) {
$('#get-sms-code').click(function() {
var phone = $('#phone').val();
if (!phone) { alert('Please enter phone number'); return; }
$(this).prop('disabled', true);
var countdown = 60;
var timer = setInterval(function() {
$('#get-sms-code').text('Resend (' + countdown + ')');
countdown--;
if (countdown < 0) {
clearInterval(timer);
$('#get-sms-code').text('Get Code').prop('disabled', false);
}
}, 1000);
$.ajax({
url: '<?php echo admin_url("admin-ajax.php"); ?>',
type: 'POST',
data: { action: 'send_sms_code', phone: phone },
success: function(response) {
$('#sms-message').html('<p>' + response.data.message + '</p>');
}
});
});
$('#sms-verify-form').submit(function(e) {
e.preventDefault();
var phone = $('#phone').val();
var code = $('#sms-code').val();
$.ajax({
url: '<?php echo admin_url("admin-ajax.php"); ?>',
type: 'POST',
data: { action: 'verify_sms_code', phone: phone, code: code },
success: function(response) {
if (response.success) {
$('#sms-message').html('<p style="color:green;">Verification successful!</p>');
} else {
$('#sms-message').html('<p style="color:red;">' + response.data + '</p>');
}
}
});
});
});
</script>
4. Register AJAX Handlers
Hook the send and verify functions to WordPress AJAX for frontend calls.
// Add to your functionality file
add_action('wp_ajax_send_sms_code', 'handle_send_sms_code');
add_action('wp_ajax_nopriv_send_sms_code', 'handle_send_sms_code');
add_action('wp_ajax_verify_sms_code', 'handle_verify_sms_code');
add_action('wp_ajax_nopriv_verify_sms_code', 'handle_verify_sms_code');
function handle_send_sms_code() {
$phone = sanitize_text_field($_POST['phone']);
$result = send_sms_verification_code($phone);
wp_send_json($result);
}
function handle_verify_sms_code() {
$phone = sanitize_text_field($_POST['phone']);
$code = sanitize_text_field($_POST['code']);
if (verify_sms_code($phone, $code)) {
wp_send_json_success('Code correct');
} else {
wp_send_json_error('Invalid or expired code');
}
}
Important Notes & Optimization Tips
- Security: The example stores codes in a global variable for demonstration only. In production, use a secure method like WordPress Transients API (with expiration) or a custom database table.
- Rate Limiting: Implement limits on how often a phone number can request codes to prevent abuse.
- Error Handling: Provide clear, user-friendly error messages on both frontend and backend.
- Number Format: Tencent Cloud SMS requires the format
+[CountryCode][Number](e.g.,+8613712345678for China). Validate and convert formats as needed. - SDK Configuration: Ensure your server PHP environment meets SDK requirements (PHP >= 5.6) and can access Tencent Cloud API endpoints.
- Plugin Approach: Consider packaging the functionality as a standalone plugin for easier management and updates.
Conclusion
By following these steps, you can integrate Tencent Cloud SMS into WordPress to add phone number verification. The core process involves configuring credentials, using the SDK to send SMS, creating frontend interactions with AJAX, and storing/verifying codes. Adapt the code to your specific needs, prioritizing security and user experience.