Index.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. <?php
  2. namespace app\controller;
  3. use Fastknife\Exception\ParamException;
  4. use Fastknife\Service\ClickWordCaptchaService;
  5. use Fastknife\Service\BlockPuzzleCaptchaService;
  6. use Fastknife\Service\Service;
  7. use think\exception\HttpResponseException;
  8. use think\facade\Validate;
  9. use think\Response;
  10. /**
  11. * 该文件位于controller目录下
  12. * Class Index
  13. * @package app\controller
  14. */
  15. class Index
  16. {
  17. public function index()
  18. {
  19. try {
  20. $service = $this->getCaptchaService();
  21. $data = $service->get();
  22. } catch (\Exception $e) {
  23. $this->error($e->getMessage());
  24. }
  25. $this->success($data);
  26. }
  27. /**
  28. * 一次验证
  29. */
  30. public function check()
  31. {
  32. $data = request()->post();
  33. try {
  34. $this->validate($data);
  35. $service = $this->getCaptchaService();
  36. $service->check($data['token'], $data['pointJson']);
  37. } catch (\Exception $e) {
  38. $this->error($e->getMessage());
  39. }
  40. $this->success([]);
  41. }
  42. /**
  43. * 二次验证
  44. */
  45. public function verification()
  46. {
  47. $data = request()->post();
  48. try {
  49. $this->validate($data);
  50. $service = $this->getCaptchaService();
  51. $service->verification($data['token'], $data['pointJson']);
  52. } catch (\Exception $e) {
  53. $this->error($e->getMessage());
  54. }
  55. $this->success([]);
  56. }
  57. protected function getCaptchaService()
  58. {
  59. $captchaType = request()->post('captchaType', null);
  60. $config = config('captcha');
  61. switch ($captchaType) {
  62. case "clickWord":
  63. $service = new ClickWordCaptchaService($config);
  64. break;
  65. case "blockPuzzle":
  66. $service = new BlockPuzzleCaptchaService($config);
  67. break;
  68. default:
  69. throw new ParamException('captchaType参数不正确!');
  70. }
  71. return $service;
  72. }
  73. protected function validate($data)
  74. {
  75. $rules = [
  76. 'token' => ['require'],
  77. 'pointJson' => ['require']
  78. ];
  79. $validate = Validate::rule($rules)->failException(true);
  80. $validate->check($data);
  81. }
  82. protected function success($data)
  83. {
  84. $response = [
  85. 'error' => false,
  86. 'repCode' => '0000',
  87. 'repData' => $data,
  88. 'repMsg' => null,
  89. 'success' => true,
  90. ];
  91. throw new HttpResponseException(Response::create($response, 'json'));
  92. }
  93. protected function error($msg)
  94. {
  95. $response = [
  96. 'error' => true,
  97. 'repCode' => '6111',
  98. 'repData' => null,
  99. 'repMsg' => $msg,
  100. 'success' => false,
  101. ];
  102. throw new HttpResponseException(Response::create($response, 'json'));
  103. }
  104. }