Ems.php 3.1 KB

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