Dragon-v

PHP TP5 实现短信发送 此API为京东万象

1.编写前台表单页面

<form action="phoneDo" method="post">
  <input type="text" name="phone">
  <button type="submit">发送</button>
</form>

2.后台接收手机号并编写短信内容

public function phoneDo(){
  //接受前台表单传来的电话号
  $phone=input('phone');
  //生成四位随机数 可以把四位随机数存入缓存,用于后期验证
  $num=rand(1000,9999);
  //编写短信内容
  $content="【龍】你的验证码是:".$num.",3分钟内有效!";
  //调用
  $res=sendmsg($phone,$content);
  //输出返回值
echo $res;
}

3.在application/commom.php中编写发送短信的代码

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;
  }
}
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 '短信发送成功';
    }else{
      /*if(isset($arr['msg'])){
      return $arr['msg'];
    }*/
    return '短信发送失败';
    }
  }
}

4.在application/config.php下新加配置

msg' =>[
  'gateway'=>'请求网址',
  'appkey'=>'密钥'
]

请求网址与密钥的获取下方均有

注:此两处要保持一直

5.密钥获取方式:注册成功之后,点击箭头所指按钮,或跳出一个框,红色加粗部分便是密钥

6.网址的获取方式:箭头所指便是请求网址

  注:京东万象免费测试五次机会手机并不会收到短信,但可输出成功数据,只有购买短信后手机方可收到短信通知!!!

posted on 2021-08-21 08:14  Dragon-v  阅读(76)  评论(0编辑  收藏  举报