WechatMiniExpressSendSyncService.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. foreach ($deliveryLists as $delivery) {
  87. //商品信息
  88. $goodsNames = implode(" ", array_column($delivery['order_goods_info'], 'goods_name'));
  89. $itemDesc = mb_strlen($goodsNames) > 128 ? (mb_substr($goodsNames, 0, 124, 'UTF-8') . '...') : $goodsNames;
  90. $expressCode = Express::where('id', $delivery['express_id'] ?? 0)->value('code');
  91. if (! empty($delivery['invoice_no']) && ! empty($delivery['mobile']) && ! empty($expressCode)) {
  92. $data['shipping_list'][] = [
  93. 'tracking_no' => $delivery['invoice_no'],
  94. 'express_company' => $expressCode,
  95. 'contact' => [
  96. 'receiver_contact' => substr_replace($delivery['mobile'], '****', 3, 4)
  97. ],
  98. 'item_desc' => $itemDesc,
  99. ];
  100. } else {
  101. if ($data['delivery_mode'] == 1) {
  102. // 统一发货 无需物流,改为虚拟发货
  103. $data['logistics_type'] = 3;
  104. }
  105. }
  106. }
  107. switch ($order['delivery_type']) {
  108. // 快递发货
  109. case DeliveryEnum::EXPRESS_DELIVERY:
  110. $data['logistics_type'] = $data['logistics_type'] ?? 1;
  111. break;
  112. // 门店自提
  113. case DeliveryEnum::SELF_DELIVERY:
  114. $data['logistics_type'] = 4;
  115. break;
  116. // 虚拟发货
  117. case DeliveryEnum::DELIVERY_VIRTUAL:
  118. $data['logistics_type'] = 3;
  119. break;
  120. default:
  121. break;
  122. }
  123. // dump($data);
  124. $token = static::getToken($app);
  125. $result_content = $app->http_client->post("/wxa/sec/order/upload_shipping_info?access_token={$token}", [
  126. 'body' => json_encode($data, JSON_UNESCAPED_UNICODE),
  127. ])->getBody()->getContents();
  128. $result = json_decode($result_content, true);
  129. // dump($result);
  130. if (! isset($result['errcode']) || $result['errcode'] != 0) {
  131. // token失效 不标记失败 等下次执行
  132. if (isset($result['errcode']) && $result['errcode'] == 40001) {
  133. Log::write("等待下次执行" . ($result_content ? : "发货录入发生错误"), $log);
  134. return false;
  135. }
  136. Log::write($result_content ? : "发货录入发生错误", $log);
  137. Order::update([ 'wechat_mini_express_sync' => 2, 'wechat_mini_express_sync_time' => $time ], [
  138. [ 'id', '=', $order['id'] ],
  139. ]);
  140. return false;
  141. }
  142. Order::update([ 'wechat_mini_express_sync' => 1, 'wechat_mini_express_sync_time' => $time ], [
  143. [ 'id', '=', $order['id'] ],
  144. ]);
  145. return true;
  146. } catch(\Throwable $e) {
  147. Log::write($e->__toString(), $log);
  148. return false;
  149. }
  150. }
  151. /**
  152. * @notes 积分订单录入
  153. * @param array $order
  154. * @return bool
  155. * @author lbzy
  156. * @datetime 2023-09-18 15:40:39
  157. */
  158. static function _sync_integral_order(array $order) : bool
  159. {
  160. try {
  161. $time = time();
  162. $log = 'wechat_mini_express_sync_integral_order';
  163. $app = static::getMiniApp();
  164. $user = UserAuth::where('user_id', $order['user_id'])->where('terminal', UserTerminalEnum::WECHAT_MMP)->findOrEmpty();
  165. if (empty($user->openid)) {
  166. Log::write("用户:{$order['user_id']} openid不存在,订单ID:{$order['id']}", $log);
  167. Order::update([ 'wechat_mini_express_sync' => 2, 'wechat_mini_express_sync_time' => time() ], [
  168. [ 'id', '=', $order['id'] ],
  169. ]);
  170. return false;
  171. }
  172. $goods_names = $order['goods_snap']['name'] ?? '商品';
  173. $shipping_item = [
  174. 'item_desc' => mb_strlen($goods_names) > 128 ? (mb_substr($goods_names, 0, 124, 'UTF-8') . '...') : $goods_names,
  175. ];
  176. $data = [
  177. 'order_key' => [
  178. 'order_number_type' => 2,
  179. 'transaction_id' => $order['transaction_id'],
  180. ],
  181. 'delivery_mode' => 1,
  182. 'upload_time' => date(DATE_RFC3339, $time),
  183. 'payer' => [
  184. 'openid' => $user->openid,
  185. ],
  186. ];
  187. $delivery = IntegralDelivery::where('order_id', $order['id'])->findOrEmpty();
  188. $express = Express::where('id', $delivery['express_id'] ?? 0)->findOrEmpty();
  189. if (! empty($delivery->invoice_no) && ! empty($delivery->mobile) && ! empty($express->code)) {
  190. $shipping_item['tracking_no'] = $delivery->invoice_no;
  191. // 微信小程序 物流公司delivery_id
  192. $shipping_item['express_company'] = $express->code;
  193. $shipping_item['contact']['receiver_contact'] = substr_replace($delivery->mobile, '****', 3, 4);
  194. } else {
  195. // 无需物流,改为虚拟发货
  196. $data['logistics_type'] = 3;
  197. }
  198. $data['shipping_list'][] = $shipping_item;
  199. $data['logistics_type'] = match ($order['delivery_way']) {
  200. IntegralGoodsEnum::DELIVERY_EXPRESS => $data['logistics_type'] ?? 1,
  201. default => 3,
  202. };
  203. // dump($data);
  204. $token = static::getToken($app);
  205. $result_content = $app->http_client->post("/wxa/sec/order/upload_shipping_info?access_token={$token}", [
  206. 'body' => json_encode($data, JSON_UNESCAPED_UNICODE),
  207. ])->getBody()->getContents();
  208. $result = json_decode($result_content, true);
  209. // dump($result);
  210. if (! isset($result['errcode']) || $result['errcode'] != 0) {
  211. // token失效 不标记失败 等下次执行
  212. if (isset($result['errcode']) && $result['errcode'] == 40001) {
  213. Log::write("等待下次执行" . ($result_content ? : "发货录入发生错误"), $log);
  214. return false;
  215. }
  216. Log::write($result_content ? : "发货录入发生错误", $log);
  217. IntegralOrder::update([ 'wechat_mini_express_sync' => 2, 'wechat_mini_express_sync_time' => $time ], [
  218. [ 'id', '=', $order['id'] ],
  219. ]);
  220. return false;
  221. }
  222. IntegralOrder::update([ 'wechat_mini_express_sync' => 1, 'wechat_mini_express_sync_time' => $time ], [
  223. [ 'id', '=', $order['id'] ],
  224. ]);
  225. return true;
  226. } catch(\Throwable $e) {
  227. Log::write($e->__toString(), $log);
  228. return false;
  229. }
  230. }
  231. /**
  232. * @notes 充值录入
  233. * @param array $recharge
  234. * @return bool
  235. * @throws InvalidArgumentException
  236. * @author lbzy
  237. * @datetime 2023-07-17 15:18:18
  238. */
  239. static function _sync_recharge(array $recharge) : bool
  240. {
  241. try {
  242. $time = time();
  243. $log = 'wechat_mini_express_sync_recharge';
  244. $app = static::getMiniApp();
  245. $user = UserAuth::where('user_id', $recharge['user_id'])->where('terminal', UserTerminalEnum::WECHAT_MMP)->findOrEmpty();
  246. if (empty($user->openid)) {
  247. Log::write("用户:{$recharge['user_id']} openid不存在,订单ID:{$recharge['id']}", $log);
  248. RechargeOrder::update([ 'wechat_mini_express_sync' => 2, 'wechat_mini_express_sync_time' => time() ], [
  249. [ 'id', '=', $recharge['id'] ],
  250. ]);
  251. return false;
  252. }
  253. $shipping_item = [
  254. 'item_desc' => '余额充值',
  255. ];
  256. $data = [
  257. 'order_key' => [
  258. 'order_number_type' => 2,
  259. 'transaction_id' => $recharge['transaction_id'],
  260. ],
  261. 'delivery_mode' => 1,
  262. 'upload_time' => date(DATE_RFC3339, $time),
  263. 'payer' => [
  264. 'openid' => $user->openid,
  265. ],
  266. 'logistics_type' => 3,
  267. ];
  268. $data['shipping_list'][] = $shipping_item;
  269. // dump($data);
  270. $token = static::getToken($app);
  271. $result_content = $app->http_client->post("/wxa/sec/order/upload_shipping_info?access_token={$token}", [
  272. 'body' => json_encode($data, JSON_UNESCAPED_UNICODE),
  273. ])->getBody()->getContents();
  274. $result = json_decode($result_content, true);
  275. // dump($result);
  276. if (! isset($result['errcode']) || $result['errcode'] != 0) {
  277. // token失效 不标记失败 等下次执行
  278. if (isset($result['errcode']) && $result['errcode'] == 40001) {
  279. Log::write("等待下次执行" . ($result_content ? : "发货录入发生错误"), $log);
  280. return false;
  281. }
  282. Log::write($result_content ? : "发货录入发生错误", $log);
  283. RechargeOrder::update([ 'wechat_mini_express_sync' => 2, 'wechat_mini_express_sync_time' => $time ], [
  284. [ 'id', '=', $recharge['id'] ],
  285. ]);
  286. return false;
  287. }
  288. RechargeOrder::update([ 'wechat_mini_express_sync' => 1, 'wechat_mini_express_sync_time' => $time ], [
  289. [ 'id', '=', $recharge['id'] ],
  290. ]);
  291. return true;
  292. } catch(\Throwable $e) {
  293. Log::write($e->__toString(), $log);
  294. return false;
  295. }
  296. }
  297. private static function getToken($app)
  298. {
  299. return $app->access_token->getToken()['access_token'];
  300. }
  301. static function wechatSyncCheck($order)
  302. {
  303. $app = static::getMiniApp();
  304. $data = [
  305. 'transaction_id' => $order['transaction_id'] ?? '',
  306. ];
  307. $token = static::getToken($app);
  308. $result_content = $app->http_client->post("/wxa/sec/order/get_order?access_token={$token}", [
  309. 'body' => json_encode($data, JSON_UNESCAPED_UNICODE),
  310. ])->getBody()->getContents();
  311. $result = json_decode($result_content, true);
  312. if (! isset($result['errcode']) || $result['errcode'] != 0) {
  313. // token失效 不标记失败 等下次执行
  314. if (isset($result['errcode']) && $result['errcode'] == 40001) {
  315. Log::write("等待下次执行" . ($result_content ? : "发货录入发生错误"), 'wechat_mini_express_sync_check');
  316. return false;
  317. }
  318. Log::write($result_content ? : "发货录入发生错误", 'wechat_mini_express_sync_check');
  319. return [];
  320. }
  321. return $result;
  322. }
  323. }