Captcha.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace addons\wechat\controller;
  3. use addons\wechat\library\Wechat;
  4. use addons\wechat\model\WechatCaptcha;
  5. use fast\Http;
  6. /**
  7. * 微信验证码验证接口
  8. */
  9. class Captcha extends \think\addons\Controller
  10. {
  11. /**
  12. * 验证码检测接口
  13. */
  14. public function check()
  15. {
  16. $captcha = $this->request->post("captcha");
  17. $event = $this->request->post("event");
  18. $result = WechatCaptcha::check($captcha, $event);
  19. if ($result) {
  20. $this->success("验证码正确");
  21. } else {
  22. $this->error("验证码错误");
  23. }
  24. }
  25. /**
  26. * 验证码发送接口
  27. */
  28. public function send()
  29. {
  30. $ip = $this->request->ip();
  31. $event = $this->request->post("event");
  32. if (!$event) {
  33. $this->error("参数错误");
  34. }
  35. $captch = WechatCaptcha::where('ip', $ip)
  36. ->where('event', $event)
  37. ->whereTime('createtime', '-2 minutes')
  38. ->find();
  39. if ($captch) {
  40. $this->error("获取频繁,请稍后重试");
  41. }
  42. $token = Wechat::getAccessToken();
  43. if (!$token) {
  44. $this->error("发送失败,请稍后重试");
  45. }
  46. $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={$token}";
  47. $params = [
  48. 'expire_seconds' => 120,
  49. 'action_name' => 'QR_STR_SCENE',
  50. 'action_info' => [
  51. 'scene' => [
  52. 'scene_str' => "captcha_" . $event . "_" . $ip,
  53. ]
  54. ],
  55. ];
  56. //获取验证码
  57. $result = Http::sendRequest($url, json_encode($params));
  58. if ($result['ret']) {
  59. $msg = (array)json_decode($result['msg'], true);
  60. if (isset($msg['ticket']) && isset($msg['url'])) {
  61. $this->success("", null, ['image' => "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" . urlencode($msg['ticket']), 'url' => $msg['url']]);
  62. }
  63. }
  64. $this->error("获取失败!请稍后重试");
  65. }
  66. }