前提条件
在安装和使用阿里云PHP SDK前,确保您已经:
- 请确认您的系统满足需求。
- 已经注册阿里云账号并生成访问密钥(AccessKey)。详细步骤请参考创建AccessKey。
1.安装PHP SDK
[root@iZbp1ho4i5t91cq1pp6ikoZ test.com]# composer require alibabacloud/client
Do not run Composer as root/super user! See https://getcomposer.org/root for details
Using version ^1.5 for alibabacloud/client
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 12 installs, 0 updates, 0 removals
- Installing clagiordano/weblibs-configmanager (v1.0.7): Downloading (100%)
- Installing adbario/php-dot-notation (2.2.0): Downloading (100%)
- Installing symfony/polyfill-mbstring (v1.17.1): Downloading (100%)
- Installing mtdowling/jmespath.php (2.5.0): Downloading (100%)
- Installing danielstjules/stringy (3.1.0): Downloading (100%)
- Installing psr/http-message (1.0.1): Downloading (100%)
- Installing psr/http-client (1.0.1): Downloading (100%)
- Installing ralouphie/getallheaders (3.0.3): Downloading (100%)
- Installing guzzlehttp/psr7 (1.6.1): Downloading (failed)
Downloading (100%)
- Installing guzzlehttp/promises (v1.3.1): Downloading (100%)
- Installing guzzlehttp/guzzle (7.0.1): Downloading (100%)
- Installing alibabacloud/client (1.5.25): Downloading (100%)
guzzlehttp/psr7 suggests installing zendframework/zend-httphandlerrunner (Emit PSR-7 responses)
guzzlehttp/guzzle suggests installing psr/log (Required for using the Log middleware)
Writing lock file
Generating autoload files
1 package you are using is looking for funding.
Use the `composer fund` command to find out more!
2.控制器代码 获取验证码(将code 以及key存入缓存)
<?php
use think\Request;
use think\Cache;
// 阿里云短信服务 202007101044
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
// Download:https://github.com/aliyun/openapi-sdk-php
// Usage:https://github.com/aliyun/openapi-sdk-php/blob/master/README.md
//阿里云 访问密钥(AccessKey)
define('AccessKeyID', '<accessKeyId>');
define('AccessKeySecret', '<accessSecret>');
define('SMS_LOGIN','SMS_195****27'); //模版内容:【SignName】 验证码为:${code},您正在登录,若非本人操作,请勿泄露。
define('SMS_REG','SMS_195****33'); // 模版内容:【SignName】您正在注册****账号,验证码为:${code},请勿泄漏于他人!
class SendVerificationCode
{
//随机产生六位数
private function getSmsCode($len=6,$format='ALL') {
switch($format) {
case 'ALL':
$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~'; break;
case 'CHAR':
$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-@#~'; break;
case 'NUMBER':
$chars='0123456789'; break;
default :
$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~';
break;
}
mt_srand((double)microtime()*1000000*getmypid());
$password="";
while(strlen($password)<$len)
$password.=substr($chars,(mt_rand()%strlen($chars)),1);
return $password;
}
// 发送短信验证码 20200710115029
public function sms_regverifysend(Request $request){
if($request->param('token')){
if('f04d5e2f87d0fcds' === $request->param('token')){
if($request->isPost()){
$PhoneNumbers = $request->param('mobile');
$type = $request->param('type');
//是否开启调试
if(!empty($request->param('debug'))){
$debug = $request->param('debug')? 1 : 0;
}else{
$debug = 0;
}
if($type == 'login'){
$TemplateCode = SMS_LOGIN;
}elseif($type == 'reg'){
$TemplateCode = SMS_REG;
}
$SignName = "【SignName】"; //例如:阿里云 要和申请用的签名一致
//随机生成6位数字
$code = $this->getSmsCode(6,'NUMBER');
AlibabaCloud::accessKeyClient(AccessKeyID, AccessKeySecret)
->regionId('cn-hangzhou')
->asDefaultClient();
try {
$result = AlibabaCloud::rpc()
->product('Dysmsapi')
// ->scheme('https') // https | http
->version('2017-05-25')
->action('SendSms')
->method('POST')
->host('dysmsapi.aliyuncs.com')
->options([
'query' => [
'RegionId' => "cn-hangzhou",
'PhoneNumbers' => $PhoneNumbers,
'SignName' => $SignName,
'TemplateCode' => $TemplateCode,
'TemplateParam' => json_encode(["code"=>$code]),
],
])
->request();
/***
* Array
(
[Message] => OK
[RequestId] => 82B1AC3C-5F13-434F-A698-F1A73DB50D02
[BizId] => 224411294351309109^0
[Code] => OK
)
Array
(
[Message] => 模板变量缺少对应参数值
[RequestId] => F8932DD4-801A-45B3-BB50-09432E4D0237
[Code] => isv.TEMPLATE_MISSING_PARAMETERS
)
**/
$arr = $result->toArray();
if($debug){
print_r($result->toArray());
die;
}
if(strtolower($arr['Code']) == 'ok' ){
//存code到缓存中
$key = 'verificationCode_'.$this->getSmsCode(15,'ALL');
//有效期3分钟
$expiredAt = time() + 3 * 60;
Cache::set($key,['mobile'=>$mobile,'code'=>$code],$expiredAt);
$data = [
'verification_key' => $key,
'expiredAt' => date('Y-m-d H:i:s',$expiredAt),
'verification_code' => $code
];
echo json_encode(['code'=>1,"messege"=>'验证码发送成功','data'=>$data,'verify_time_total'=>60]);
}else{
echo json_encode(['code'=>0,"messege"=>'验证码发送失败','data'=>$arr]);
}
} catch (ClientException $e) {
echo $e->getErrorMessage() . PHP_EOL;
} catch (ServerException $e) {
echo $e->getErrorMessage() . PHP_EOL;
}
}else{
echo json_encode(['code'=>0,"messege"=>'please use post request']);
}
}else{
echo json_encode(['code'=>1001, 'messege'=>'没有访问权限', 'data'=>[]]);
}
}else{
echo json_encode(['code'=>1000, 'messege'=>'参数有误', 'data'=>[]]); // 响应json串
}
}
}
?>
3.比对验证码
//小程序用户注册或者登陆 202007021308
public function user_register(Request $request){
if($request->param('token')){
if('f04d5e2f87d0fcds' === $request->param('token')){
if($request->isPost()){
//add 20200710132225
$verification_key = $request->param('verification_key');
$code = $request->param('code');
$verifyData = Cache::get($verification_key);
if( !$verifyData){
//$this->setMsg('验证码已失效');
echo json_encode(['code'=>0, 'messege'=>'验证码已失效']);
die;
}
if(!hash_equals($code,(string)$verifyData['code'])){
//$this->setMsg('验证码错误');
echo json_encode(['code'=>0, 'messege'=>'验证码错误']);
die;
}
//删除缓存
Cache::rm($verification_key);
$openid = $request->param('openid');
$tel = $request->param('tel');
// var_dump($request->param());
// die;
$user_data = array(
'tel' => $tel,
'binding_tel_time' => date('Y-m-d H:i:s')
);
//fetchSql(true)生成的SQL等同于:SELECT `id`,`nickName`,`openid` FROM `ims_yckj_liucheng_fans` WHERE `openid` = 'opxz9v0zpideUCpFuDCIU7ZbY_bQ' AND `uniacid` = 8 LIMIT 1
$user = Db::table('ims_yckj_liucheng_fans')->where('openid', $openid)->where('uniacid', 8)->field(array('id', 'nickName', 'openid'))->find();
if (!empty($user)) {
$result = Db::table('ims_yckj_liucheng_fans')->data($user_data)->where('openid', $openid)->where('uniacid', 8)->update();
if (!empty($result)) {
echo json_encode(['code'=>1, 'messege'=>'注册成功', 'data'=>$request->param()]);
}else{
echo json_encode(['code'=>0, 'messege'=>'注册失败', 'data'=>$request->param()]);
}
}else{
echo json_encode(['code'=>0, 'messege'=>'请先授权登录', 'data'=>$request->param()]);
}
}else{
echo json_encode(['code'=>0, 'messege'=>'请使用post请求传参', 'data'=>[]]);
}
}else{
echo json_encode(['code'=>1001, 'messege'=>'没有访问权限', 'data'=>[]]);
}
}else{
echo json_encode(['code'=>1000, 'messege'=>'参数有误', 'data'=>[]]);
}
}
4.使用ApiPost调用接口
用户登录、注册验证码.png获取验证码
用户注册.png模拟用户注册
网友评论