Sms.php 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use app\common\library\Sms as Smslib;
  5. use app\common\model\User;
  6. /**
  7. * 手机短信接口
  8. */
  9. class Sms extends Api
  10. {
  11. protected $noNeedLogin = '*';
  12. protected $noNeedRight = '*';
  13. public function _initialize()
  14. {
  15. parent::_initialize();
  16. }
  17. /**
  18. * 发送验证码
  19. *
  20. * @param string $mobile 手机号
  21. * @param string $event 事件名称
  22. */
  23. public function send()
  24. {
  25. $mobile = $this->request->request("mobile");
  26. $event = $this->request->request("event");
  27. $event = $event ? $event : 'register';
  28. if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
  29. $this->error(__('手机号不正确'));
  30. }
  31. $last = Smslib::get($mobile, $event);
  32. if ($last && time() - $last['createtime'] < 60) {
  33. $this->error(__('发送频繁'));
  34. }
  35. $ipSendTotal = \app\common\model\Sms::where(['ip' => $this->request->ip()])->whereTime('createtime', '-1 hours')->count();
  36. if ($ipSendTotal >= 5) {
  37. $this->error(__('发送频繁'));
  38. }
  39. if ($event) {
  40. $userinfo = User::getByMobile($mobile);
  41. if ($event == 'register' && $userinfo) {
  42. //已被注册
  43. $this->error(__('已被注册'));
  44. } else if (in_array($event, ['changemobile']) && $userinfo) {
  45. //被占用
  46. $this->error(__('已被占用'));
  47. } else if (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
  48. //未注册
  49. $this->error(__('未注册'));
  50. }
  51. }
  52. $ret = Smslib::send($mobile, NULL, $event);
  53. if ($ret) {
  54. $this->success(__('发送成功'));
  55. } else {
  56. $this->error(__('发送失败'));
  57. }
  58. }
  59. /**
  60. * 检测验证码
  61. *
  62. * @param string $mobile 手机号
  63. * @param string $event 事件名称
  64. * @param string $captcha 验证码
  65. */
  66. public function check()
  67. {
  68. $mobile = $this->request->request("mobile");
  69. $event = $this->request->request("event");
  70. $event = $event ? $event : 'register';
  71. $captcha = $this->request->request("captcha");
  72. if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
  73. $this->error(__('手机号不正确'));
  74. }
  75. if ($event) {
  76. $userinfo = User::getByMobile($mobile);
  77. if ($event == 'register' && $userinfo) {
  78. //已被注册
  79. $this->error(__('已被注册'));
  80. } else if (in_array($event, ['changemobile']) && $userinfo) {
  81. //被占用
  82. $this->error(__('已被占用'));
  83. } else if (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
  84. //未注册
  85. $this->error(__('未注册'));
  86. }
  87. }
  88. $ret = Smslib::check($mobile, $captcha, $event);
  89. if ($ret) {
  90. $this->success(__('成功'));
  91. } else {
  92. $this->error(__('验证码不正确'));
  93. }
  94. }
  95. }