最近做的几个项目都用到了短信验证码的功能,频繁的找代码我也觉得繁琐了,今天把代码写到博客,方便粘贴复制。今天是对接腾讯云的代码示例。
先使用 composer 安装 tencent SDK
composer require tencentcloud/tencentcloud-sdk-php
简单封装一下
namespace app\extend;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Sms\V20190711\SmsClient;
use TencentCloud\Sms\V20190711\Models\SendSmsRequest;
class SmsTencent
{
public $config = [];
public function __construct($appid, $secret_id, $secret_key)
{
$this->config = [
'appid' => $appid,
'secret_id' => $secret_id,
'secret_key' => $secret_key
];
}
public function send($template_id, $sign, $phone, $auth_code)
{
$return = [
'code' => 0,
'msg' => 'success',
'data' => []
];
try {
$cred = new Credential($this->config['secret_id'], $this->config['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();
$params = array(
"PhoneNumberSet" => array(
'86' . $phone
),
"TemplateID" => $template_id,
"Sign" => $sign,
"TemplateParamSet" => array(
(string)$auth_code
),
"SmsSdkAppid" => $this->config['appid']
);
$req->fromJsonString(json_encode($params));
$resp = $client->SendSms($req);
$result = $resp->toJsonString();
$result = json_decode($result, true);
} catch (TencentCloudSDKException $e) {
$return['code'] = 500;
$return['msg'] = $e->getMessage();
return $return;
}
if (isset($result['SendStatusSet'][0]['Code'])&&$result['SendStatusSet'][0]['Code']=='Ok') {
$return['code'] = 0;
$return['msg'] = 'success';
} else {
$return['code'] = 500;
$return['msg'] = $result['SendStatusSet'][0]['Message'] ?? '发送失败';
}
return $return;
}
}
调用
//生成验证码
$auth_code = rand(1000,9999);
$phone = $post['phone'];
//签名
$sign = Config::get('sms.sign');
//appid
$appid = Config::get('sms.appid');
//secret_id
$secret_id = Config::get('sms.secret_id');
//secret_key
$secret_key = Config::get('sms.secret_key');
//模板ID
$auth_code_template_id = Config::get('sms.auth_code_template_id');
$sms = new SmsTencent($appid, $secret_id, $secret_key);
$result = $sms->send($auth_code_template_id, $sign, $phone, $auth_code);
if ($result['code'] != 0) {
return api_json_return(500, $result['msg'] ?? '发送失败');
}
return api_json_return(0, '发送成功');
so easy