Ems.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use app\common\library\Ems as Emslib;
  5. use app\common\model\User;
  6. /**
  7. * 邮箱验证码接口
  8. */
  9. class Ems extends Api
  10. {
  11. protected $noNeedLogin = '*';
  12. protected $noNeedRight = '*';
  13. public function _initialize()
  14. {
  15. parent::_initialize();
  16. \think\Hook::add('ems_send', function ($params) {
  17. $obj = \app\common\library\Email::instance();
  18. $result = $obj
  19. ->to($params->email)
  20. ->subject('验证码')
  21. ->message("你的验证码是:" . $params->code)
  22. ->send();
  23. return $result;
  24. });
  25. }
  26. /**
  27. * 发送验证码
  28. *
  29. * @param string $email 邮箱
  30. * @param string $event 事件名称
  31. */
  32. public function send()
  33. {
  34. $email = $this->request->request("email");
  35. $event = $this->request->request("event");
  36. $event = $event ? $event : 'register';
  37. $last = Emslib::get($email, $event);
  38. if ($last && time() - $last['createtime'] < 60) {
  39. $this->error(__('发送频繁'));
  40. }
  41. if ($event) {
  42. $userinfo = User::getByEmail($email);
  43. if ($event == 'register' && $userinfo) {
  44. //已被注册
  45. $this->error(__('已被注册'));
  46. } elseif (in_array($event, ['changeemail']) && $userinfo) {
  47. //被占用
  48. $this->error(__('已被占用'));
  49. } elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
  50. //未注册
  51. $this->error(__('未注册'));
  52. }
  53. }
  54. $ret = Emslib::send($email, null, $event);
  55. if ($ret) {
  56. $this->success(__('发送成功'));
  57. } else {
  58. $this->error(__('发送失败'));
  59. }
  60. }
  61. /**
  62. * 检测验证码
  63. *
  64. * @param string $email 邮箱
  65. * @param string $event 事件名称
  66. * @param string $captcha 验证码
  67. */
  68. public function check()
  69. {
  70. $email = $this->request->request("email");
  71. $event = $this->request->request("event");
  72. $event = $event ? $event : 'register';
  73. $captcha = $this->request->request("captcha");
  74. if ($event) {
  75. $userinfo = User::getByEmail($email);
  76. if ($event == 'register' && $userinfo) {
  77. //已被注册
  78. $this->error(__('已被注册'));
  79. } elseif (in_array($event, ['changeemail']) && $userinfo) {
  80. //被占用
  81. $this->error(__('已被占用'));
  82. } elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
  83. //未注册
  84. $this->error(__('未注册'));
  85. }
  86. }
  87. $ret = Emslib::check($email, $captcha, $event);
  88. if ($ret) {
  89. $this->success(__('成功'));
  90. } else {
  91. $this->error(__('验证码不正确'));
  92. }
  93. }
  94. }