Sms.php 3.0 KB

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