Captcha.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <?php
  2. namespace app\api\controller;
  3. use think\captcha\facade\Captcha as ThinkCaptcha;
  4. use think\facade\Cache;
  5. class Captcha extends BaseApi
  6. {
  7. /**
  8. * 验证码
  9. */
  10. public function captcha()
  11. {
  12. if (isset($this->params['captcha_id']) && !empty($this->params['captcha_id'])) {
  13. Cache::delete($this->params['captcha_id']);
  14. }
  15. $captcha_data = ThinkCaptcha::create(null, true);
  16. $captcha_id = md5(uniqid(null, true));
  17. // 验证码10分钟有效
  18. Cache::set($captcha_id, $captcha_data['code'], 600);
  19. return $this->response($this->success([ 'id' => $captcha_id, 'img' => $captcha_data['img'] ]));
  20. }
  21. /**
  22. * 检测验证码
  23. * @param boolean $snapchat 阅后即焚
  24. */
  25. public function checkCaptcha($snapchat = true) : array
  26. {
  27. if (!isset($this->params['captcha_id']) || empty($this->params['captcha_id'])) {
  28. return $this->error('', 'REQUEST_CAPTCHA_ID');
  29. }
  30. if (!isset($this->params['captcha_code']) || empty($this->params['captcha_code'])) {
  31. return $this->error('', 'REQUEST_CAPTCHA_CODE');
  32. }
  33. if ($snapchat) $captcha_data = Cache::pull($this->params['captcha_id']);
  34. else $captcha_data = Cache::get($this->params['captcha_id']);
  35. if (empty($captcha_data)) return $this->error('', 'CAPTCHA_FAILURE');
  36. if ($this->params['captcha_code'] != $captcha_data) return $this->error('', 'CAPTCHA_ERROR');
  37. return $this->success();
  38. }
  39. }