public static function VerificationCode(Request $request){
AlibabaCloud::accessKeyClient('输入阿里云ID', '输入阿里云sercet')
->regionId('cn-hangzhou')
->asDefaultClient();
$user_phone = $request->get('phone');
$user = Distributors::where(['mobile'=>$user_phone,'status'=>1])->select('uid','mobile','status')->first();
if(empty($user)){
return new JsonResponse(['code' => '4100014','message' => '请输入绑定签署合同的手机号','data'=>'']);
}
$results = '';//验证码
$results .= mt_rand(10000000, 99999999);
$data =$results+time();
$code =substr($data,4);
try {
$result = AlibabaCloud::rpc()
->product('Dysmsapi')
->version('2017-05-25')
->action('SendSms')
->method('POST')
->host('dysmsapi.aliyuncs.com')
->options([
'query' => [
'PhoneNumbers' => "$user_phone",
'SignName' => "签名",
'TemplateCode' => "SMS_模板",
'TemplateParam' => json_encode(['code' => $code])
],
])
->request();
if($result->toArray()){
Cache::put('code',$code,5);//验证码存入缓存并且五分钟有效时间
Cache::put('phone',$user_phone,5);//手机号存入缓存并且五分钟有效时间
return new JsonResponse(['code' => '200','message' => '发送短信成功','data'=>'']);
}
} catch (ClientException $e) {
echo $e->getErrorMessage() . PHP_EOL;
} catch (ServerException $e) {
echo $e->getErrorMessage() . PHP_EOL;
}
}
第二种方法:
composer.json 加文件 overtrue/easy-sms": "^1.1",
代码:
public function index(Request $request)
{
$content = $request->only(['phone', 'type']);
$val = Validator::make($content, [
'phone' => 'required',
'type' => 'required'
]);
if ($val->fails()) {
throw new AppException($val->errors()->first());
}
/**
* 接入短信
*/
$easySms = new EasySms(config('sms'));
$code = rand(1000, 9999);
$verification = $easySms->send($content['phone'], [
'template' => 'SMS_',
'data' => [
'code' => $code
],
]);
if (!$verification) {
error('发送失败');
}
Cache::put($content['type'] . $content['phone'], $code, 300);//手机号存入缓存并且五分钟有效时间
}
配置文件config里新建sms类:
return [
// HTTP 请求的超时时间(秒)
'timeout' => 5.0,
// 默认发送配置
'default' => [
// 网关调用策略,默认:顺序调用
'strategy' => \Overtrue\EasySms\Strategies\OrderStrategy::class,
// 默认可用的发送网关
'gateways' => [
'aliyun',
],
],
// 可用的网关配置
'gateways' => [
'errorlog' => [
'file' => '/tmp/easy-sms.log',
],
'aliyun' => [
'access_key_id' => env('SMS_ACCESS_KEY_ID'),
'access_key_secret' => env('SMS_ACCESS_KEY_SECRET'),
'sign_name' => env('SMS_SIGN_NAME'),
],
//...
],
];