好久没有更新阿里云短信API了,最近做新项目,到阿里云官网想下个最新的sdk发现已经更新好久了,之前只是一直在用老的,而且好久没关注,这次记录一下。
申请模版和签名不多说了,自己去阿里云管理台操作好,发送短信的文档(短信发送API)也写的很清楚,这里记录一下thinkphp5.1调用API发送短信。
使用阿里云短信服务发送验证码示例:
1.先切换到项目根目录,然后composer安装sdk,
composer require alibabacloud/client
这里会下一堆东西,圈起来的貌似都是(不是很确定,因为当天没来得及记下来)
2.因为项目这边前后台都可能会用到,所以我这边就写在了common.php里(application/common.php),配置信息放在config/app.php里。
<?php
// 应用公共文件
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
/**
* 验证码(阿里云短信)
*/
function smsVerify($mobile, $code, $tempId)
{
AlibabaCloud::accessKeyClient(config('app.aliyunsms.access_key_id'), config('app.aliyunsms.access_key_secret'))
->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' => config('app.aliyunsms.sign_name'),
'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.在需要的地方调用这个方法即可:
我这里是ajax调用的,所以返回值是json格式。
$code = rand_string(4,1);//这里是随机生成4位数字,这个方法是我自己写的哦,要注意!
$res = smsVerify($mobile, $code, 'SMS_113461246');
if($res['status'] == 1){
Session::set($mobile.'code',$code);
ajaxReturn(1,"验证码已发送");
}else{
ajaxReturn(0,"验证码发送失败,请联系客服");
}
这样就好了,验证码发送的功能就完成了!
vue2 Implicit conversion from float int loses precision php8Implicit Mysql8新增用户,mysql8配置权限,mysql8配置,mysql8配置文件 Linux命令,scp,scp命令,Linux复制 git commit git add centos git 搭建FTP,Linux FTP,禁止FTP登录ssh 上传文件,阿里云OSS上传,文件上传到OSS,OSS文件上传,OSS上传 微信支付,微信支付V3,PHP微信支付,微信nativePay支付,微信jsapi支付 微信支付,微信支付V3,PHP微信支付 bootstrap4 modal, lavarel The subversion command line tools are no longer provided by Xcode. 银联支付,tp5.1银联支付 支付宝即时到账,PHP支付宝 system libzip must be upgraded to version >= 0.11 CMake 3.0.2 or higher is required