checkOrderAndReport.js 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import { compile, uncompile, unixTimestamp } from "../utils/helper";
  2. import httpClient from "../utils/httpClient";
  3. import DnSdk from "./DnSdk";
  4. class checkOrderAndReport {
  5. static instance = null;
  6. static timer = null;
  7. static reportDelayMap = [
  8. //index是report次数 值是delayTime(秒)
  9. 20, // 立即
  10. 60, // 1分钟
  11. 120, // 2分钟
  12. 180, // 3分钟
  13. 300, // 5分钟
  14. 600, // 10分钟
  15. 1200, // 20分钟
  16. 1800, // 30分钟
  17. 3600, // 1小时
  18. 7200, // 2小时
  19. ];
  20. constructor() { }
  21. async checkOrder() {
  22. const res = wx.getStorageInfoSync();
  23. for (let storageKey of res.keys) {
  24. if (storageKey.indexOf("_dnsdkOrderAndReport_") > -1) {
  25. const order = uncompile(wx.getStorageSync(storageKey));
  26. console.log("order", order);
  27. const delayTimeMap = checkOrderAndReport.reportDelayMap;
  28. const delayTime = delayTimeMap[order.reportCount];
  29. const timeDiff = unixTimestamp() - order.timestamp;
  30. let currentMapIndex = -1;
  31. for (let i = delayTimeMap.length - 1; i >= 0; i--) {
  32. if (timeDiff >= delayTimeMap[i]) {
  33. currentMapIndex = i;
  34. break;
  35. }
  36. }
  37. if (delayTime == undefined) {
  38. // 删除超过重试次数的订单
  39. wx.removeStorageSync(storageKey);
  40. console.log(storageKey + " removed!");
  41. continue;
  42. }
  43. if (timeDiff >= delayTime) {
  44. let sync_status = 0;
  45. // 请求判断是否支付成功
  46. const res = await httpClient.post("/payment/order/query", {
  47. order_id: order.order_id ?? null,
  48. ext: order.ext,
  49. });
  50. // 是否支付成功
  51. sync_status = res.sync_status ?? 0;
  52. if (sync_status) {
  53. DnSdk.getInstance().onPurchase(order.money * 100); // 腾讯广告小游戏SDK上报
  54. wx.removeStorageSync(storageKey);
  55. console.log(storageKey + " report success and removed!");
  56. } else {
  57. if (currentMapIndex == delayTimeMap.length - 1) {
  58. // 删除超过最长重试延时的订单
  59. wx.removeStorageSync(storageKey);
  60. console.log(storageKey + " removed!");
  61. continue;
  62. }
  63. if (currentMapIndex > order.reportCount) {
  64. order.reportCount = currentMapIndex;
  65. }
  66. order.reportCount += 1;
  67. wx.setStorageSync(storageKey, compile(order));
  68. }
  69. }
  70. }
  71. }
  72. checkOrderAndReport.getInstance().timer = setTimeout(
  73. checkOrderAndReport.getInstance().checkOrder,
  74. 60000
  75. );
  76. }
  77. run() {
  78. if (!checkOrderAndReport.getInstance().timer) {
  79. checkOrderAndReport.getInstance().checkOrder();
  80. }
  81. }
  82. static getInstance() {
  83. if (!this.instance) {
  84. this.instance = new checkOrderAndReport();
  85. }
  86. return this.instance;
  87. }
  88. }
  89. export default checkOrderAndReport;