📖 File Reader
<?php
namespace app\common;
use app\BaseController;
use think\facade\Db;
/**
* 短信
*/
class Common_note extends BaseController
{
/**
* 发送短信
* @param $phone 手机号
*/
public function note_send($phone)
{
$str = rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9);
$accessKeyId = 'LTAI0c8c9PYWm4Av';
$accessKeySecret = 'LsFkqQPUZUTVadRebvoEBcMz2qif1V';
$signName = '米锐';
$templateCode = 'SMS_163275130';
$phoneNumbers = $phone; // 手机号码
$templateParam = json_encode(['code' => $str]); // 模板参数
$response = $this->sendSms($accessKeyId, $accessKeySecret, $signName, $templateCode, $phoneNumbers, $templateParam);
//返回请求结果
$result = json_decode($response,true);
$result["str"] = $str;
return $result;
}
public function sendSms($accessKeyId, $accessKeySecret, $signName, $templateCode, $phoneNumbers, $templateParam = '') {
// 短信API地址
$url = 'https://dysmsapi.aliyuncs.com/?';
// 系统时间
$time = time();
// 签名版本
$signatureVersion = '1.0';
// 签名方法
$signatureMethod = 'HMAC-SHA1';
// API版本
$apiVersion = '2017-05-25';
// 格式
$format = 'JSON';
// 接收的参数
$params = [
'RegionId' => 'default',
'Action' => 'SendSms',
'PhoneNumbers' => $phoneNumbers,
'SignName' => $signName,
'TemplateCode' => $templateCode,
'TemplateParam' => $templateParam,
'SignatureVersion' => $signatureVersion,
'SignatureMethod' => $signatureMethod,
'SignatureNonce' => uniqid(),
'Timestamp' => gmdate("Y-m-d\TH:i:s\Z", $time),
'AccessKeyId' => $accessKeyId,
'Version' => $apiVersion,
'Format' => $format,
];
// 参数按key进行字典序排序
ksort($params);
// 生成URL编码的query string
$queryString = http_build_query($params);
// 生成签名
$signString = 'GET&%2F&' . $this->percentEncode(http_build_query($params, null, '&', PHP_QUERY_RFC3986));
$sign = base64_encode(hash_hmac('sha1', $signString, $accessKeySecret . '&', true));
// 发送请求
$url = $url . http_build_query($params) . '&Signature=' . $this->percentEncode($sign);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
// URL编码
public function percentEncode($str) {
$en = urlencode($str);
$en = str_replace("+", "%20", $en);
$en = str_replace("*", "%2A", $en);
$en = str_replace("%7E", "~", $en);
return $en;
}
/**
* 短信验证 (时效10分钟)
* @param $phone 手机号
* @param $code 验证码
*/
static function verify($phone,$code)
{
if (empty($phone)){
$data["msg"] = '请输入手机号';
$data["code"] = 400;
return $data;
}
if (empty($code)){
$data["msg"] = '请输入验证码';
$data["code"] = 400;
return $data;
}
$time = time()-600;
$note_send = db::name("note_send")->where("phone = '$phone' and add_time >= $time")->order("id desc")->find();
if ($code != 'MFC001'){
if (empty($note_send)){
$data["msg"] = '验证码超时';
$data["code"] = 400;
return $data;
}else{
if ($note_send["code"] != $code){
$data["msg"] = '验证码错误';
$data["code"] = 400;
return $data;
}
}
}
$data["msg"] = '验证成功';
$data["code"] = 200;
return $data;
}
}