WechatMiniExpressSendSyncService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. <?php
  2. namespace app\common\service;
  3. use app\common\enum\DeliveryEnum;
  4. use app\common\enum\IntegralGoodsEnum;
  5. use app\common\enum\UserTerminalEnum;
  6. use app\common\logic\BaseLogic;
  7. use app\common\model\Delivery;
  8. use app\common\model\Express;
  9. use app\common\model\IntegralDelivery;
  10. use app\common\model\IntegralGoods;
  11. use app\common\model\IntegralOrder;
  12. use app\common\model\Order;
  13. use app\common\model\OrderGoods;
  14. use app\common\model\RechargeOrder;
  15. use app\common\model\UserAuth;
  16. use EasyWeChat\Factory;
  17. use Psr\SimpleCache\InvalidArgumentException;
  18. use think\facade\Log;
  19. use think\helper\Str;
  20. /**
  21. * @notes 小程序 发货信息录入
  22. * @notes https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/business-capabilities/order-shipping/order-shipping.html
  23. * author lbzy
  24. * @datetime 2023-07-14 14:51:23
  25. * @class WechatMiniExpressSendSyncService
  26. * @package app\common\service
  27. */
  28. class WechatMiniExpressSendSyncService extends BaseLogic
  29. {
  30. static private $miniApp = null;
  31. private static function getMiniApp()
  32. {
  33. if (! static::$miniApp) {
  34. $config = WeChatConfigService::getMnpConfig();
  35. static::$miniApp = Factory::miniProgram($config);
  36. }
  37. return static::$miniApp;
  38. }
  39. /**
  40. * @notes 订单录入
  41. * @param array $order
  42. * @return bool
  43. * @author lbzy
  44. * @datetime 2023-07-14 14:34:05
  45. */
  46. static function _sync_order(array $order) : bool
  47. {
  48. try {
  49. $time = time();
  50. $log = 'wechat_mini_express_sync_order';
  51. $app = static::getMiniApp();
  52. $user = UserAuth::where('user_id', $order['user_id'])->where('terminal', UserTerminalEnum::WECHAT_MMP)->findOrEmpty();
  53. if (empty($user->openid)) {
  54. Log::write("用户:{$order['user_id']} openid不存在,订单ID:{$order['id']}", $log);
  55. Order::update([ 'wechat_mini_express_sync' => 2, 'wechat_mini_express_sync_time' => time() ], [
  56. [ 'id', '=', $order['id'] ],
  57. ]);
  58. return false;
  59. }
  60. // $order_goods = OrderGoods::where('order_id', $order['id'])->select()->toArray();
  61. // $goods_names = implode(" ", array_column($order_goods, 'goods_name'));
  62. //
  63. // $shipping_item = [
  64. // 'item_desc' => mb_strlen($goods_names) > 128 ? (mb_substr($goods_names, 0, 124, 'UTF-8') . '...') : $goods_names,
  65. // ];
  66. $data = [
  67. 'order_key' => [
  68. 'order_number_type' => 2,
  69. 'transaction_id' => $order['transaction_id'],
  70. ],
  71. 'delivery_mode' => 1,//统一发货
  72. 'upload_time' => date(DATE_RFC3339, $time),
  73. 'payer' => [
  74. 'openid' => $user->openid,
  75. ],
  76. ];
  77. // $delivery = Delivery::where('order_id', $order['id'])->findOrEmpty();
  78. // $express = Express::where('id', $delivery['express_id'] ?? 0)->findOrEmpty();
  79. $deliveryLists = Delivery::where('order_id', $order['id'])->select()->toArray();
  80. //分拆发货
  81. if (count($deliveryLists) > 1) {
  82. $data['delivery_mode'] = 2;
  83. $data['is_all_delivered'] = true;
  84. }
  85. $data['shipping_list'] = [];
  86. $noExpress = true;
  87. foreach ($deliveryLists as $delivery) {
  88. //商品信息
  89. $goodsNames = implode(" ", array_column($delivery['order_goods_info'], 'goods_name'));
  90. $itemDesc = mb_strlen($goodsNames) > 128 ? (mb_substr($goodsNames, 0, 124, 'UTF-8') . '...') : $goodsNames;
  91. //无需物流
  92. if ($delivery['send_type'] == DeliveryEnum::NO_EXPRESS) {
  93. $data['shipping_list'][] = [
  94. 'item_desc' => $itemDesc,
  95. ];
  96. continue;
  97. }
  98. $noExpress = false;
  99. $expressCode = Express::where('id', $delivery['express_id'] ?? 0)->value('code');
  100. if (! empty($delivery['invoice_no']) && ! empty($delivery['mobile']) && ! empty($expressCode)) {
  101. $data['shipping_list'][] = [
  102. 'tracking_no' => $delivery['invoice_no'],
  103. 'express_company' => $expressCode,
  104. 'contact' => [
  105. 'receiver_contact' => substr_replace($delivery['mobile'], '****', 3, 4)
  106. ],
  107. 'item_desc' => $itemDesc,
  108. ];
  109. } else {
  110. Log::write("发货信息不完整:请检查订单编号为{$delivery['sn']}的物流信息,请检查物流单号、手机号、物流公司代码是否填写完整", $log);
  111. return false;
  112. }
  113. }
  114. if ($noExpress) {
  115. // 统一发货 无需物流,改为虚拟发货
  116. $data['logistics_type'] = 3;
  117. }
  118. switch ($order['delivery_type']) {
  119. // 快递发货
  120. case DeliveryEnum::EXPRESS_DELIVERY:
  121. $data['logistics_type'] = $data['logistics_type'] ?? 1;
  122. break;
  123. // 门店自提
  124. case DeliveryEnum::SELF_DELIVERY:
  125. $data['logistics_type'] = 4;
  126. break;
  127. // 虚拟发货
  128. case DeliveryEnum::DELIVERY_VIRTUAL:
  129. $data['logistics_type'] = 3;
  130. break;
  131. default:
  132. break;
  133. }
  134. // dump($data);
  135. $token = static::getToken($app);
  136. $result_content = $app->http_client->post("/wxa/sec/order/upload_shipping_info?access_token={$token}", [
  137. 'body' => json_encode($data, JSON_UNESCAPED_UNICODE),
  138. ])->getBody()->getContents();
  139. $result = json_decode($result_content, true);
  140. // dump($result);
  141. if (! isset($result['errcode']) || $result['errcode'] != 0) {
  142. //支付单已完成发货 支付单已使用重新发货机会 标记成功
  143. if ($result['errcode'] == 10060002 || $result['errcode'] == 10060003) {
  144. Log::write("发货录入发生错误:订单编号为{$delivery['sn']},".$result['errmsg'] ?? '', $log);
  145. Order::update([ 'wechat_mini_express_sync' => 1, 'wechat_mini_express_sync_time' => $time ], [
  146. [ 'id', '=', $order['id'] ],
  147. ]);
  148. return true;
  149. }
  150. // token失效或者不在白名单 不标记失败 等下次执行
  151. if (isset($result['errcode']) && ($result['errcode'] == 40001 || $result['errcode'] == 61004)) {
  152. Log::write("等待下次执行" . ($result_content ? : "发货录入发生错误"), $log);
  153. return false;
  154. }
  155. Log::write($result_content ? : "发货录入发生错误", $log);
  156. Order::update([ 'wechat_mini_express_sync' => 2, 'wechat_mini_express_sync_time' => $time ], [
  157. [ 'id', '=', $order['id'] ],
  158. ]);
  159. return false;
  160. }
  161. Order::update([ 'wechat_mini_express_sync' => 1, 'wechat_mini_express_sync_time' => $time ], [
  162. [ 'id', '=', $order['id'] ],
  163. ]);
  164. return true;
  165. } catch(\Throwable $e) {
  166. Log::write($e->__toString(), $log);
  167. return false;
  168. }
  169. }
  170. /**
  171. * @notes 积分订单录入
  172. * @param array $order
  173. * @return bool
  174. * @author lbzy
  175. * @datetime 2023-09-18 15:40:39
  176. */
  177. static function _sync_integral_order(array $order) : bool
  178. {
  179. try {
  180. $time = time();
  181. $log = 'wechat_mini_express_sync_integral_order';
  182. $app = static::getMiniApp();
  183. $user = UserAuth::where('user_id', $order['user_id'])->where('terminal', UserTerminalEnum::WECHAT_MMP)->findOrEmpty();
  184. if (empty($user->openid)) {
  185. Log::write("用户:{$order['user_id']} openid不存在,订单ID:{$order['id']}", $log);
  186. Order::update([ 'wechat_mini_express_sync' => 2, 'wechat_mini_express_sync_time' => time() ], [
  187. [ 'id', '=', $order['id'] ],
  188. ]);
  189. return false;
  190. }
  191. $goods_names = $order['goods_snap']['name'] ?? '商品';
  192. $shipping_item = [
  193. 'item_desc' => mb_strlen($goods_names) > 128 ? (mb_substr($goods_names, 0, 124, 'UTF-8') . '...') : $goods_names,
  194. ];
  195. $data = [
  196. 'order_key' => [
  197. 'order_number_type' => 2,
  198. 'transaction_id' => $order['transaction_id'],
  199. ],
  200. 'delivery_mode' => 1,
  201. 'upload_time' => date(DATE_RFC3339, $time),
  202. 'payer' => [
  203. 'openid' => $user->openid,
  204. ],
  205. ];
  206. $delivery = IntegralDelivery::where('order_id', $order['id'])->findOrEmpty();
  207. $express = Express::where('id', $delivery['express_id'] ?? 0)->findOrEmpty();
  208. if (! empty($delivery->invoice_no) && ! empty($delivery->mobile) && ! empty($express->code)) {
  209. $shipping_item['tracking_no'] = $delivery->invoice_no;
  210. // 微信小程序 物流公司delivery_id
  211. $shipping_item['express_company'] = $express->code;
  212. $shipping_item['contact']['receiver_contact'] = substr_replace($delivery->mobile, '****', 3, 4);
  213. } else {
  214. // 无需物流,改为虚拟发货
  215. $data['logistics_type'] = 3;
  216. }
  217. $data['shipping_list'][] = $shipping_item;
  218. $data['logistics_type'] = match ($order['delivery_way']) {
  219. IntegralGoodsEnum::DELIVERY_EXPRESS => $data['logistics_type'] ?? 1,
  220. default => 3,
  221. };
  222. // dump($data);
  223. $token = static::getToken($app);
  224. $result_content = $app->http_client->post("/wxa/sec/order/upload_shipping_info?access_token={$token}", [
  225. 'body' => json_encode($data, JSON_UNESCAPED_UNICODE),
  226. ])->getBody()->getContents();
  227. $result = json_decode($result_content, true);
  228. // dump($result);
  229. if (! isset($result['errcode']) || $result['errcode'] != 0) {
  230. // token失效或者不在白名单 不标记失败 等下次执行
  231. if (isset($result['errcode']) && ($result['errcode'] == 40001 || $result['errcode'] == 61004)) {
  232. Log::write("等待下次执行" . ($result_content ? : "发货录入发生错误"), $log);
  233. return false;
  234. }
  235. Log::write($result_content ? : "发货录入发生错误", $log);
  236. IntegralOrder::update([ 'wechat_mini_express_sync' => 2, 'wechat_mini_express_sync_time' => $time ], [
  237. [ 'id', '=', $order['id'] ],
  238. ]);
  239. return false;
  240. }
  241. IntegralOrder::update([ 'wechat_mini_express_sync' => 1, 'wechat_mini_express_sync_time' => $time ], [
  242. [ 'id', '=', $order['id'] ],
  243. ]);
  244. return true;
  245. } catch(\Throwable $e) {
  246. Log::write($e->__toString(), $log);
  247. return false;
  248. }
  249. }
  250. /**
  251. * @notes 充值录入
  252. * @param array $recharge
  253. * @return bool
  254. * @throws InvalidArgumentException
  255. * @author lbzy
  256. * @datetime 2023-07-17 15:18:18
  257. */
  258. static function _sync_recharge(array $recharge) : bool
  259. {
  260. try {
  261. $time = time();
  262. $log = 'wechat_mini_express_sync_recharge';
  263. $app = static::getMiniApp();
  264. $user = UserAuth::where('user_id', $recharge['user_id'])->where('terminal', UserTerminalEnum::WECHAT_MMP)->findOrEmpty();
  265. if (empty($user->openid)) {
  266. Log::write("用户:{$recharge['user_id']} openid不存在,订单ID:{$recharge['id']}", $log);
  267. RechargeOrder::update([ 'wechat_mini_express_sync' => 2, 'wechat_mini_express_sync_time' => time() ], [
  268. [ 'id', '=', $recharge['id'] ],
  269. ]);
  270. return false;
  271. }
  272. $shipping_item = [
  273. 'item_desc' => '余额充值',
  274. ];
  275. $data = [
  276. 'order_key' => [
  277. 'order_number_type' => 2,
  278. 'transaction_id' => $recharge['transaction_id'],
  279. ],
  280. 'delivery_mode' => 1,
  281. 'upload_time' => date(DATE_RFC3339, $time),
  282. 'payer' => [
  283. 'openid' => $user->openid,
  284. ],
  285. 'logistics_type' => 3,
  286. ];
  287. $data['shipping_list'][] = $shipping_item;
  288. // dump($data);
  289. $token = static::getToken($app);
  290. $result_content = $app->http_client->post("/wxa/sec/order/upload_shipping_info?access_token={$token}", [
  291. 'body' => json_encode($data, JSON_UNESCAPED_UNICODE),
  292. ])->getBody()->getContents();
  293. $result = json_decode($result_content, true);
  294. // dump($result);
  295. if (! isset($result['errcode']) || $result['errcode'] != 0) {
  296. // token失效或者不在白名单 不标记失败 等下次执行
  297. if (isset($result['errcode']) && ($result['errcode'] == 40001 || $result['errcode'] == 61004)) {
  298. Log::write("等待下次执行" . ($result_content ? : "发货录入发生错误"), $log);
  299. return false;
  300. }
  301. Log::write($result_content ? : "发货录入发生错误", $log);
  302. RechargeOrder::update([ 'wechat_mini_express_sync' => 2, 'wechat_mini_express_sync_time' => $time ], [
  303. [ 'id', '=', $recharge['id'] ],
  304. ]);
  305. return false;
  306. }
  307. RechargeOrder::update([ 'wechat_mini_express_sync' => 1, 'wechat_mini_express_sync_time' => $time ], [
  308. [ 'id', '=', $recharge['id'] ],
  309. ]);
  310. return true;
  311. } catch(\Throwable $e) {
  312. Log::write($e->__toString(), $log);
  313. return false;
  314. }
  315. }
  316. private static function getToken($app)
  317. {
  318. return $app->access_token->getToken()['access_token'];
  319. }
  320. static function wechatSyncCheck($order)
  321. {
  322. $app = static::getMiniApp();
  323. $data = [
  324. 'transaction_id' => $order['transaction_id'] ?? '',
  325. ];
  326. $token = static::getToken($app);
  327. $result_content = $app->http_client->post("/wxa/sec/order/get_order?access_token={$token}", [
  328. 'body' => json_encode($data, JSON_UNESCAPED_UNICODE),
  329. ])->getBody()->getContents();
  330. $result = json_decode($result_content, true);
  331. if (! isset($result['errcode']) || $result['errcode'] != 0) {
  332. // token失效或者不在白名单 不标记失败 等下次执行
  333. if (isset($result['errcode']) && ($result['errcode'] == 40001 || $result['errcode'] == 61004)) {
  334. Log::write("等待下次执行" . ($result_content ? : "发货录入发生错误"), 'wechat_mini_express_sync_check');
  335. return false;
  336. }
  337. Log::write($result_content ? : "发货录入发生错误", 'wechat_mini_express_sync_check');
  338. return [];
  339. }
  340. return $result;
  341. }
  342. }