You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

339 lines
13 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. <?php
  2. namespace App\JsonRpc;
  3. use App\Commons\Log;
  4. use App\Constants\v3\ErrorCode;
  5. use App\Constants\v3\LogLabel;
  6. use App\Constants\v3\OrderState;
  7. use App\Exception\ErrorCodeException;
  8. use App\Model\v3\Order;
  9. use App\Model\v3\OrderGoods;
  10. use App\Model\v3\OrderMain;
  11. use App\Service\v3\Interfaces\FinancialRecordServiceInterface;
  12. use App\Service\v3\Interfaces\OrderOnlineServiceInterface;
  13. use App\Service\v3\Interfaces\SeparateAccountsServiceInterface;
  14. use EasyWeChat\Factory;
  15. use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
  16. use Hyperf\DbConnection\Db;
  17. use Hyperf\Guzzle\CoroutineHandler;
  18. use Hyperf\RpcServer\Annotation\RpcService;
  19. use Hyperf\Di\Annotation\Inject;
  20. use App\JsonRpc\OrdersServiceInterface;
  21. /**
  22. * @RpcService(name="OrdersService", protocol="jsonrpc-http", server="jsonrpc-http", publishTo="")
  23. */
  24. class OrdersService implements OrdersServiceInterface
  25. {
  26. /**
  27. * @Inject
  28. * @var Log
  29. */
  30. protected $log;
  31. /**
  32. * @Inject
  33. * @var OrderOnlineServiceInterface
  34. */
  35. protected $orderOnlineService;
  36. /**
  37. * @Inject
  38. * @var SeparateAccountsServiceInterface
  39. */
  40. protected $separateAccountsService;
  41. /**
  42. * @Inject
  43. * @var FinancialRecordServiceInterface
  44. */
  45. protected $financialRecordService;
  46. /**
  47. * 订单完成
  48. * @param $global_order_id
  49. * @param $user_id
  50. * @return array
  51. */
  52. public function onlineComplete($global_order_id, $user_id)
  53. {
  54. Db::beginTransaction();
  55. try {
  56. $this->orderOnlineService->doComplete($global_order_id, $user_id);
  57. $this->separateAccountsService->orderOnlineCompleted($global_order_id, $user_id);
  58. Db::commit();
  59. return [
  60. "status" => 200,
  61. "code" => 0,
  62. "result" => [],
  63. "message" => '处理成功'
  64. ];
  65. } catch (\Exception $e) {
  66. Db::rollBack();
  67. $this->log->event(LogLabel::ORDER_COMPLETE_LOG, ['jsonrpc_order_service_exception_onlineComplete' => $e->getMessage(), 'params' => json_encode([$global_order_id, $user_id])]);
  68. return [
  69. "status" => 200,
  70. "code" => $e->getCode() ?? ErrorCode::ORDER_COMPLETE_FAIL,
  71. "result" => [],
  72. "message" => $e->getMessage()
  73. ];
  74. }
  75. }
  76. /**
  77. * 线上订单退款,整个订单退,这个是专门用于处理用户的申请退款的同意退款操作
  78. * @param $global_order_id
  79. * @param $user_id
  80. * @return array
  81. */
  82. public function onlineRefund($global_order_id, $user_id)
  83. {
  84. try {
  85. $result = $this->orderOnlineService->doRefund($global_order_id, $user_id);
  86. return [
  87. "status" => 200,
  88. "code" => 0,
  89. "result" => [],
  90. "message" => '处理成功'
  91. ];
  92. } catch (\Exception $e) {
  93. return [
  94. "status" => 200,
  95. "code" => $e->getCode(),
  96. "result" => [],
  97. "message" => $e->getMessage()
  98. ];
  99. }
  100. }
  101. /**
  102. * 线上订单单笔退款,主要用于后台强行操作退单退款
  103. * 支持单商品、单店、整单
  104. * 按比例计算红包进行退款
  105. * 比如:两个子订单和子订单商品,分别是2元,98元,使用了10元优惠券
  106. * 退2元商品时,退款金额为
  107. * 红包 (2/(98+2)*10 = 0.2
  108. * 退款:2-0.2=1.8
  109. * @param $user_id *用户ID
  110. * @param $global_order_id *全局总订单ID
  111. * @param $order_child_id *主订单ID,
  112. * @param $order_goods_id *订单商品ID
  113. * @param $note
  114. * @return array
  115. */
  116. public function onlineSingleRefund($user_id, $note, $global_order_id, $order_child_id='', $order_goods_id='')
  117. {
  118. Db::beginTransaction();
  119. try {
  120. $params = [
  121. 'user_id' => $user_id,
  122. 'note' => $note,
  123. 'global_order_id' => $global_order_id,
  124. 'order_child_id' => $order_child_id,
  125. 'order_goods_id' => $order_goods_id,
  126. ];
  127. if (!$user_id || !$global_order_id || !$note) {
  128. $this->log->event(LogLabel::ORDER_REFUND_LOG, [
  129. 'jsonrpc_order_service_exception_onlineSingleRefund' => '参数不对',
  130. 'params' => json_encode($params)
  131. ]);
  132. throw new ErrorCodeException(ErrorCode::ORDER_REFUND_FAIL);
  133. }
  134. // 主订单
  135. $orderMain = OrderMain::query()
  136. ->where(['global_order_id' => $global_order_id, 'user_id' => $user_id])
  137. ->whereIn('state', array_merge(OrderState::CAN_REFUND_DIRECT, [OrderState::REFUNDED]))
  138. ->first();
  139. if (is_null($orderMain)) {
  140. $this->log->event(LogLabel::ORDER_REFUND_LOG, [
  141. 'jsonrpc_order_service_exception_onlineSingleRefund' => '订单不存在',
  142. 'params' => json_encode($params)
  143. ]);
  144. throw new ErrorCodeException(ErrorCode::ORDER_REFUND_FAIL);
  145. }
  146. // 子订单
  147. $orderChild = null;
  148. if ($order_child_id) {
  149. $orderChild = Order::query()->with('store')->where(['order_main_id' => $orderMain->global_order_id, 'id' => $order_child_id])->first();
  150. }
  151. // 订单商品
  152. $orderGoods = null;
  153. if ($order_goods_id) {
  154. if (!$order_child_id || is_null($orderChild)) {
  155. $this->log->event(LogLabel::ORDER_REFUND_LOG, [
  156. 'jsonrpc_order_service_exception_onlineSingleRefund' => '子订单参数异常[单品]',
  157. 'params' => json_encode($params)
  158. ]);
  159. throw new ErrorCodeException(ErrorCode::ORDER_REFUND_FAIL);
  160. }
  161. $orderGoods = OrderGoods::query()
  162. ->where(['order_id' => $orderChild->id, 'id' => $order_goods_id, 'status' => 1])
  163. ->first();
  164. if (is_null($orderGoods)) {
  165. $this->log->event(LogLabel::ORDER_REFUND_LOG, [
  166. 'jsonrpc_order_service_exception_onlineSingleRefund' => '订单商品参数异常[单品]',
  167. 'params' => json_encode($params)
  168. ]);
  169. throw new ErrorCodeException(ErrorCode::ORDER_REFUND_FAIL);
  170. }
  171. }
  172. $totalAmount = $orderMain->total_money; // 订单可退款金额,总订单金额不含配送费和服务费
  173. $preRefundAmount = 0; // 预退款金额
  174. $refundAmount = 0; // 实际退款金额
  175. $refundType = 'main'; // 退款类型, Main整单 Sub子单 Goods单品
  176. if ($orderGoods) { // 1. 如果订单商品存在则说明要退单品
  177. $preRefundAmount = bcmul($orderGoods->price, $orderGoods->number, 2);
  178. $refundType = 'goods';
  179. } elseif ($orderChild) { // 2. 否则如果存在子订单说明退子订单
  180. $preRefundAmount = $orderChild->money;
  181. $refundType = 'sub';
  182. } else { // 3. 再则如果存在主订单说明退主订单
  183. $preRefundAmount = $orderMain->total_money;
  184. $refundType = 'main';
  185. }
  186. // 占订单金额的比例
  187. $rate = bcdiv($preRefundAmount, $totalAmount, 6);
  188. // 计算优惠券所占金额
  189. $couponMoney = bcmul($orderMain->coupon_money, $rate, 6);
  190. // 计算本次退款实际退款金额
  191. $refundAmount = bcsub($preRefundAmount, $couponMoney, 2);
  192. if ($refundAmount <= 0) {
  193. $this->log->event(LogLabel::ORDER_REFUND_LOG, [
  194. 'jsonrpc_order_service_exception_onlineSingleRefund' => '没有可退款金额[实际退款金额]',
  195. 'params' => json_encode($params)
  196. ]);
  197. throw new ErrorCodeException(ErrorCode::ORDER_REFUND_FAIL);
  198. }
  199. // 开始退款
  200. $config = config('wxpay');
  201. $app = Factory::payment($config);
  202. $app['guzzle_handler'] = CoroutineHandler::class;
  203. $result = $app->refund->byOutTradeNumber(
  204. $orderMain->global_order_id,
  205. $orderMain->global_order_id.$order_child_id.$order_goods_id,
  206. bcmul($orderMain->money, 100, 0),
  207. bcmul($refundAmount, 100, 0),
  208. [
  209. 'refund_desc' => '订单协商退款[' . $refundType . ']',
  210. 'notify_url' => config('wechat.notify_url.refund_single'),
  211. ]
  212. );
  213. if ($result['return_code'] == 'FAIL') {
  214. $this->log->event(LogLabel::ORDER_REFUND_LOG, [
  215. 'jsonrpc_order_service_exception_onlineSingleRefund' => $result['return_msg'] . '[微信退款失败]',
  216. 'params' => json_encode($result)
  217. ]);
  218. throw new ErrorCodeException(ErrorCode::ORDER_REFUND_FAIL);
  219. }
  220. if ($result['result_code'] == 'FAIL') {
  221. $this->log->event(LogLabel::ORDER_REFUND_LOG, [
  222. 'jsonrpc_order_service_exception_onlineSingleRefund' => $result['err_code_des'] . '[微信退款失败]' . $result['err_code'],
  223. 'params' => json_encode($result)
  224. ]);
  225. throw new ErrorCodeException(ErrorCode::ORDER_REFUND_FAIL);
  226. }
  227. // 退款申请成功,查询退款状态,此处暂时无法传递和记录单品退的信息,所以直接查询退款状态处理,不做回调
  228. $refundResult = $app->refund->queryByRefundId($result['refund_id']);
  229. $this->log->event(LogLabel::ORDER_REFUND_LOG, [
  230. 'jsonrpc_order_service_exception_onlineSingleRefund' => '[微信退款查询]',
  231. 'params' => json_encode($refundResult)
  232. ]);
  233. // 退款成功
  234. if (
  235. !($refundResult['return_code'] == 'SUCCESS'
  236. && isset($refundResult['result_code'])
  237. && $refundResult['result_code'] == 'SUCCESS')
  238. ) {
  239. throw new ErrorCodeException(ErrorCode::ORDER_REFUND_FAIL);
  240. }
  241. $currentTime = time();
  242. // 处理订单状态
  243. $orderMain->state = OrderState::REFUNDED_DIRECT;
  244. $orderMain->total_refund_note = $note;
  245. $orderMain->refund_time = $currentTime;
  246. $orderMain->save();
  247. if ($refundType == 'sub') {
  248. $orderChild->status = 3;
  249. $orderChild->refund_note = $note;
  250. $orderChild->refund_time = $currentTime;
  251. $orderChild->save();
  252. } elseif ($refundType == 'goods') {
  253. $orderGoods->status = 3;
  254. $orderGoods->refund_note = $note;
  255. $orderGoods->refund_time = $currentTime;
  256. $orderGoods->save();
  257. }
  258. // 处理用户和商户流水
  259. $orderChildren = [];
  260. if ($refundType == 'main') { # 整单退的话还得处理所有子订单的商户
  261. $orderChildren = Order::query()->with('store:user_id')->where(['order_main_id' => $orderMain->global_order_id])->get();
  262. foreach ($orderChildren as $key => &$order) {
  263. // 占订单金额的比例
  264. $rate = bcdiv($order->money, $totalAmount, 6);
  265. // 计算优惠券所占金额
  266. $couponMoney = bcmul($orderMain->coupon_money, $rate, 6);
  267. // 计算本次退款实际退款金额
  268. $refundStoreAmount = bcsub($order->money, $couponMoney, 2);
  269. $this->financialRecordService->storeRefundDirect($order->store->user_id, $order->id, $refundStoreAmount);
  270. }
  271. } elseif ($refundType == 'sub'||$refundType == 'goods') { # 退子订单或者退单品的话,商户只有一个
  272. $orderChildren = Order::query()->with('store:user_id')->where(['id' => $order_child_id])->get();
  273. $this->financialRecordService->storeRefundDirect($orderChild->store->user_id, $orderChild->id, $refundAmount);
  274. }
  275. $this->financialRecordService->userRefundDirect($orderMain->user_id, $orderMain->global_order_id, $refundAmount);
  276. Db::commit();
  277. // 记录badge
  278. $orderChildIds = array_values(array_column($orderChildren, 'store_id'));
  279. $this->badgeService->doByOrder($orderMain->user_id, $orderChildIds, $orderMain->global_order_id, OrderState::REFUNDED);
  280. return [
  281. "status" => 200,
  282. "code" => 0,
  283. "result" => [],
  284. "message" => '处理成功'
  285. ];
  286. } catch (\Exception $e) {
  287. Db::rollBack();
  288. return [
  289. "status" => 200,
  290. "code" => $e->getCode(),
  291. "result" => [],
  292. "message" => '[退款失败]'.$e->getMessage()
  293. ];
  294. }
  295. }
  296. }