Paper.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  1. <?php
  2. namespace addons\exam\controller;
  3. use addons\exam\enum\CommonStatus;
  4. use addons\exam\enum\ExamMode;
  5. use addons\exam\library\ExamService;
  6. use addons\exam\model\PaperModel;
  7. use addons\exam\model\QuestionModel;
  8. use addons\exam\model\UserModel;
  9. use app\admin\model\exam\CateModel;
  10. use app\admin\model\exam\GradeModel;
  11. use think\Request;
  12. use think\Db;
  13. include_once EXTEND_PATH.'icbc/DefaultIcbcClient.php';
  14. /**
  15. * 试卷接口
  16. */
  17. class Paper extends Base
  18. {
  19. protected $noNeedLogin = ['index','lists','detail'];
  20. protected $noNeedRight = ['*'];
  21. protected $user;
  22. /**
  23. * 查询出分类下的试卷
  24. */
  25. public function index()
  26. {
  27. $cate_id = input('cate_id/d', '0');
  28. $sort = input('sort/s', '');
  29. $now = time();
  30. $query = PaperModel::with([
  31. 'cates' => function ($query) {
  32. $query->withField('id, name');
  33. }
  34. ])
  35. ->where('status', CommonStatus::NORMAL)
  36. ->where('is_only_room', 0)// 过滤仅考场使用的试卷
  37. ->whereRaw("((start_time = 0 and end_time = 0) or (start_time < {$now} and end_time > {$now}))");
  38. // 分类
  39. if ($cate_id) {
  40. $child_cate_ids = CateModel::getChildId($cate_id);
  41. array_push($child_cate_ids, $cate_id);
  42. $query->whereIn('cate_id', $child_cate_ids);
  43. }
  44. // 排序
  45. if ($sort && $sort != 'null') {
  46. $sort = explode('|', $sort);
  47. $field = $sort[0];
  48. $order_by = $sort[1];
  49. $field = in_array($field, ['join_count']) ? $field : 'join_count';
  50. $order_by = $order_by == 'desc' ? 'desc' : 'asc';
  51. $query->order("{$field} $order_by");
  52. }
  53. $list = $query->paginate();
  54. $this->success('', ['list' => $list]);
  55. }
  56. public function lists()
  57. {
  58. $list = Db::name('exam_paper')->field('id,image,title,updatetime')->where('status','normal')
  59. ->order('weigh desc, id desc')->autopage()->select();
  60. $list = list_domain_image($list,['image']);
  61. $this->success('', $list);
  62. }
  63. public function detail(){
  64. $id = input('id');
  65. $info = Db::name('exam_paper')->field('id,image,title,content,updatetime,quantity')->where('status','normal')
  66. ->find($id);
  67. $info = info_domain_image($info,['image']);
  68. $this->success('', $info);
  69. }
  70. /**
  71. * 试卷取题接口
  72. */
  73. public function getExamQuestion()
  74. {
  75. $paper_id = input('paper_id/d', 0);
  76. $room_id = input('room_id/d', 0);
  77. // 验证是否需要绑定手机号
  78. // UserModel::isMustBindMobile($this->auth->getUser());
  79. // 预创建考场考试记录
  80. // $room_grade_id = ExamService::preRoomGrade($room_id, $this->auth->id);
  81. // 获取试卷题目
  82. $question_data = ExamService::getExamQuestion($paper_id, $room_id);
  83. // $this->success('', array_merge($question_data, ['room_grade_id' => $room_grade_id]));
  84. $this->success('', $question_data);
  85. }
  86. //开始考试接口
  87. public function startpaper(){
  88. $paper_id = input('paper_id/d', 0);
  89. $user_id = $this->auth->id;
  90. //检查考试状态
  91. /*$check = Db::name('exam_grade')->where('user_id', $user_id)->where('status',1)->find();
  92. if($check){
  93. $this->success('您有其他考试正在进行中,即将继续考试',0);//直接给成功,数据返回0,前端跳转
  94. }*/
  95. //检查试卷
  96. $paper = PaperModel::get($paper_id);
  97. switch (true) {
  98. case !$paper:
  99. $this->error('科普答题信息不存在');
  100. case $paper->status != 'NORMAL':
  101. $this->error('科普答题信息不存在');
  102. case $paper->mode == 'RANDOM' && !$paper->configs:
  103. $this->error('科普答题信息未配置');
  104. }
  105. //时间限制
  106. /*if ($paper['start_time'] > 0 && $paper['start_time'] > time()) {
  107. $this->error('该试卷未开始,不能参与考试');
  108. }
  109. if ($paper['end_time'] > 0 && $paper['end_time'] < time()) {
  110. $this->error('该试卷已结束,不能参与考试');
  111. }*/
  112. //考试资格
  113. /*if(!in_array($user_id,explode(',',$paper['user_ids']))){
  114. $this->error('您不能参加该考试');
  115. }*/
  116. //次数限制
  117. if ($paper['limit_count'] > 0){
  118. $my_count = Db::name('exam_grade')->where('user_id', $user_id)->where('paper_id', $paper_id)->where('status',2)->count();
  119. if($my_count >= $paper['limit_count']) {
  120. $this->error('在该科普中您的答题次数已达上限');
  121. }
  122. }
  123. //记录为已开始,计划任务倒计时之后 自动结束
  124. $data = [
  125. 'cate_id' => $paper['cate_id'],
  126. 'user_id' => $this->auth->id,
  127. 'paper_id' => $paper_id,
  128. 'mode' => $paper['mode'],
  129. 'total_score' => $paper['total_score'],
  130. 'total_count' => $paper['quantity'],
  131. 'start_time' => time(),
  132. 'createtime' => time(),
  133. 'status' => 1,
  134. 'limit_time' => $paper['limit_time'], //限时N秒
  135. 'last_time' => $paper['limit_time'] > 0 ? (time() + $paper['limit_time']) : 0, //最后限制交卷时间,时间戳
  136. ];
  137. $grade_id = Db::name('exam_grade')->insertGetId($data);
  138. $this->success('',$grade_id);
  139. }
  140. //进行中考试
  141. public function half_examing(){
  142. $user_id = $this->auth->id;
  143. $check = Db::name('exam_grade')->where('user_id', $user_id)->where('status',1)->find();
  144. if(empty($check)){
  145. $this->error('您没有进行中的考试');
  146. }
  147. $paper_id = $check['paper_id'];
  148. // 获取试卷题目
  149. $question_data = ExamService::getExamQuestion($paper_id, 0);
  150. $question_data['paper']['limit_time'] = $check['last_time'] - time();//倒计时秒数
  151. $this->success('', $question_data);
  152. }
  153. /**
  154. * 交卷
  155. */
  156. public function submit()
  157. {
  158. $request = Request::instance();
  159. $user_id = $this->auth->id;
  160. $grade_id = $request->post('grade_id');
  161. $paper_id = $request->post('paper_id/d', 0);
  162. $questions = $request->post('questions/a', []);
  163. $start_time = $request->post('start_time/d', time());
  164. $room_id = 0;
  165. $room_grade_id = $request->post('room_grade_id/d', 0);
  166. if (!$user_id || !$paper_id || !$questions) {
  167. $this->error('提交数据有误');
  168. }
  169. $check = Db::name('exam_grade')->where('status',1)->where('id',$grade_id)->where('user_id',$user_id)->where('paper_id',$paper_id)->find();
  170. if(!$check){
  171. $this->error('交卷有误,或者您已交卷');
  172. }
  173. $start_time = $check['start_time'];
  174. // 考场考试
  175. if ($room_id) {
  176. if (!$room_grade_id) {
  177. $this->error('提交数据不合法');
  178. }
  179. // 考场考试
  180. $result = ExamService::roomExam($user_id, $room_id, $room_grade_id, $questions, $start_time, $paper, $room, $is_makeup, $room_grade_log);
  181. // 记录考场考试成绩
  182. $room_grade_log->allowField(true)->save(
  183. array_merge(
  184. $result,
  185. [
  186. // 'cate_id' => $paper['cate_id'],
  187. 'user_id' => $user_id,
  188. 'paper_id' => $paper_id,
  189. 'is_makeup' => $is_makeup,
  190. 'is_pre' => 0, // 提交成绩后不再为预创建标记
  191. ],
  192. [
  193. 'exam_mode' => ExamMode::ROOM,
  194. ]
  195. )
  196. );
  197. } else {
  198. $result = ExamService::paperExam($user_id, $paper_id, $questions, $start_time, $paper);
  199. // 记录考试成绩
  200. /*GradeModel::create(array_merge(
  201. $result,
  202. [
  203. 'cate_id' => $paper['cate_id'],
  204. 'user_id' => $user_id,
  205. 'paper_id' => $paper_id,
  206. ],
  207. [
  208. // 'exam_mode' => ExamMode::PAPER,
  209. 'date' => date('Y-m-d'),
  210. ]), true);*/
  211. $update = array_merge(
  212. $result,
  213. [
  214. 'updatetime' => time(),
  215. 'date' => date('Y-m-d'),
  216. 'status' => 2,
  217. 'finish_time' => time(),
  218. ]);
  219. unset($update['pass_score']);
  220. unset($update['start_time']);
  221. $rs = Db::name('exam_grade')->where('id',$grade_id)->update($update);
  222. if($rs === false){
  223. $this->error('交卷失败');
  224. }
  225. // 异步推送积分到工行(写入队列)
  226. $cephone = '15388010006';
  227. //$cephone = $this->auth->mobile;
  228. $this->addIcbcQueue($cephone, $result['score'], '10938', $this->auth->nickname);
  229. }
  230. $result['nickname'] = $this->auth->nickname;
  231. unset($result['question_ids']);
  232. unset($result['user_answers']);
  233. unset($result['configs']);
  234. $this->success('',$result);
  235. }
  236. /**
  237. * 积分维护接口 - 推送积分数据到工行
  238. * @param string $mobile_phone 用户手机号
  239. * @param int $integral_value 变动的积分值(整数)
  240. * @param string $integral_type 积分类型
  241. * @param array $remarks 备用字段数组(可选,最多7个)
  242. * @return array 返回接口响应结果
  243. */
  244. public function update_villager_integral($mobile_phone = '', $integral_value = 0, $integral_type = '', $remarks = [])
  245. {
  246. // PHP 8+ 兼容:确保参数不为null
  247. $mobile_phone = $mobile_phone ?? '';
  248. $integral_value = $integral_value ?? 0;
  249. $integral_type = $integral_type ?? '';
  250. $remarks = $remarks ?? [];
  251. // 如果没有传入手机号,尝试从登录用户获取
  252. if (empty($mobile_phone) && isset($this->auth->mobile)) {
  253. $mobile_phone = $this->auth->mobile;
  254. }
  255. // 生成16位唯一序列号(时间戳10位+随机数6位)
  256. $fSeqNo = time() . str_pad(mt_rand(0, 999999), 6, '0', STR_PAD_LEFT);
  257. // 构建业务参数
  258. $biz_content = [
  259. 'fSeqNo' => $fSeqNo,
  260. 'corpCode' => 'xingfulishequ',
  261. 'mobilePhone' => $mobile_phone,
  262. 'integralValue' => (string)$integral_value, // 确保是字符串类型
  263. 'integralType' => $integral_type,
  264. ];
  265. // 添加备用字段(如果有)
  266. for ($i = 1; $i <= 7; $i++) {
  267. if (isset($remarks[$i - 1]) && !empty($remarks[$i - 1])) {
  268. $biz_content['remark' . $i] = $remarks[$i - 1];
  269. }
  270. }
  271. // 工行RSA密钥(字符串格式)
  272. $public_key = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwFgHD4kzEVPdOj03ctKM7KV+16bWZ5BMNgvEeuEQwfQYkRVwI9HFOGkwNTMn5hiJXHnlXYCX+zp5r6R52MY0O7BsTCLT7aHaxsANsvI9ABGx3OaTVlPB59M6GPbJh0uXvio0m1r/lTW3Z60RU6Q3oid/rNhP3CiNgg0W6O3AGqwIDAQAB';
  273. $private_key = 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCR8/ZvKPAdZzsyvapySvztQm56s1N59ynKMOWpUbK4c5MNWMl+q3dvsp+UiSAx2TAeGkYfW3W6nO/3Y0hAZki99fmuzpPujEeHhs79HNwGZYQjN71Vck2JeflTq8jpL+9/up0Kz2nbwtZDMKTTEgbfNeO24gV1bmvD2kQ9j66RIyuXSDwQbVbQfl6LiqKoJm3rbtsbwX1Ytc0/Szslyor1VdPZWnHDMm3m78Hqu7X3vL6K7fAW/4FVbeKV7vWjvyiTQfETmuADqMdsqV5YeqUZWE/Dnzg+6JV/3L9nJ8f+/mPlh8k1h1oW035GrADKFKf1M2ujKKeHICnj7qKCdBeNAgMBAAECggEAHkh+U2YtHAy1Tbvox7ojbJ8iCTd4FJBiDV/D5zPaX0crtdM8S5oMOBLZ5ZnmIjGsODK/ZfY2ITg62huxfBs88J0+5zRZoV9d4BLqk74PMQyTNDN2h2omCGZUgzXbg/a8PMZdm0aZ8k0k4+AN8vWEk3+89c9Dzq/QkFyTWCqdz+Mp9NkcOjA255kj5/D1q9Zj0x9VcmKg3oTtrKL/dkspUxVaMKXcpo6J4AszC05tT3N0SNLhcq51I6B9QdbYsYCkP9whPNYIl/y4dN4QnNEivQzA5/ltr5DDQZc7Xke1+SpJN+ylBOBJ8yvNoDnuxx0xEWuNJ5bUzyri/DNjZRKNQQKBgQDKkxn5R4Q3rChI/KVIXHMecTs9fXN5pbnA8UKU6ZeTl+wHffxwRieHZJJp1nDcQ5i8YXCtqEJcJGFn3T0rEjVCJ/RVHclFO+TjYaK9HtyNJLPrvKmAzjCzV1yPfe4qmpgJddzZI7Vii2uFgklixvhkoY74hwSJtvLPTO0p0xrYdQKBgQC4cgfpCMLYlaHQGz+dAEf4IewQpwBGn7XShCpiXGFciGZZEIzvJMzXP7yo8pDMHQbB4kQsTRRG2fcdHGWI5VQGHPqG5O0tUueKGUlSg7j8Y/Pp8ZrBGSrlilAf17I/u9MC7Xe2ZRVGNgPDYAyjMEGmClI0n2+aN6b4CFVBjYmfuQKBgEKO9KDIE7QrF41rnW7aGWTuNVWty2wzvIWdf4/n9EqlRwLrLS9CjahZrhWiRLDKcPusVFZqi2s09OAoe/mT4PXcpNX2lHPwCvN+1/allje10HvrIBJXLP8v/BSVftR2uO+azzZ1GhrHzksulKgk0eZWguA7lI0fFEZycxYj65UlAoGAD9p1RZlkLfuGgf2llRgOF4zK3o+MHYXiuep0PioUkECFE4ixpGh0Vtf6nkbjHTgteYK6O1iQsppPfCgRrheQBkp9WhTZMfkbP6p2u+nof4ET2PrUQ16naj1eL655erLpKypADORZVMSVxDhAPdKLAfuHH1DI5ed8qXsF4PGKb7kCgYEAm/d+daT6YsbHDZlJ/J9Q8rRkKmiqj43NGQSHKg6Z6BEDibm8wRmj3Itu1N6XVChuaH+ekJzvUnZ/q1nyYzGvy6bOHYn3ziF9aH7wuhcRZ4qARmKDnzTBLg2QXBK1+400O3LJ+sAH/yuH/Y4hzRE6YMxBQpdYfnlJcIFVimAsT1w=';
  274. // 构建通用请求参数
  275. $data = [
  276. 'app_id' => '10000000000004096993',
  277. 'msg_id' => createUniqueNo('msg', time()),
  278. 'format' => 'json',
  279. 'charset' => 'UTF-8',
  280. 'encrypt_type' => 'AES',
  281. 'sign_type' => 'RSA2',
  282. ];
  283. // 记录请求日志(调试用)
  284. \think\Log::record('积分维护接口请求参数: ' . json_encode([
  285. 'app_id' => $data['app_id'],
  286. 'msg_id' => $data['msg_id'],
  287. 'biz_content' => $biz_content
  288. ], JSON_UNESCAPED_UNICODE), 'info');
  289. try {
  290. // 检查必要的类和函数
  291. if (!class_exists('\DefaultIcbcClient')) {
  292. \think\Log::record('DefaultIcbcClient 类不存在', 'error');
  293. return [
  294. 'return_code' => '-98',
  295. 'return_msg' => 'DefaultIcbcClient 类不存在',
  296. 'raw_response' => ''
  297. ];
  298. }
  299. if (!function_exists('createUniqueNo')) {
  300. \think\Log::record('createUniqueNo 函数不存在', 'error');
  301. return [
  302. 'return_code' => '-97',
  303. 'return_msg' => 'createUniqueNo 函数不存在',
  304. 'raw_response' => ''
  305. ];
  306. }
  307. // 创建工行客户端
  308. \think\Log::record('准备创建 DefaultIcbcClient...', 'info');
  309. $client = new \DefaultIcbcClient(
  310. $data['app_id'],
  311. $private_key,
  312. $data['sign_type'],
  313. $data['charset'],
  314. $data['format'],
  315. $public_key,
  316. '', '', '', ''
  317. );
  318. \think\Log::record('DefaultIcbcClient 创建成功', 'info');
  319. // 构建请求参数
  320. $request = [
  321. 'serviceUrl' => 'https://gw.dccnet.com.cn:8084/api/mybank/farm/farmplatf/updateVillagerIntegral/V1',
  322. 'method' => 'POST',
  323. 'isNeedEncrypt' => false,
  324. 'extraParams' => null,
  325. 'biz_content' => $biz_content,
  326. ];
  327. // 发送请求
  328. $response = $client->execute($request, $data['msg_id'], '');
  329. // 记录原始响应(调试用)
  330. \think\Log::record('积分维护接口原始响应长度: ' . strlen($response), 'info');
  331. // 检查响应是否为空
  332. if (empty($response)) {
  333. $resultData = [
  334. 'return_code' => '-1',
  335. 'return_msg' => '接口无响应',
  336. 'raw_response' => $response
  337. ];
  338. $this->writeIcbcLog(false, $resultData, $biz_content);
  339. return $resultData;
  340. }
  341. // 清理响应内容:提取 JSON 部分
  342. // 工行接口可能返回调试信息,需要清理
  343. $clean_response = $this->cleanResponse($response);
  344. // 如果清理后的响应与原始不同,记录
  345. if ($clean_response !== $response) {
  346. \think\Log::record('积分维护接口响应包含非JSON内容,已清理', 'info');
  347. }
  348. // 解析响应
  349. $result = json_decode($clean_response, true);
  350. // 检查JSON解析是否成功
  351. if (json_last_error() !== JSON_ERROR_NONE) {
  352. \think\Log::record('积分维护接口JSON解析失败: ' . json_last_error_msg(), 'error');
  353. $resultData = [
  354. 'return_code' => '-2',
  355. 'return_msg' => 'JSON解析失败: ' . json_last_error_msg(),
  356. 'raw_response' => $response,
  357. 'clean_response' => $clean_response
  358. ];
  359. $this->writeIcbcLog(false, $resultData, $biz_content);
  360. return $resultData;
  361. }
  362. // 检查是否有response_biz_content(按API文档,响应数据在这个字段里)
  363. if (isset($result['response_biz_content'])) {
  364. $biz_result = json_decode($result['response_biz_content'], true);
  365. if ($biz_result) {
  366. // 合并业务响应和原始响应
  367. $resultData = array_merge($biz_result, ['raw_response' => $response]);
  368. $this->writeIcbcLog($resultData['return_code'] == 0, $resultData, $biz_content);
  369. return $resultData;
  370. }
  371. }
  372. // 如果直接有return_code,直接返回
  373. if (isset($result['return_code'])) {
  374. $this->writeIcbcLog($result['return_code'] == 0, $result, $biz_content);
  375. return $result;
  376. }
  377. // 返回完整结果
  378. $resultData = $result ? $result : [
  379. 'return_code' => '-3',
  380. 'return_msg' => '未知响应格式',
  381. 'raw_response' => $response
  382. ];
  383. $this->writeIcbcLog(false, $resultData, $biz_content);
  384. return $resultData;
  385. } catch (\Exception $e) {
  386. // 捕获异常
  387. \think\Log::record('积分维护接口异常: ' . $e->getMessage(), 'error');
  388. $resultData = [
  389. 'return_code' => '-99',
  390. 'return_msg' => '接口调用异常: ' . $e->getMessage(),
  391. 'raw_response' => ''
  392. ];
  393. $this->writeIcbcLog(false, $resultData, $biz_content);
  394. return $resultData;
  395. }
  396. }
  397. /**
  398. * 添加工行积分任务到队列
  399. * @param string $mobile_phone 手机号
  400. * @param int $integral_value 积分值
  401. * @param string $integral_type 积分类型
  402. * @param string $nickname 用户昵称
  403. */
  404. private function addIcbcQueue($mobile_phone, $integral_value, $integral_type, $nickname)
  405. {
  406. try {
  407. // PHP 8+ 兼容:确保所有值都不为null
  408. $data = [
  409. 'mobile_phone' => $mobile_phone ?? '',
  410. 'integral_value' => $integral_value ?? 0,
  411. 'integral_type' => $integral_type ?? '',
  412. 'nickname' => $nickname ?? '',
  413. 'status' => 0, // 0-待处理, 1-处理中, 2-成功, 3-失败
  414. 'retry_count' => 0,
  415. 'createtime' => time(),
  416. 'updatetime' => time(),
  417. ];
  418. Db::name('icbc_queue')->insert($data);
  419. // 不立即处理,完全由定时任务处理
  420. // 这样可以避免 fastcgi_finish_request() 影响正常响应
  421. } catch (\Exception $e) {
  422. // 队列写入失败,记录日志但不影响主流程
  423. \think\Log::record('工行队列写入失败: ' . $e->getMessage(), 'error');
  424. }
  425. }
  426. /**
  427. * 异步处理工行队列(不阻塞当前请求)
  428. */
  429. private function processIcbcQueueAsync()
  430. {
  431. // 使用fastcgi_finish_request()立即返回响应给用户
  432. if (function_exists('fastcgi_finish_request')) {
  433. fastcgi_finish_request();
  434. }
  435. // 后台处理队列
  436. $this->processIcbcQueue();
  437. }
  438. /**
  439. * 处理工行队列任务
  440. */
  441. public function processIcbcQueue()
  442. {
  443. // 获取待处理的任务(限制每次处理10条)
  444. $tasks = Db::name('icbc_queue')
  445. ->where('status', 0)
  446. ->where('retry_count', '<', 3) // 最多重试3次
  447. ->limit(10)
  448. ->select();
  449. foreach ($tasks as $task) {
  450. try {
  451. // 更新状态为处理中
  452. Db::name('icbc_queue')->where('id', $task['id'])->update([
  453. 'status' => 1,
  454. 'updatetime' => time()
  455. ]);
  456. // 调用工行接口
  457. $result = $this->update_villager_integral(
  458. $task['mobile_phone'],
  459. $task['integral_value'],
  460. $task['integral_type'],
  461. [$task['nickname']]
  462. );
  463. // 先检查返回值是否为数组
  464. if (!is_array($result)) {
  465. \think\Log::record('工行接口返回值异常[ID:'.$task['id'].']: ' . var_export($result, true), 'error');
  466. // 返回值异常,标记为失败
  467. $retry_count = $task['retry_count'] + 1;
  468. $status = $retry_count >= 3 ? 3 : 0;
  469. Db::name('icbc_queue')->where('id', $task['id'])->update([
  470. 'status' => $status,
  471. 'retry_count' => $retry_count,
  472. 'result' => json_encode(['error' => '返回值不是数组', 'raw' => var_export($result, true)], JSON_UNESCAPED_UNICODE),
  473. 'error_msg' => '接口返回值格式错误',
  474. 'updatetime' => time()
  475. ]);
  476. continue;
  477. }
  478. // 根据结果更新状态
  479. if (isset($result['return_code']) && $result['return_code'] == 0) {
  480. // 成功
  481. Db::name('icbc_queue')->where('id', $task['id'])->update([
  482. 'status' => 2,
  483. 'result' => json_encode($result, JSON_UNESCAPED_UNICODE),
  484. 'updatetime' => time()
  485. ]);
  486. } else {
  487. // 失败,增加重试次数
  488. $retry_count = $task['retry_count'] + 1;
  489. $status = $retry_count >= 3 ? 3 : 0; // 重试3次后标记为失败
  490. $error_msg = isset($result['return_msg']) ? $result['return_msg'] : '未知错误';
  491. Db::name('icbc_queue')->where('id', $task['id'])->update([
  492. 'status' => $status,
  493. 'retry_count' => $retry_count,
  494. 'result' => json_encode($result, JSON_UNESCAPED_UNICODE),
  495. 'error_msg' => $error_msg,
  496. 'updatetime' => time()
  497. ]);
  498. }
  499. } catch (\Exception $e) {
  500. // 异常处理
  501. Db::name('icbc_queue')->where('id', $task['id'])->update([
  502. 'status' => 0,
  503. 'retry_count' => $task['retry_count'] + 1,
  504. 'error_msg' => $e->getMessage(),
  505. 'updatetime' => time()
  506. ]);
  507. \think\Log::record('工行队列处理异常[ID:'.$task['id'].']: ' . $e->getMessage(), 'error');
  508. }
  509. }
  510. }
  511. /**
  512. * 写入工行接口日志
  513. * @param bool $is_success 是否成功
  514. * @param array $result 返回结果
  515. * @param array $request_data 请求数据
  516. */
  517. private function writeIcbcLog($is_success, $result, $request_data)
  518. {
  519. // 确定日志文件路径
  520. $log_dir = RUNTIME_PATH . 'icbc_log/';
  521. if (!is_dir($log_dir)) {
  522. mkdir($log_dir, 0755, true);
  523. }
  524. $filename = $is_success ? 'suc.txt' : 'failicbc.txt';
  525. $filepath = $log_dir . $filename;
  526. // 构建日志内容
  527. $log_content = [
  528. '时间' => date('Y-m-d H:i:s'),
  529. '请求数据' => $request_data,
  530. '返回数据' => $result,
  531. '原始响应' => isset($result['raw_response']) ? $result['raw_response'] : '',
  532. '分隔线' => str_repeat('-', 80)
  533. ];
  534. $log_text = "\n" . json_encode($log_content, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . "\n";
  535. // 追加写入文件
  536. file_put_contents($filepath, $log_text, FILE_APPEND);
  537. }
  538. /**
  539. * 清理响应内容,提取纯JSON
  540. * @param string $response 原始响应
  541. * @return string 清理后的JSON字符串
  542. */
  543. private function cleanResponse($response)
  544. {
  545. // 1. 去除首尾空白
  546. $response = trim($response);
  547. // 2. 查找第一个 { 或 [(JSON开始)
  548. $json_start = -1;
  549. $first_brace = strpos($response, '{');
  550. $first_bracket = strpos($response, '[');
  551. if ($first_brace !== false && $first_bracket !== false) {
  552. $json_start = min($first_brace, $first_bracket);
  553. } elseif ($first_brace !== false) {
  554. $json_start = $first_brace;
  555. } elseif ($first_bracket !== false) {
  556. $json_start = $first_bracket;
  557. }
  558. // 3. 查找最后一个 } 或 ](JSON结束)
  559. $json_end = -1;
  560. $last_brace = strrpos($response, '}');
  561. $last_bracket = strrpos($response, ']');
  562. if ($last_brace !== false && $last_bracket !== false) {
  563. $json_end = max($last_brace, $last_bracket);
  564. } elseif ($last_brace !== false) {
  565. $json_end = $last_brace;
  566. } elseif ($last_bracket !== false) {
  567. $json_end = $last_bracket;
  568. }
  569. // 4. 提取JSON部分
  570. if ($json_start !== -1 && $json_end !== -1 && $json_end > $json_start) {
  571. return substr($response, $json_start, $json_end - $json_start + 1);
  572. }
  573. // 5. 如果没找到JSON结构,返回原始内容
  574. return $response;
  575. }
  576. /*
  577. * 查看错题
  578. * Robin
  579. * @param $ids
  580. * */
  581. public function error_ids($ids)
  582. {
  583. $questions = QuestionModel::whereIn('id', ($ids))->select();
  584. $this->success('', $questions);
  585. }
  586. }