待发短信

在线客服
产品支持 短信宝客服
合作渠道 渠道合作
服务咨询

4001-021-502

工作时间

9:00-21:00

Tipask问答系统新增短信宝短信接口

Tipask是一款100%开放源码的PHP问答系统,基于Laravel5.6 LTS 版本开发,容易扩展,具有强大的负载能力和稳定性。今天小编就以替换短信接口为例一步一步教大家如何开发,进行替换的短信接口是我们短信宝短信群发平台的短信接口,我们短信宝短信接口非常稳定,发送速度快,注册还送测试短信,推荐大家使用。

首先我们打开项目\resources\views\themes\default\account\forgetPassword.blade.php文件替换30~58行左右的代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
            @if(Setting()->get('mobile_trun') == 1)
                <div class="form-group">
                    <label class="required">选择找回密码方式</label>
                    <div class="radio">
   <label><input type="radio" name="emamobile" class="emamobile" value="1" checked="">邮箱</label>
  <label><input type="radio" name="emamobile" class="emamobile" value="0">短信</label>
                    </div>      </div>
                <div class="form-group mobile @if($errors->first('mobile')) has-error @endif" style="display: none;">
                    <label class="required">手机</label>
  <input type="text" id="mobile" class="form-control" name="mobile" placeholder="注册手机" value="{{old('mobile')}}">
 @if ($errors->first('mobile')) <span class="help-block">{{$errors->first('mobile')}}</span>   @endif
  </div> <div class="form-group mobile @if($errors->first('mobile_code')) has-error @endif" style="display: none;">
                    <label for="mobile_code" class="required">短信验证码</label>
                    <div class="col-md-12" style="padding-left: 0;">
                        <div class="col-md-8" style="padding-left: 0;">
    <input type="text" class="form-control" name="mobile_code" id="mobile_code" placeholder="请输入短信验证码">
     </div> <b class="btn btn-primary" id="btn-code" style="margin-bottom: 15px;">获取验证码</b>
                        @if ($errors->first('mobile_code'))
                            <span class="help-block">{{$errors->first('mobile_code')}}</span>
                        @endif
                    </div>
                </div>
            @endif
                <div class="form-group email @if ($errors->first('email')) has-error @endif">

接着我们添加获取短信验证码的js代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
@section('js')
    <script type="text/javascript">
        $('.emamobile').on('click',function(){
            var $this = $(this).val();
            if ($this == '0') {
                $('.mobile').css('display','block');
                $('.email').css('display','none');
            }else{
                $('.email').css('display','block');
                $('.mobile').css('display','none');
            }
        })
    </script>
    <script type="text/javascript">
        var time = 0; //倒计时时间
        var res = null//倒计时资源,释放时使用
        var sendNode = null//发送的按钮节点
 
        function sendTime(){
            clearTimeout(res);
            time--;
 
            if (time <= 0) {
                time = "获取验证码";
                sendNode.text(time);
                clearTimeout(res);
                time = 0;
                return;
            }
 
            sendNode.text("剩余"+time+"秒");
            res = setTimeout("sendTime()",1000);
        }
 
        $(function(){
            sendNode = $("#btn-code");
            var flg = true;
 
            sendNode.click(function(){
                if (time == 0) {
                    var mobile = $('#mobile').val();
                    var reg = /^1[3,4,5,7,8]\d{9}$/;
                    var ret = false;
                    if (!reg.test(mobile)) {
                        alert('手机号码不正确!');
                        return ret;
                    }
 
                    if ({{Setting()->get('code_register')}} == 1) {
                        var code = $("#captcha").val();
                        if (code == '') {
                            alert('请输入验证码');
                            return ret;
                        }
                        var data = {"captcha":code,"mobile":mobile};
 
                    }else{
                       var data = {"mobile":mobile};
                    }
                    var err ="";
                    if (flg == true) {
                        flg = false;
                        $.ajax({
                            type:"POST",
                            url:"{{ route('auth.user.forget_mobile_code') }}",
                            dataType:"html",
                            async:false,
                            data:data,
                            success:function(data){
                                if (data == 'ok') {
                                    time = 60;
                                    sendTime();
                                    alert('短信发送成功');
                                    flg = true;
                                }else if(data == '-1'){
                                    alert('手机号不存在');
                                }else{
                                    alert('短信发送失败'+data);
                                }
                            },
                            error:function(data){
                                var errors = unescape(data['responseText'].replace(/\\/g,"%"));
                                var error = JSON.parse(errors);
                                if (error['captcha'] != ''&&error['captcha']) {
                                    alert(error['captcha']);
                                    return false;
                                }
 
                                if (error['mobile'] != '' && error['mobile']) {
                                    alert(error['mobile']);
                                    return false;
                                }
                            }
                        })
                    }
                }
            })
        })
    </script>
@endsection

接着我们打开项目\resources\views\themes\default\account\register.blade.php文件,在33~53行左右添加以下代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
      @if(Setting()->get('mobile_trun') == 1)
                <div class="form-group @if ($errors->first('mobile')) has-error @endif">
                    <label for="mobile" class="required">Mobile(手机)</label>
  <input type="text" class="form-control" id="mobile" name="mobile" required="" placeholder="请输入手机">
                    @if ($errors->first('mobile'))
                        <span class="help-block">{{ $errors->first('mobile') }}</span>
                    @endif
                </div>
                <div class="form-group @if($errors->first('mobile_code')) has-error @endif">
                    <label for="mobile_code" class="required">短信验证码</label>
                    <div class="col-md-12" style="padding-left: 0;">
                        <div class="col-md-8" style="padding-left: 0;">
           <input type="text" class="form-control" name="mobile_code" id="mobile_code" required="" placeholder="请输入短信验证码">
                        </div>    
                    <b class="btn btn-primary" id="btn-code" style="margin-bottom: 15px;">获取验证码</b>
                    @if ($errors->first('mobile_code'))
                        <span class="help-block">{{ $errors->first('mobile_code') }}</span>
                    @endif
                    </div>
                </div>
            @endif
           

接着添加js代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
@section('js')
    <script> 
        var time = 0;
        var res = null;
        function sendTime(){
            clearTimeout(res); 
            time --;
 
            if (time <= 0) {
                time = "获取验证码";
                $('#btn-code').text(time);
                clearTimeout(res);
                time = 0;
                return;
            }
 
            $('#btn-code').text("剩余"+time+"秒");
            res = setTimeout("sendTime()",1000);
        }
 
        $(function(){
            var flg = true;
            $('#btn-code').on('click',function(){
                var mobile = $('#mobile').val();
                var reg = /^1[3,4,5,7,8]\d{9}$/;
                var ret = false;
                if (!reg.test(mobile)) {
                    alert('手机号码不正确!');
                    return ret;
                }
                if ({{Setting()->get('code_register')}} == 1) {
                    var code = $("#captcha").val();
                    if (code == '') {
                        alert('请输入验证码');
                        return ret;
                    }
                    var data = {"captcha":code,"mobile":mobile};
 
                }else{
                   var data = {"mobile":mobile};
                }
                var err ="";
                if (flg == true) {
                    flg = false;
                    $.ajax({
                        type:"POST",
                        url: "{{ route('auth.user.mobile_code') }}",
                        dataType : "html",
                        async : false,
                        data : data,
                        success:function(data){
                            if (data == "ok") {
                                time = 60;
                                sendTime();
                                alert('短信发送成功');
                                flg = true;
                            }else{
                                alert('短信发送失败请联系管理员。');
                                flg = true;
                            }
                        },
                        error:function(data){
                            var errors = unescape(data['responseText'].replace(/\\/g, "%"));
                            var error = JSON.parse(errors);
                            if(error['mobile'] != ''&&error['mobile'] ){
                                alert(error['mobile']);
                                return false;
                            }
                            if (error['captcha']&&error['captcha']!='') {
                                alert(error['captcha']);
                                return false;
                            }
 
                        }
                    });
                }
                return flg;
            })
 
        })
 
    </script>
@endsection

添加完成之后,我们在打开\resources\views\admin\public\menu.blade.php文件,在13行左右添加以下代码:

?
1
<li><a href="{{ route('admin.setting.mobile') }}"><i class="fa fa-circle-o"></i> 短信设置</a></li>

然后我们打开项目\resources\views\admin\setting\irrigation.blade.php文件,在71行左右添加以下代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
            <h3 class="box-title">短信策略</h3>
                        </div>
                        <div class="box-body">
                            <div class="form-group">
                                <label for="website_url">开启</label>
                                <span class="text-muted">(开启后必须使用短信进行验证)</span>
                                <div class="radio">
  <label><input type="radio" name="mobile_trun" value="1" @if(Setting()->get('mobile_trun') == 1) checked @endif>开启</label>
    <label><input type="radio" name="mobile_trun" value="0" @if(Setting()->get('mobile_trun') == 0) checked @endif>关闭</label>
                                </div>                            </div>
                        </div>
                    </div>
                    <div class="box box-default">
                        <div class="box-header with-border">

接着我们在项目\resources\views\admin\setting\下创建mobile.blade.php文件:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
@extends('admin/public/layout')
@section('title')短信配置@endsection
@section('content')
    <section class="content-header">
        <h1>短信配置</h1>
    </section>
    <section class="content">
     <div class="row">
        <div class="col-xs-12">
          <div class="box box-primary">
             <form role="form" name="settingForm" method="POST" action="{{ route('admin.setting.mobile') }}">
               <input type="hidden" name="_token" value="{{ csrf_token() }}">
                 <div class="box-body">
                   <div class="form-group @if ($errors->has('smsbao_user')) has-error @endif">
  <label for="smsbao_user">短信宝用户名</label>
    <span class="text-muted">(还没有短信宝帐号?<a href="http://www.smsbao.com/">注册</a>)</span>
    <input type="text" name="smsbao_user" class="form-control " placeholder="短信宝用户名" value="{{ old('smsbao_user',Setting()->get('smsbao_user')) }}">
      @if ($errors->has('smsbao_user')) <p class="help-block">{{ $errors->first('smsbao_user') }}</p> @endif
       </div>  <div class="form-group @if ($errors->has('smsbao_pass')) has-error @endif">   <label for="smsbao_pass">短信宝密码</label>
      <span class="text-muted">(请输入短信宝密码)</span>
      <input type="password" name="smsbao_pass" class="form-control " placeholder="短信宝密码" value="{{ old('smsbao_pass',Setting()->get('smsbao_pass')) }}">
      @if ($errors->has('smsbao_pass')) <p class="help-block">{{ $errors->first('smsbao_pass') }}</p> @endif
      </div> <div class="form-group  @if ($errors->has('smsbao_sign')) has-error @endif">
     <label for="smsbao_sign">短信宝签名</label>        <span class="text-muted">(请输入短信宝签名)</span>
     <input type="text" name="smsbao_sign" class="form-control " placeholder="短信宝签名" value="{{ old('smsbao_sign',Setting()->get('smsbao_sign')) }}">
    @if ($errors->has('smsbao_sign')) <p class="help-block">{{ $errors->first('smsbao_sign') }}</p> @endif
     </div>  </div>      <div class="box-footer">
                            <button type="submit"  class="btn btn-primary">保存</button>
                            <button type="button" class="btn btn-success" id="btn_test_mobile" >发送测试短信</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </section>
@endsection
@section('script')
    <div class="modal fade" id="test_mobile_model"  role="dialog">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="exampleModalLabel">发送测试短信</h4>
                </div>
                <div class="modal-body">
                    <form name="messageForm" id="message_form">
                        <div class="form-group">
                            <label for="to_user_id" class="control-label">接收人手机号:</label>
                            <input type="mobile" class="form-control" id="test_send_to" name="sendTo" value="" placeholder="接收人手机号" />
                        </div>
                        <div class="form-group">
                            <label for="message-text" class="control-label">内容:</label>
                            <textarea class="form-control" id="test_mobile_content" name="content">你好,这是一条测试短信。收到短信则短信接口正常使用!</textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="submit_test_mobile">发送</button>
                </div>
            </div>
        </div>
    </div>
    <script type="text/javascript">    
        $(function(){
            set_active_menu('global',"{{ route('admin.setting.mobile') }}");
            $("#btn_test_mobile").click(function(){
                if(confirm('请确认短信配置项已保存成功?')){
                    $("#test_mobile_model").modal('show');
                }
            });
            /*发送测试邮件*/
            $("#submit_test_mobile").click(function(){
                var sendTo = $("#test_send_to").val();
                var content = $("#test_mobile_content").val();
                $.post('{{ route('admin.tool.sendTestMobile') }}',{sendTo:sendTo,content:content},function(msg){
                    console.log(msg);
                    if(msg == 'ok'){
                        alert('短信发送成功');
                    }else{
                        alert('短信发送错误:'+ msg );
                    }
                    $("#test_mobile_model").modal('hide');
                });
            });
 
        });
    </script>
@endsection

打开项目\app\Http\routes.php文件在49行左右添加以下代码:

?
1
2
  Route::match(['get','post'],'mobile_code',['as'=>'auth.user.mobile_code','uses'=>'UserController@mobile_code']);
    Route::match(['get','post'],'forget_mobile_code',['as'=>'auth.user.forget_mobile_code','uses'=>'UserController@forget_mobile_code']);

在315行左右添加短信设置代码,406行左右工具管理处添加第二行代码:

?
1
2
3
4
5
/*短信设置*/
    Route::any('setting/mobile',['as'=>'admin.setting.mobile','uses'=>'SettingController@mobile']);
 
 Route::post('tool/sendTestMobile',['as'=>'admin.tool.sendTestMobile','uses'=>'ToolController@sendTestMobile']);
 

添加完成之后打开项目\app\Http\Controllers\Controller.php文件,添加sendSms短信发送方法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
    /*短信发送*/
    protected function sendSms($mobile,$content)
    {
        $user = Setting()->get('smsbao_user');
        $pass = Setting()->get('smsbao_pass');
        $sign = Setting()->get('smsbao_sign');
 
        if (empty($user) || empty($pass) || empty($sign) ) {
            return '11';
        }
        $url 'http://api.smsbao.com/sms?u='.$user.'&p='.md5($pass).'&m='.$mobile.'&c=【'.$sign.'】'.$content;
        $ret file_get_contents($url);
        if ($ret == 0) {
            return 'ok';
        }else{
            return $ret;
        }
    }

接着打开项目\app\Http\Controllers\Account\UserController.php文件,在108行左右添加验证短信验证码代码:

?
1
2
3
4
5
6
7
8
9
10
       if (Setting()->get('mobile_trun') == 1) {
               $validateRules['mobile'] = 'required|regex:/^1[3,4,5,7,8]\d{9}$/|unique:users';
               if (empty(session('mobile_code')) || $request->mobile_code != session('mobile_code')) {
                    return redirect(route('auth.user.register'))
                        ->withInput($request->only('mobile_code'))
                        ->withErrors([
                            'mobile_code' => '短信验证码错误!',
                        ]);
               }
            }

接着在158行左右添加mobile_codeforget_mobile_code方法,代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
 public function mobile_code(Request $request)
    {
            if( Setting()->get('code_register') == 1){
                $validateRules['captcha'] = 'required|captcha';
            }
            $validateRules['mobile'] = 'required|regex:/^1[3,4,5,7,8]\d{9}$/|unique:users';
            
            $this->validate($request,$validateRules);
            $code = rand(10000,99999);
            session(['mobile_code'=>$code]);
            $content '您好,您的验证码为:'.$code.',请妥善保存。';
            $ret =  $this->sendSms($request->mobile,$content);
 
            if ($ret == 'ok') {
                return 'ok';
            }else{
                return json_encode($ret);
            }
    }
 
    public function forget_mobile_code(Request $request)
    {
        if( Setting()->get('code_register') == 1){
            $validateRules['captcha'] = 'required|captcha';
        }
 
         $user = User::where('mobile','=',$request->mobile)->first();
 
         if (empty($user)) {
             return json_encode('-1');
         }
 
         $code = rand(10000,99999);
         session(['mobile_code'=>$code]);
         session(['forget_mobile'=>$request->mobile]);
         $content '您好,您正在进行找回密码操作,验证码为:'.$code.',请妥善保存!';
         $ret $this->sendSms($request->mobile,$content);
         if ($ret == 'ok') {
             return 'ok';
         }else{
            return json_encode($ret);
         }
    }

添加完成之后再去修改forgetPassword方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*忘记密码*/
    public function forgetPassword(Request $request)
    {
 
        if($request->isMethod('post'))
        {   
            if (Setting()->get('mobile_trun') == 1) {
                if (empty(session('mobile_code')) || $request->mobile_code != session('mobile_code')) {
                    return redirect(route('auth.user.forgetPassword'))
                        ->withInput($request->only('mobile_code'))
                        ->withErrors([
                            'mobile_code' => '短信验证码错误!',
                        ]);
               }
            if (empty(session('forget_mobile')) || $request->mobile != session('forget_mobile')) {
                   return redirect(route('auth.user.forgetPassword'))->withInput($request->only('forget_mobile'))
                   ->withErrors(['forget_mobile'=>'手机号不正确']);
               }   
            $content '您好,您正在进行找回密码操作,新的密码为:123456,请您尽快修改密码';
            $ret $this->sendSms($request->mobile,$content);
            if ($ret == 'ok') {
                $data['password'] = bcrypt('123456');
                User::where('mobile','=',$request->mobile)->update($data);
            return  $this->success(route('auth.user.login'),'密码修改成功,请重新登录');;
            }else{
               return  redirect(route('auth.user.login'))
                ->withInput($request->only('mobile'))
                ->withErrors([
                    'mobile' => '错误',
                ]);
            }
 
            }
            $request->flashOnly('email');
            /*表单数据校验*/
            $this->validate($request, [
                // 'email' => 'required|email|exists:users',
                'captcha' => 'required|captcha'
            ]);
 
            $emailToken = EmailToken::create([
                'email' =>  $request->input('email'),
                'token' => EmailToken::createToken(),
                'action'=> 'findPassword'
            ]);
            if($emailToken){
                $subject = Setting()->get('website_name').' 找回密码通知';
                $content "如果您在 ".Setting()->get('website_name')."的密码丢失,请点击下方链接找回 → ".route('auth.user.findPassword',['token'=>$emailToken->token])."<br />如非本人操作,请忽略此邮件!";
                $this->sendEmail($emailToken->email,$subject,$content);
            }
            return view("theme::account.forgetPassword")->with('success','ok')->with('email',$request->input('email'));
 
        }
 
        return view("theme::account.forgetPassword");
 
    }

然后我们打开项目\app\Http\Controllers\Admin\SettingController.php文件,添加短信配置方法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 /*短信配置*/
    public function mobile(Request $request)
    {
        if ($request->isMethod('post')) {
            $data $request->except('_token');
            unset($data['_token']);
            foreach ($data as $name => $value) {
                $_ENV[strtoupper($name)] = $value;
                Setting()->set($name,$value);
            }
            Setting()->clearAll();
            Setting()->writeToEnv();
            return $this->success(route('admin.setting.mobile'),'短信配置保存成功');
        }
        return view('admin.setting.mobile');
    }

接着我们在项目\app\Http\Controllers\Admin\ToolController.php文件中添加sendTestMobile方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    public function sendTestMobile(Request $request)
    {
        $validateRules = [
            'sendTo' => 'required|regex:/^1[3,4,5,7,8]\d{9}$/',
            'content' => 'required|max:255',
        ];
        $this->validate($request,$validateRules);
        $user = Setting()->get('smsbao_user');
        $pass = Setting()->get('smsbao_pass');
        if (empty($user) && empty($pass)) {
            return '请填写短信宝用户名和密码。';
        }
        $url 'http://api.smsbao.com/sms?u='.$user.'&p='.md5($pass).'&m='.$request->sendTo.'&c='.$request->content;
        $ret file_get_contents($url);
        if ($ret == 0) {
            return 'ok';
        }else{
            return $ret;
        }
    }

接着打开项目\app\Models\User.php文件,将36行代码修改为以下代码:

?
1
 protected $fillable = ['name''email''password','status','mobile','site_notifications','email_notifications',''];

最后打开项目\app\Services\Registrar.php文件,修改create方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 public function create(array $data)
    {
        $user =  User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'mobile' => $data['mobile'],
            'status' => $data['status'],
            'site_notifications' => 'follow_user,invite_answer,comment_question,comment_article,adopt_answer,comment_answer,reply_comment',
            'email_notifications' => 'adopt_answer,invite_answer'
        ]);
 
        if($user){
            UserData::create([
                'user_id' => $user->id,
                'coins' => 0,
                'credits' => 20,
                'registered_at' => Carbon::now(),
                'last_visit' => Carbon::now(),
                'last_login_ip' => $data['visit_ip'],
            ]);
        }
 
        return $user;
    }

好了,经过以上的替换,短信宝的短信平台已经替换成功了,可以正常使用了。我们进行测试发送。

报备一下短信宝的VIP模板,这样就可以走短信宝的优质通道了,即便遇到敏感文字我们都不会人工审核,短信内容3~5秒就可送达。

另外:我们已经开发好完整的Tipask问答系统短信宝插件,点击此链接 下载及查看安装流程。

开源插件

最新更新

电商类

CMS类

微信类

文章标签