php调用接口发送短信

首先在各平台上申请短信接口权限

我是在京东万象上申请的短信权限,发送短信权限都是有测试次数,不用收费
在这里插入图片描述

我们可以看到请求参数、返回参数、返回示例值,按照他的格式就可以进行访问接口来进行发送短信操作,需要注意的是因为是测试数据,没有购买所以这里的content是不能自定义的,只能按照他的要求来写:【凯信通】您的验证码是:$code,appkey当你注册京东万象完成之后就可以查看自己的appkey。

在这里插入图片描述

我这里使用的是thinkphp5框架

1、发送短信的前台页面
<!DOCTYPE html>
<html>

<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE">
	<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
	<title>个人注册</title>

    <link rel="stylesheet" type="text/css" href="/static/home/css/all.css" />
    <link rel="stylesheet" type="text/css" href="/static/home/css/pages-register.css" />
    
	<script type="text/javascript" src="/static/home/js/all.js"></script>
	<script type="text/javascript" src="/static/home/js/pages/register.js"></script>
</head>

<body>
	<div class="register py-container ">
		<!--head-->
		<div class="logoArea">
			<a href="" class="logo1"></a>
		</div>
		<!--register-->
		<div class="registerArea">
			<h3>注册新用户<span class="go">我有账号,去<a href="login.html" target="_blank">登陆</a></span></h3>
			<div class="info">
				<form action="{:url('phone')}" method="post" id="reg_form" class="sui-form form-horizontal">
					<div class="control-group">
						<label class="control-label">手机号:</label>
						<div class="controls">
							<input type="text" id="phone" name="phone" placeholder="请输入你的手机号" class="input-xfat input-xlarge">
							<span class="error"></span>
						</div>
					</div>
					<div class="control-group">
						<label for="code" class="control-label">验证码:</label>
						<div class="controls">
							<input type="text" id="code" name="code" placeholder="验证码" class="input-xfat input-xlarge" style="width:120px">
							<button type="button" class="btn-xlarge" id="dyMobileButton">发送验证码</button>
							<span class="error"></span>
						</div>
					</div>
					<div class="control-group">
						<label for="password" class="control-label">登录密码:</label>
						<div class="controls">
							<input type="password" id="password" name="password" placeholder="设置登录密码" class="input-xfat input-xlarge">
							<span class="error"></span>
						</div>
					</div>
					<div class="control-group">
						<label for="repassword" class="control-label">确认密码:</label>
						<div class="controls">
							<input type="password" id="repassword" name="repassword" placeholder="再次确认密码" class="input-xfat input-xlarge">
							<span class="error"></span>
						</div>
					</div>
					<div class="control-group">
						<label class="control-label"></label>
						<div class="controls btn-reg">
							<a id="reg_btn" class="sui-btn btn-block btn-xlarge btn-danger reg-btn" href="javascript:;">完成注册</a>
						</div>
					</div>
				</form>
				<div class="clearfix"></div>
			</div>
		</div>
	</div>
<script>
	$(function(){
		//点击 注册  提交表单
		$('#reg_btn').click(function(){
			//提交表单
			$('form').submit();
		});

		//发送验证码
		$('#dyMobileButton').click(function(){
			//获取手机号
			var phone = $('#phone').val();
			if(phone == ''){
				//手机号不能为空
				$('#phone').next().html('手机号不能为空');
				return;
			}else if(!/^1[3-9]\d{9}$/.test(phone)){
				//手机号格式不正确
				$('#phone').next().html('手机号格式不正确');
				return;
			}else{
				$('#phone').next().html('');
			}
			var time = 60;
			//设置定时器  倒计时效果 ,发送短信接口调用时间前台限制
			var timer = setInterval(function(){
				time--;
				if(time > 0){
					//正在倒计时
					$('#dyMobileButton').html('重新发送:' + time + '秒');
					$('#dyMobileButton').prop('disabled', true);
				}else{
					//停止倒计时
					$('#dyMobileButton').html('发送验证码');
					$('#dyMobileButton').prop('disabled', false);
					clearInterval(timer);
				}
			}, 1000);
			//发送ajax请求,来进行调用接口实现验证码的发送
			$.ajax({
				"url":"{:url('home/login/sendcode')}",
				"type":"post",
				"data":"phone=" + phone,
				"dataType":"json",
				"success":function(res){
					//提示
				// 	alert(res.msg);return;
				}
			});

		});
	});
</script>
</body>

</html>

效果展示:

在这里插入图片描述

当点击发送验证码时会请求login控制器的sendcode方法来进行验证码的发送

2、sendcode发送验证码控制器方法
 //发送验证码
    public function sendcode(){
        //接收参数
        $params = input();
        //参数检测
        $validate = $this->validate($params,[
            'phone|手机号' => 'require|regex:1[3-9]\d{9}'
        ]);
        if ($validate !== true){
            $res= [
              'code' =>  440,
              'msg' => '参数错误!'
            ];
            echo json_encode($res);die;
        }
        //从cache中获取当前手机号码的发送验证码时间,这个时间是在调用发送短信接口成功时记录的。
        $time = cache('register_time_'.$params['phone']);
        //当间隔时间小于60秒时,不允许再次调用发送短信请求,这里是对发送短信时间做后台限制。
        if (time()-$time < 60){
            $res =[
                'code'=>'403',
                'msg'=>'发送验证码太频繁!'
            ];
            echo json_encode($res);die;
        }
        //发送信息内容
        $code = mt_rand(1000,9999);
        //生成随机4位数作为验证码
        $content = "【凯信通】您的验证码是:{$code}";
        //调用公共方法send_msg实现短信的发送
         $suc = send_msg($params['phone'],$content);
        //返回数据
        if ($suc){
            //存验证码
            cache('register_code_'.$params['phone'] ,$code,180);
            //存储时间
            cache('register_time_'.$params['phone'],time(),180);
            $res = [
                'code'=>200,
                'msg'=>'短信发送成功',
                'data'=>$content
            ];
            echo json_encode($res);die;
        }else{
            $res= [
                'code' =>  404,
                'msg' => '发送信息失败!'
            ];
            echo json_encode($res);die;
        }
    }

3、sendmsg公共函数,调用发送短信接口

我将appkey和请求地址url存储在config.php文件中如下

//短信验证配置
'msg' =>[
    'url' => 'https://way.jd.com/kaixintong/kaixintong',
    'appkey' => 'fd6ff7c134f41a4xxxxxxxxxxxxxxxxxxxxx'
],
if (!function_exists('send_msg')){
    function send_msg($mobile,$content){
        //获取config中的地址和appkey
        $appkey = config('msg.appkey');
        $url = config('msg.url');
        //https://way.jd.com/chuangxin/dxjk?mobile=13568813957&content=【创信】你的验证码是:5873,3分钟内有效!&appkey=您申请的APPKEY 点此获取APPKEY
        //拼接请求地址:get请求
        $url .= '?mobile='.$mobile.'&content='.$content.'&appkey='.$appkey;  
        //使用curl发送请求,调用发送短信接口
        $res = curl_request($url,false,[],true);
        if(!$res){
            return false;
        }
        //将返回的json字符串转化为数组
        $arr = json_decode($res,true);
        //从接口文档中可以看出,只有code为10000时才发送成功,返回成功
        if (isset($arr['code']) && $arr['code'] == 10000){
            return true;
        }else{
            return false;
        }
    }
}
3、curl_request发送请求函数,这是之前封装的curl发送请求方法
if (!function_exists('curl_request')){
    function curl_request($url,$post=true,$params=[],$https=true){
        //初始化请求会话
        $ch = curl_init($url);
        if ($post){
            //设置请求方式为post
            curl_setopt($ch,CURLOPT_POST,true);
            //设置请求参数
            curl_setopt($ch,CURLOPT_POSTFIELDS,$params);
        }
        if ($https){
            //如果是https协议,禁止服务器验证本地证书
            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        }
        //发送请求,获取返回参数
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        $res = curl_exec($ch);
        //关闭请求
        curl_close($ch);
        return $res;
    }
}
4、注册时login控制器phone方法
//手机验证码注册账号
public function phone(){
    //接受参数
    $params = input();
    //参数检测
    $validate = $this->validate($params,[
        'phone|手机号' => 'require|regex:1[3-9]\d{9}|unique:user,phone',
        'code|验证码' => 'require|length:4',
        'password|密码' => 'require|length:6,20|confirm:repassword'
    ]);
    //参数验证
    if ($validate !== true){
        $this->error($validate);
    }
    //验证码检验
    //从cache中获取该号码存储的验证码
    $code = cache('register_code_'.$params['phone']);
	//验证码进行验证输入的验证码是否为短信发送的验证码
    if ($code != $params['code']){
        $this->error('验证码错误');
    }
    //校验完成验证码失效
    cache('register_code_'.$params['phone'],null);
    //数据处理密码加密:此处encrypt1是自己封装的密码加密函数。
    $params['password'] = encrypt1($params['password']);
    //默认用户名为注册电话号码
    $params['username'] = $params['phone'];
    //调用模型方法存入数据库,即可完成注册操作。
    User::create($params,true);
    //跳转页面
    $this->redirect('home/login/login');
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值