VerificationCodeServer.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace app\admin\server\sms;
  3. use app\admin\model\SmsRecord;
  4. use support\Redis;
  5. class VerificationCodeServer
  6. {
  7. /**
  8. * Notes:获取验证码
  9. * @param $mobile
  10. * @param $user_id
  11. * User: yym
  12. * Date: 2022/9/18
  13. * @return bool
  14. * @throws \Exception
  15. */
  16. public static function getCode($mobile, $user_id)
  17. {
  18. SmsRecord::affairBegin();
  19. try {
  20. $action = 'get_code';//模板名称
  21. $template_id = config('plugin.hzdad.wbsms.app.aliyun.actions')[$action]['template_id'] ?? '';
  22. $params = ['time'=>date("Y-m-d H:i:s",time()),'code' => randCode(6, true)];//参数
  23. $areacode = "86";//国际区号,腾讯云选传,其他不传
  24. $sms = new \Hzdad\Wbsms\Wbsms('aliyun');
  25. $insert_status = SmsRecord::InsertData($mobile, '会员获取无卡结算验证码' . $params['code'], $template_id, $user_id);
  26. if($insert_status)
  27. {
  28. $result = $sms->sendsms($action,$mobile,$params,$areacode);
  29. if ($result['code'] == 200) {
  30. Redis::setEx('get_code_' . $mobile, 300, $params['code']);
  31. SmsRecord::affairCommit();
  32. return true;
  33. } else {
  34. //SmsRecord::InsertData($mobile, $result['msg'], $template_id, $user_id);
  35. throw new \Exception($result['msg'], 500);
  36. }
  37. }
  38. throw new \Exception('发送失败', 500);
  39. }catch (\Exception $exception){
  40. SmsRecord::affairRollback();//数据库回滚
  41. throw new \Exception($exception->getMessage(), 500);
  42. }
  43. }
  44. /**
  45. * Notes:验证码校验
  46. * @param int $mobile
  47. * @param int $code
  48. * @return bool
  49. * @throws \Exception
  50. * User: yym
  51. * Date: 2022/7/25
  52. */
  53. public static function checkCode(int $mobile, int $code)
  54. {
  55. if(!Redis::exists('get_code_' . $mobile))
  56. {
  57. throw new \Exception('验证码已过期,请重新获取');
  58. }
  59. if(Redis::get('get_code_' . $mobile) != $code)
  60. {
  61. throw new \Exception('验证码错误');
  62. }
  63. Redis::del('get_code_' . $mobile);
  64. return true;
  65. }
  66. }