方法一:
1,composer下载:
composer require mrgoon/aliyun-sms
2,验证方法代码:
//短信验证
public function sms(Request $request){
// 接收参数
$tel = $request->get('tel');
//随机生成验证码
$code = mt_rand(100000,999999);
//验证码存redis
Cache::set("tel_".$tel,$code,300);
// 验证码发手机
$config = [
'access_key' => "你自己的accessKey",//appID
'access_secret' => "你自己的accessSecret",// appKey
'sign_name' => "signName",// 签名
];
$sms = new AliSms();
//$response = $sms->sendSms('phone number', 'tempplate code', ['name'=> 'value in your template'], $config);
$response = $sms->sendSms($tel, 'SMS_150575093', ['code'=> $code], $config);// 'code' 是模板里的 $code 是上面是生成的
if ($response){
return json("获取验证码成功".$response);
}else{
return json("获取短信验证码失败");
}
}
方法二
function send_sms($tel){
// 获取配置信息
$code = rand(0000,9999);
$accessKeyId = 'AccessKeyID'; // 阿里云
$accessKeySecret = 'AccessKeySecret'; // 阿里云 AccessKeySecret
$templateCode = ''; // 短信模板ID
$signName=''; // 短信签名
$params = array (
'SignName' => $signName,
'Format' => 'JSON',
'Version' => '2017-05-25',
'AccessKeyId' => $accessKeyId,
'SignatureVersion' => '1.0',
'SignatureMethod' => 'HMAC-SHA1',
'SignatureNonce' => uniqid(),
'Timestamp' => gmdate('Y-m-d\TH:i:s\Z'),
'Action' => 'SendSms',
'TemplateCode' => $templateCode,
'PhoneNumbers' => $tel,
// 营销短信无需 TemplateParam 参数
'TemplateParam' => '{"code":"' . $code . '"}'
);
// 计算签名并把签名结果加入请求参数
$params ['Signature'] = computeSignature($params, $accessKeySecret);
// 发送请求
$url = 'http://dysmsapi.aliyuncs.com/?' . http_build_query($params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$result = curl_exec($ch);
curl_close($ch);
//返回请求结果
$result = json_decode($result,true);
if ($result['Code']=="isv.MOBILE_NUMBER_ILLEGAL"){
$data = ['code'=>400, 'msg'=>'非法手机号','sms'=>''];
return $data;
}elseif ($result['Code']=="isv.OUT_OF_SERVICE"){
$data = ['code'=>400, 'msg'=>'短信业务已停机,联系管理请联系管理员','sms'=>''];
return $data;
}elseif ($result['Code']=="isv.BUSINESS_LIMIT_CONTROL"){
$data = ['code'=>400, 'msg'=>'当前手机号发送频率过高,请稍后再试','sms'=>''];
return $data;
}else{
$data = ['code'=>200, 'msg'=>'ok','sms'=>$code];
return $data;
}
}
function computeSignature($parameters, $accessKeySecret) {
ksort($parameters);
$canonicalizedQueryString = '';
foreach ($parameters as $key => $value) {
$canonicalizedQueryString .= '&' .percentEncode($key) . '=' . percentEncode($value);
}
$stringToSign = 'GET&%2F&' . percentencode ( substr ( $canonicalizedQueryString, 1 ) );
$signature = base64_encode(hash_hmac('sha1', $stringToSign, $accessKeySecret . '&', true));
return $signature;
}
function percentEncode($string) {
$string = urlencode($string);
$string = preg_replace('/\+/', '%20', $string);
$string = preg_replace('/\*/', '%2A', $string);
$string = preg_replace('/%7E/', '~', $string);
return $string;
}