欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

PHP发送短信

程序员文章站 2022-03-20 16:17:51
1.要拼接接收的手机号和短信 2.拼接要发送短信的要求 3.向第三方发送请求 ......

1.要拼接接收的手机号和短信

 public function sendcode()
    {
        $parpm = input();
        $valist = $this->validate($parpm, [
            'phone' => 'require|regex:1[3-9]\d{9}'
        ]);
        if ($valist !== true) {
            $res = [
                'code' => 400,
                'msg' => $valist
            ];
            return json($res);
            die;
        }
        $timer = cache('register_time_' . $parpm['phone']);
        if (time() - $timer < 60) {
            $rs = [
                'code' => '500',
                'msg' => '发送太过频繁'
            ];
            echo json_encode($rs);
            die;
        }
        $co = mt_rand(1000, 9999);
        $code = '%23code%23%3d' . $co;
        //发送短信验证
//          $resule=sendmsg($parpm['phone'],$code);
        $resule = true;
        if ($resule === true) {
            cache('register_code_' . $parpm['phone'], $co, 180);
            cache('register_time_' . $parpm['phone'], time(), 180);
            $re = [
                'code' => 200,
                'msg' => '短信发送成功',
                'data' => "$code"
            ];
            echo json_encode($re);
            die;
        } else {
            $re = [
                'code' => 400,
                'msg' => $resule
            ];
            echo json_encode($re);
            die;
        }
    }

2.拼接要发送短信的要求

if(!function_exists('sendmsg')){
     function sendmsg($phone,$code){
         $gateway=config('msg.gateway');
         $appkey=config('msg.appkey');
         $tpl_id=config('msg.tpl_id');
         $url=$gateway.'?mobile='.$phone.'&tpl_id='.$tpl_id.'&tpl_value='.$code.'&key='.$appkey;
         $res=curl_require($url,false,[],false);
         if(!$res){
            return '请求失败';
         }
         $arr=json_decode($res,true);
         if(isset($arr['code'])&&$arr['code']==10000){
              return true;
         }else{
             return false;
         }
     }
}

3.向第三方发送请求

if(!function_exists('curl_require')){
      function curl_require($url,$post=true,$parpm=[],$https=false){
          $ch=curl_init($url);
          if($post){
                curl_setopt($ch,curlopt_port,true);
                curl_setopt($ch,curlopt_postfields,$parpm);
          }
          if($https){
               curl_setopt($ch,curlopt_ssl_verifypeer,false);
          }
          curl_setopt($ch,curlopt_returntransfer,true);
          $res=curl_exec($ch);
          curl_close($ch);
          return $res;
      }
}