tp5.1发送阿里云短信验证码

使用tp模拟生成手机号,并发送阿里云短信验证码

1.项目根目录执行composer,安装sdk

composer  require  alibabacloud/client

2.发送验证码示例

// 公共文件
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;   

// 代码如下
    private static $mobileSegment = [
	        '134', '135', '136', '137', '138', '139', '150', '151', '152', '157', '130', '131', '132', '155', '186', '133', '153', '189',
	    ];
	
	public function nextMobile()
	{
        // 模拟生成手机号
		$prefix = self::$mobileSegment[array_rand(self::$mobileSegment)];
		$middle = mt_rand(2000, 9000);
		$suffix = mt_rand(2000, 9000);

        $mobile = $prefix . $middle . $suffix;

		
		
		$code = mt_rand(2000, 9000);//这里是随机生成4位数字
		
		$res    = self::smsVerify($mobile, $code, '你的template_code');
    
		if($res['status'] == 1){
		
		    dump(1,"验证码已发送");
		
		}else{
		
		    dump(0,"验证码发送失败,请联系客服");
		
		}
	}
	
	
	/**
	
	  * 验证码(阿里云短信)
	
	  */
	
	function smsVerify($mobile, $code, $tempId)
	
	{     
	
	   AlibabaCloud::accessKeyClient('你的access_key_id', '你的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'          => '你的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;
	
	    }
	
	}
	

你可能感兴趣的:(阿里云,php,短信)