关于TP短信验证码发送功能实现
以京东万象为例:
注册账号选择短信接口
第一步:封装公共函数
1.使用curl发送请求
if (!function_exists('curl_request')) {
//使用curl函数库发送请求
function curl_request($url, $post = true, $params = [], $https = true)
{
//初始化请求
$ch = curl_init($url);
//默认是get请求。如果是post请求 设置请求方式和请求参数
if ($post) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
}
//如果是https协议,禁止从服务器验证本地证书
if ($https) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
//发送请求,获取返回结果
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res = curl_exec($ch);
/*if(!$res){
$msg = curl_error($ch);
dump($msg);die;
}*/
//关闭请求
curl_close($ch);
return $res;
}
}
2.封装方法用于发送短信
if (!function_exists('sendmsg')) {
//使用curl_request函数调用短信接口发送短信
function sendmsg($phone, $content)
{
//从配置中取出请求地址、appkey
$gateway = config('msg.gateway');
$appkey = config('msg.appkey');
//https://way.jd.com/chuangxin/dxjk?mobile=13568813957&content=【创信】你的验证码是:5873,3分钟内有效!&appkey=您申请的APPKEY
$url = $gateway . '?appkey=' . $appkey . "&content=" . $content . "&mobile=" . $phone;
//get请求
$url .= '&mobile=' . $phone . '&content=' . $content;
$res = curl_request($url, false, [], true);
//处理结果
if (!$res) {
return '请求发送失败';
}
//解析结果
$arr = json_decode($res, true);
if (isset($arr['code']) && $arr['code'] == 10000) {
//短信接口调用成功
return true;
} else {
/*if(isset($arr['msg'])){
return $arr['msg'];
}*/
return '短信发送失败';
}
}
第二步:配置中修改接口参数
//短信配置
'msg' => [
'gateway' => "***",
'appkey' => '***',
]
第三步:调用接口发送短信
public function getcode(Request $request){
$phone = '***';
$content = "【创信】你的验证码是:5873,3分钟内有效!";
$res = sendmsg($phone,$content);
if($res){
return json(['code' => 200, 'msg' => '验证码已发送成功,请注意查收', 'data' => '']);
}
}