Laravel实现短信发送验证码注册

前端代码




    
    
    
    
    
    Document


后端接口

路由:
Route::get("create", "SmsController@create")->name("create");//注册表单
Route::get("register", "SmsController@register")->name("register");//注册动作
Route::post("sendcode", "SmsController@sendcode")->name("sendcode");//发送验证码
控制器代码:
public function sendcode(Request $request){
        $mobile = $request->input('mobile');
        $request->validate([
            'mobile' => ['required', 'regex:/^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199)\d{8}$/']
        ]);
        // 验证码
        $code = mt_rand(1000, 9999);
        // 将验证码 存入session中
        $request->session()->put('verify_code', $code);
        // 设置验证码有效时间
        $time = 5;
        // 发送内容
        $content = urldecode("您的验证码为{$code},在{$time}分钟内有效。");
        //发送
        $result = $this->sendMsg($mobile, $content);

        if ($result !== "0") {
            return response()->json(['code' => 0, 'msg' => '发送失败']);
        } else {
            return response()->json(['code' => 1, "msg" => "发送成功"]);
        }
    }

    protected function sendMsg($mobile, $message){
        // 短信发送接口    这是用的短信宝的接口
        $username = "********";
        $password = md5("********");
        $url = "http://api.smsbao.com/sms?u={$username}&p={$password}&m={$mobile}&c={$message}";
        // 发送请求
        $result = $this->curlRequest($url);
        Log::debug($result);
        return $result;
    }
请求函数:
// curl 发送http 请求
    private function curlRequest($url, $post='')
    {
        // 初始化
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');

        // post请求
        if($post) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
        }

        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        // 执行请求
        $data = curl_exec($curl);
        if(curl_exec($curl) === false) {
            return 'Curl error: ' . curl_error($curl);
        } else {
            curl_close($curl);
            return $data;
        }
    }

你可能感兴趣的:(Laravel实现短信发送验证码注册)