WechatCaptcha.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace addons\wechat\model;
  3. use fast\Random;
  4. use think\Model;
  5. class WechatCaptcha extends Model
  6. {
  7. // 表名
  8. protected $name = 'wechat_captcha';
  9. // 自动写入时间戳字段
  10. protected $autoWriteTimestamp = 'int';
  11. // 定义时间戳字段名
  12. protected $createTime = 'createtime';
  13. protected $updateTime = '';
  14. // 追加属性
  15. protected $append = [
  16. ];
  17. /**
  18. * 发送验证码
  19. * @param $openid string 用户OpenID
  20. * @param $event string 事件
  21. * @param $ip string IP地址
  22. * @return string
  23. */
  24. public static function send($openid, $event, $ip)
  25. {
  26. $captcha = self::where(['openid' => $openid, 'event' => $event])->whereTime('createtime', '-2 minutes')->find();
  27. if ($captcha) {
  28. return "验证码发送速度过快,请稍后重试";
  29. }
  30. $code = Random::alnum(4);
  31. $data = [
  32. 'event' => $event,
  33. 'openid' => $openid,
  34. 'code' => $code,
  35. 'ip' => $ip,
  36. ];
  37. self::create($data);
  38. return "你的验证码是:{$code},2分钟内输入有效";
  39. }
  40. /**
  41. * 检测验证码
  42. * @param $code string 验证码
  43. * @param $event string 事件
  44. * @param $ip string IP
  45. * @return bool
  46. */
  47. public static function check($code, $event, $ip = null)
  48. {
  49. $ip = is_null($ip) ? request()->ip() : $ip;
  50. $captcha = self::where(['ip' => $ip, 'event' => $event])->whereTime('createtime', '-2 minutes')->find();
  51. if ($captcha && $captcha->code == $code && $captcha->times < 10) {
  52. $captcha->setInc("times");
  53. return true;
  54. }
  55. //验证大于10次或超时
  56. if ($captcha && ($captcha->times >= 10 || time() - $captcha->createtime > 120)) {
  57. $captcha->delete();
  58. }
  59. return false;
  60. }
  61. }