在ThinkPHP中实现短信发送和接收可以使用阿里云短信SDK。以下是实现步骤:
下载阿里云短信SDK,将下载的SDK文件夹放在ThinkPHP项目的Library目录下。
在ThinkPHP项目中的config.php配置文件中添加以下配置信息:
// 阿里云短信SDK配置信息
'aliyun_sms' => [
'access_key_id' => 'your_access_key_id',
'access_key_secret' => 'your_access_key_secret',
'sign_name' => 'your_sign_name',
'template_code' => [
'verify_code' => 'your_verify_code_template_code',
'notification' => 'your_notification_template_code'
]
]
其中,access_key_id
和access_key_secret
是阿里云账号的Access Key ID和Access Key Secret,可以在阿里云控制台中获取。sign_name
是短信签名,需要在阿里云短信控制台中申请。template_code
是短信模板编码,也需要在阿里云短信控制台中申请。
Sms
,该类的代码如下:<?php
namespace Common\Util;
use Aliyun\Core\Config;
use Aliyun\Core\Profile\DefaultProfile;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
/**
* 阿里云短信发送类
*/
class Sms
{
/**
* 发送短信
* @param string $mobile 手机号码
* @param string $templateCode 短信模板编码
* @param array $params 短信模板变量
* @return bool
*/
public static function send($mobile, $templateCode, $params)
{
Config::load(); // 加载阿里云短信SDK配置
$accessKeyId = C('aliyun_sms.access_key_id'); // Access Key ID
$accessKeySecret = C('aliyun_sms.access_key_secret'); // Access Key Secret
$signName = C('aliyun_sms.sign_name'); // 签名
$templateCode = C('aliyun_sms.template_code.' . $templateCode); // 短信模板编码
$iClientProfile = DefaultProfile::getProfile('cn-hangzhou', $accessKeyId, $accessKeySecret); // 地域、Access Key ID和Access Key Secret
$acsClient = new DefaultAcsClient($iClientProfile); // 初始化AcsClient
$request = new SendSmsRequest(); // 创建请求对象
$request->setPhoneNumbers($mobile); // 手机号码
$request->setSignName($signName); // 签名
$request->setTemplateCode($templateCode); // 短信模板编码
$request->setTemplateParam(json_encode($params)); // 短信模板变量
$response = $acsClient->getAcsResponse($request); // 发送请求
if ($response->Code == 'OK') { // 短信发送成功
return true;
} else { // 短信发送失败
return false;
}
}
}
该类中的send
方法用于发送短信,需要传入手机号码、短信模板编码和短信模板变量。其中,短信模板变量为一个关联数组,用于替换短信模板中的变量。
Sms
类的send
方法即可发送短信。例如:$params = [
'code' => '123456'
]; // 短信模板变量
$result = Sms::send('13812345678', 'verify_code', $params); // 发送短信
if ($result) { // 短信发送成功
echo '短信发送成功';
} else { // 短信发送失败
echo '短信发送失败';
}
以上就是在ThinkPHP中实现短信发送和接收的步骤。需要注意的是,由于涉及到阿里云短信服务,需要在阿里云控制台中开通短信服务,并且需要支付一定的费用。