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

laravel--对接腾讯云短信接口

程序员文章站 2022-05-25 09:09:25
...

学习总结

1.需要在腾讯云上购买并开通短信服务

2.需要下载证书到php的安装路径,证书文件cacert.pem,更改php.ini的配置文件curl.cainfo =C:\phpstudy_pro\Extensions\php\php7.3.4nts\cacert.pem更改为证书的绝对路径

3.通过composer下载腾讯云短信包到laravel项目中composer require tencentcloud/tencentcloud-sdk-php

4.生成的验证码信息保存在Redis中

1.腾讯云平台短信服务中申请签名和短信模板

laravel--对接腾讯云短信接口

laravel--对接腾讯云短信接口

1.1发送短信需要的参数保存位置

laravel--对接腾讯云短信接口

laravel--对接腾讯云短信接口

2.前台登录控制器Account.php

  1. <?php
  2. namespace App\Http\Controllers\homes;
  3. use App\Http\Controllers\Controller;
  4. use Illuminate\Http\Request;
  5. //引入数据库查询构造器,链式调用
  6. use Illuminate\Support\Facades\DB;
  7. //手动验证用户名和密码
  8. use Illuminate\Support\Facades\Auth;
  9. //哈希密码加密
  10. use Illuminate\Support\Facades\Hash;
  11. //引入redis
  12. use Illuminate\Support\Facades\Redis;
  13. use Symfony\Component\VarDumper\VarDumper;
  14. use TencentCloud\Common\Credential;
  15. use TencentCloud\Common\Profile\ClientProfile;
  16. use TencentCloud\Common\Profile\HttpProfile;
  17. use TencentCloud\Common\Exception\TencentCloudSDKException;
  18. use TencentCloud\Sms\V20190711\SmsClient;
  19. use TencentCloud\Sms\V20190711\Models\SendSmsRequest;
  20. //前台用户账号管理
  21. class Account extends Controller
  22. {
  23. //前台用户登录界面
  24. public function login()
  25. {
  26. return view('\homes\account\login');
  27. }
  28. //发送验证码短信
  29. public function sendMessage(Request $req)
  30. {
  31. try {
  32. //接收手机号码
  33. $phone ='+86'.(string) $req->phone;
  34. $redisCaptcha = Redis::get('login'.$phone);
  35. //判断是否发送短信验证码
  36. if(isset($redisCaptcha))
  37. {
  38. return json_encode(['code'=>0,'msg'=>'短信验证码已发送']);
  39. }
  40. //生成一个4位随机的验证码
  41. $captcha =(string)rand(1000,9999);
  42. //redis中短信验证码的存在时间
  43. $existTime = '10';
  44. $sec = (int)$existTime*60;
  45. $cred = new Credential("SecretId", "SecretKey");
  46. //存储在腾讯云->访问管理->访问密钥->API密钥管理中
  47. $httpProfile = new HttpProfile();
  48. $httpProfile->setEndpoint("sms.ap-beijing.tencentcloudapi.com");
  49. $clientProfile = new ClientProfile();
  50. $clientProfile->setHttpProfile($httpProfile);
  51. $client = new SmsClient($cred, "ap-beijing", $clientProfile);
  52. $reqSms = new SendSmsRequest();
  53. $params = array(
  54. "PhoneNumberSet" => array(
  55. //要发送的手机号码
  56. $phone
  57. ),
  58. "TemplateID" => '模板ID',
  59. //存储在腾讯云短信--国内短信--模板ID
  60. "Sign" => '瑄然软件',
  61. "TemplateParamSet" => array(
  62. //要发送的验证码
  63. $captcha,
  64. //验证码几分钟内有效
  65. $existTime,
  66. ),
  67. "SessionContext" => 'angle',
  68. "SmsSdkAppid" => 'SDKAppID'
  69. //存储在腾讯云--短信--应用管理--应用列表中
  70. );
  71. $reqSms->fromJsonString(json_encode($params));
  72. $resp = $client->SendSms($reqSms);
  73. $resp = $resp->toJsonString();//回调信息是一个对象转换为json字符串
  74. $resp = json_decode($resp,true);//json字符串转换为数组
  75. $resp = $resp['SendStatusSet'][0];//获取状态信息
  76. //var_dump($resp);
  77. if(($resp['Code']=="Ok") && ($resp['Message']=="send success"))
  78. {
  79. //把手机号码和验证码存入redis服务器,存放时间为
  80. Redis::setex('login'.$phone,$sec,$captcha);
  81. return json_encode(['code'=>1,'msg'=>'发送成功']);
  82. }
  83. else
  84. {
  85. return json_encode(['code'=>0,'msg'=>$resp['Message']]);
  86. }
  87. //var_dump($resp);
  88. //print_r($resp->toJsonString());
  89. }
  90. catch(TencentCloudSDKException $e) {
  91. echo $e;
  92. }
  93. }
  94. public function dologin(Request $req)
  95. {
  96. $phone ='+86'.$req->phone;
  97. $captcha = $req->captcha;
  98. $redisdata = Redis::get('login'.$phone);
  99. $pwd = '123456';//初始化密码为123456
  100. $secPwd =Hash::make($pwd);
  101. if(isset($redisdata))
  102. {
  103. if($redisdata==$captcha)
  104. {
  105. $res = DB::table('member')->select('id')->where('phone',$phone)->item();
  106. if($res)
  107. {
  108. DB::table('member')->where('id',$res['id'])->update(['lastlogin'=>time()]);
  109. }
  110. else
  111. {
  112. DB::table('member')->insert(['phone'=>$phone,'password'=>$secPwd,'reg_time'=>time()]);
  113. }
  114. //attempt方法使用比较密码时,密码不需要做哈希运算
  115. $isLogin = Auth::guard('member')->attempt(['phone'=>$phone,'password'=>$pwd]);
  116. if($isLogin)
  117. {
  118. return (json_encode(['code'=>1,'msg'=>'登录成功']));
  119. }
  120. else
  121. {
  122. exit(json_encode(['code'=>0,'msg'=>'登录失败']));
  123. }
  124. }
  125. else
  126. {
  127. exit (json_encode(['code'=>0,'msg'=>'验证码错误']));
  128. }
  129. }
  130. else
  131. {
  132. exit (json_encode(['code'=>0,'msg'=>'短信验证码过期,请重新发送验证码']));
  133. }
  134. }
  135. }

3.前台登录页面 index.blade.php

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  7. <link rel="stylesheet" href="/static/plugins/layui/css/layui.css">
  8. <script src="/static/plugins/layui/layui.js"></script>
  9. <title>前台登录界面</title>
  10. <style>
  11. .layui-form{
  12. padding: 15px;
  13. margin-top: 30vh;
  14. }
  15. .get-captcha{
  16. display: flex;
  17. flex-flow: row nowrap;
  18. }
  19. /* 登录按钮 */
  20. .login-btn{
  21. /* border: 1px solid #000; */
  22. width: 93vw;
  23. text-align: center;
  24. }
  25. .login-btn>button{
  26. width: 40vw;
  27. }
  28. </style>
  29. </head>
  30. <body>
  31. <div class="main">
  32. <div class="layui-form">
  33. @csrf
  34. {{-- 输入手机号码 --}}
  35. <div class="layui-form-item">
  36. <div class="layui-block">
  37. <input class="layui-input" required lay-verify="required" type="text" name="phone" placeholder="请输入手机号码">
  38. </div>
  39. </div>
  40. {{-- 获取短信验证码 --}}
  41. <div class="layui-form-item get-captcha">
  42. <div class="layui-inline">
  43. <input type="text" class="layui-input" required lay-verify="required" name="captcha" style="width:35vw;" placeholder="请输入验证码">
  44. </div>
  45. <div class="layui-inline">
  46. <button type="button" class="layui-btn layui-btn-primary" style="margin-left: 15px;" name="captchaBtn" onclick="getCaptcha()">获取验证码</button>
  47. </div>
  48. </div>
  49. {{-- 登录 --}}
  50. <div class="login-btn">
  51. <button type="button" class="layui-btn layui-btn-warm layui-btn-radius" name="loginBtn" onclick="dologin()">登录</button>
  52. </div>
  53. </div>
  54. </div>
  55. </body>
  56. <script>
  57. layui.use(['layer'],function(){
  58. $ = layui.jquery;
  59. layer = layui.layer;
  60. });
  61. //发送短信验证码
  62. function getCaptcha()
  63. {
  64. var phone = $('input[name="phone"]').val().trim();
  65. if(checkPhone(phone))
  66. {
  67. $.get('/homes/account/sendMessage',
  68. {
  69. phone:phone
  70. },
  71. function(res){
  72. res = JSON.parse(res);
  73. // console.log(res);
  74. if(res.code>0)
  75. {
  76. layer.msg('发送成功');
  77. setTimeout(() => {
  78. }, 1000);
  79. }
  80. else
  81. {
  82. layer.alert(res.msg,{icon:2});
  83. }
  84. });
  85. }
  86. }
  87. //检测是否是有效的电话号码
  88. function checkPhone(phone)
  89. {
  90. if(phone=="")
  91. {
  92. layer.alert("手机号码不能为空",{icon:2});
  93. return false;
  94. }
  95. if(!(phone.match(/^1[34578]\d{9}$/)))
  96. {
  97. layer.alert("手机号码格式不正确",{icon:2});
  98. return false;
  99. }
  100. return true;
  101. }
  102. //登录操作
  103. function dologin()
  104. {
  105. var phone = $('input[name="phone"]').val().trim();
  106. var captcha = $('input[name="captcha"]').val().trim();
  107. var _token = $('input[name="_token"]').val();
  108. $.post('/homes/account/dologin',
  109. {
  110. phone:phone,
  111. captcha:captcha,
  112. _token:_token,
  113. },
  114. function(res){
  115. if(res.code>0)
  116. {
  117. layer.msg(res.msg);
  118. setTimeout(() => {
  119. window.location.href='/'
  120. }, 1000);
  121. }
  122. else
  123. {
  124. layer.alert(res.msg,{icon:2});
  125. }
  126. }
  127. ,'json');
  128. // console.log(phone,' ',captcha);
  129. }
  130. </script>
  131. </html>

4.路由文件 web.php

  1. <?php
  2. use Illuminate\Support\Facades\Route;
  3. /*
  4. |--------------------------------------------------------------------------
  5. | Web Routes
  6. |--------------------------------------------------------------------------
  7. |
  8. | Here is where you can register web routes for your application. These
  9. | routes are loaded by the RouteServiceProvider within a group which
  10. | contains the "web" middleware group. Now create something great!
  11. |
  12. */
  13. Route::get('/', function(){
  14. return view('welcome');
  15. });
  16. //登录页面
  17. Route::get('/admins/account/login','admins\Account@login')->name('login');//使用name()方法对路由进行命名
  18. //验证码图片
  19. Route::get('/admins/account/captcha','admins\Account@captcha');
  20. //登录操作
  21. Route::post('/admins/account/dologin','admins\Account@dologin');
  22. //后台首页
  23. //调用框架自带的auth中间件判断是否登录,namespace()方法指定控制器的命令空间,group()方法中是一个回调函数,把一组路由写在这个回调函数中
  24. Route::namespace('admins')->middleware(['auth','rights'])->group(function(){
  25. Route::get('/admins/home/index','Home@index');
  26. Route::get('/admins/home/welcome','Home@welcome');
  27. Route::get('/admins/home/logout','Home@logout');
  28. //账号管理
  29. Route::get('/admins/admin/index','Admin@index');
  30. //添加账号
  31. Route::get('/admins/admin/add','Admin@add');
  32. //修改账号
  33. Route::get('/admins/admin/edit','Admin@edit');
  34. //保存账号
  35. Route::post('/admins/admin/save','Admin@save');
  36. //删除账号
  37. Route::get('/admins/admin/del','Admin@del');
  38. //菜单管理
  39. Route::get('/admins/menus/index','Menus@index');
  40. //添加菜单
  41. Route::get('/admins/menus/add','Menus@add');
  42. //修改菜单
  43. Route::get('/admins/menus/edit','Menus@edit');
  44. //保存菜单
  45. Route::post('/admins/menus/save','Menus@save');
  46. //删除菜单
  47. Route::get('/admins/menus/del','Menus@del');
  48. //角色管理
  49. Route::get('/admins/groups/index','Groups@index');
  50. //添加角色
  51. Route::get('/admins/groups/add','Groups@add');
  52. //修改角色
  53. Route::get('/admins/groups/edit','Groups@edit');
  54. //保存角色
  55. Route::post('/admins/groups/save','Groups@save');
  56. //删除角色
  57. Route::get('/admins/groups/del','Groups@del');
  58. //菜品管理
  59. Route::get('/admins/dish/index','Dish@index');
  60. Route::get('/admins/dish/add','Dish@add');
  61. Route::post('/admins/dish/save','Dish@save');
  62. Route::post('/admins/dish/del','Dish@del');
  63. //菜品分类管理
  64. Route::get('/admins/dish/cate','Dish@cate');
  65. Route::get('/admins/dish/cate_add','Dish@cate_add');
  66. Route::post('/admins/dish/cate_save','Dish@cate_save');
  67. Route::post('/admins/dish/cate_del','Dish@cate_del');
  68. //菜品制作方法
  69. Route::get('/admins/dish/taste','Dish@taste');
  70. Route::get('/admins/dish/taste_add','Dish@taste_add');
  71. Route::post('/admins/dish/taste_save','Dish@taste_save');
  72. Route::post('/admins/dish/taste_del','Dish@taste_del');
  73. //菜品套餐管理
  74. Route::get('/admins/dish/taocan','Dish@taocan');
  75. Route::get('/admins/dish/taocan_add','Dish@taocan_add');
  76. Route::get('/admins/dish/get_dish','Dish@get_dish');//动态取得某个菜类的数据,实现菜品选择框二级联动
  77. Route::post('/admins/dish/taocan_save','Dish@taocan_save');
  78. Route::post('/admins/dish/taocan_del','Dish@taocan_del');
  79. //菜品套餐分组管理
  80. Route::get('/admins/dish/group','Dish@group');
  81. Route::get('/admins/dish/group_add','Dish@group_add');
  82. Route::post('/admins/dish/group_save','Dish@group_save');
  83. Route::post('/admins/dish/group_del','Dish@group_del');
  84. //客服管理
  85. //客服和客户聊天窗口
  86. Route::get('/admins/servicer/index','Servicer@index');
  87. //聊天消息保存
  88. Route::get('/admins/servicer/save','Servicer@save');
  89. //文件图片上传管理
  90. //图片上传
  91. Route::post('/admins/files/upload_img','Files@upload_img');
  92. });
  93. //前台登录
  94. //向登录用户发送4位短信验证码
  95. Route::get('/homes/account/sendMessage','homes\Account@sendMessage');
  96. //前台用户登录界面
  97. Route::get('/homes/account/login','homes\Account@login');
  98. //前台用户登录操作
  99. Route::post('/homes/account/dologin','homes\Account@dologin');
  100. //前台
  101. //调用框架自带的auth中间件判断是否登录,namespace()方法指定控制器的命令空间,group()方法中是一个回调函数,把一组路由写在这个回调函数中
  102. Route::namespace('homes')->middleware('member')->group(function(){
  103. //前台首页,点菜界面
  104. Route::get('/','Home@index' );
  105. //普通菜品的制作方法选择页面
  106. Route::get('/dish_taste','Home@dish_taste');
  107. //套餐菜品明细的选择
  108. Route::get('/dish_taocan','Home@dish_taocan');
  109. //第二份半价选择页面
  110. Route::get('/dish_halfPrice','Home@dish_halfPrice');
  111. //购物车
  112. //购物车列表
  113. Route::get('/homes/cart/index','Cart@index');
  114. //获取购物车中的数据
  115. Route::get('/homes/cart/backRedData','Cart@backRedData');
  116. //购物车添加菜品
  117. Route::post('/homes/cart/addDish','Cart@addDish');
  118. //用户支付
  119. Route::get('/homes/pay/wxPay','Pay@wxPay');
  120. //微信支付回调
  121. Route::get('/homes/pay/wxPayCallBack','Pay@wxPayCallBack');
  122. });