基于 ThinkPHP 调用阿里云短信接口
1.composer 下载 阿里云短信类
composer require alibabacloud/client
2.调用阿里云短信代码
/**
* 阿里云短信验证
* @param $mobile
* @param $code
* @param $tempId
* @return array
* @throws ClientException
*
* keyID XXXXXXXXXXXXXXXXXXXXX
* keySecret XXXXXXXXXXXXXXXXXX
* tempId SMS_xxxxxxx
*
*/
function smsVerify($mobile, $code, $tempId)
{
header("Access-Control-Allow-Origin:*");
header('Access-Control-Allow-Methods:POST');
header('Access-Control-Allow-Headers:x-requested-with, content-type');
AlibabaCloud::accessKeyClient("keyID", "keySecret")
->regionId('cn-hangzhou') //replace regionId as you need(这个地方是发短信的节点,默认即可,或者换成你想要的)
->asGlobalClient();
$data = [];
try {
$result = AlibabaCloud::rpcRequest()
->product('Dysmsapi')
//->scheme('https') //https | http(如果域名是https,这里记得开启)
->version('2017-05-25')
->action('SendSms')
->method('POST')
->options([
'query' => [
'PhoneNumbers' => $mobile,
'SignName' => "xx商城", //短信签名
'TemplateCode' => $tempId,
'TemplateParam' => json_encode(['code'=>$code]),
],
])
->request();
$res = $result->toArray();
if($res['Code'] == 'OK'){
$data['status'] = 1;
$data['info'] = $res['Message'];
}else{
$data['status'] = 0;
$data['info'] = $res['Message'];
}
return $data;
} catch (ClientException $e) {
$data['status'] = 0;
$data['info'] = $e->getErrorMessage();
return $data;
} catch (ServerException $e) {
$data['status'] = 0;
$data['info'] = $e->getErrorMessage();
return $data;
}
}
3项目中调用处理
/** * 获取验证码 * @return false|string * @throws \AlibabaCloud\Client\Exception\ClientException * @throws \think\db\exception\DataNotFoundException * @throws \think\db\exception\ModelNotFoundException * @throws \think\exception\DbException */ public function getCode(){ $mobile = $this->request->mobile; $state = $this->request->state ?? 0; //state == 0 注册 state == 1忘记密码 修改密码 if(empty($mobile)) return errorMsg('-10012'); if($state == 0){ $data = Commercial::where('mobile',$mobile)->find(); if(!empty($data)) return errorMsg('-10011'); } $code = Redis::getInstance()->get($mobile); if(isset($code) && !empty($code)) return errorMsg('-10016'); $rand = rand(10000,99999); Redis::getInstance()->set($mobile,$rand,5*60); //调整验证码 缓存时间 // ****************************调用 以上逻辑不用管 根据自己需求********************** $res = smsVerify($mobile, $rand, 'SMS_XXXX'); //模板ID SMS_XXXXX // ****************************调用 end********************** if($res['status'] != 1) return errorMsg("-10017"); return successMsg([]); }
本作品采用《CC 协议》,转载必须注明作者和本文链接
发个短信 搞那么大的类库干啥