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.

330 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()->where(['order_id' => $orderChild->id, 'id' => $order_goods_id])->first();
  162. if (is_null($orderGoods)) {
  163. $this->log->event(LogLabel::ORDER_REFUND_LOG, [
  164. 'jsonrpc_order_service_exception_onlineSingleRefund' => '订单商品参数异常[单品]',
  165. 'params' => json_encode($params)
  166. ]);
  167. throw new ErrorCodeException(ErrorCode::ORDER_REFUND_FAIL);
  168. }
  169. }
  170. $totalAmount = $orderMain->total_money; // 订单可退款金额,总订单金额不含配送费和服务费
  171. $preRefundAmount = 0; // 预退款金额
  172. $refundAmount = 0; // 实际退款金额
  173. $refundType = 'main'; // 退款类型, Main整单 Sub子单 Goods单品
  174. if ($orderGoods) { // 1. 如果订单商品存在则说明要退单品
  175. $preRefundAmount = bcmul($orderGoods->price, $orderGoods->number, 2);
  176. $refundType = 'goods';
  177. } elseif ($orderChild) { // 2. 否则如果存在子订单说明退子订单
  178. $preRefundAmount = $orderChild->money;
  179. $refundType = 'sub';
  180. } else { // 3. 再则如果存在主订单说明退主订单
  181. $preRefundAmount = $orderMain->total_money;
  182. $refundType = 'main';
  183. }
  184. // 占订单金额的比例
  185. $rate = bcdiv($preRefundAmount, $totalAmount, 6);
  186. // 计算优惠券所占金额
  187. $couponMoney = bcmul($orderMain->coupon_money, $rate, 6);
  188. // 计算本次退款实际退款金额
  189. $refundAmount = bcsub($preRefundAmount, $couponMoney, 2);
  190. if ($refundAmount <= 0) {
  191. $this->log->event(LogLabel::ORDER_REFUND_LOG, [
  192. 'jsonrpc_order_service_exception_onlineSingleRefund' => '没有可退款金额[实际退款金额]',
  193. 'params' => json_encode($params)
  194. ]);
  195. throw new ErrorCodeException(ErrorCode::ORDER_REFUND_FAIL);
  196. }
  197. // 开始退款
  198. $config = config('wxpay');
  199. $app = Factory::payment($config);
  200. $app['guzzle_handler'] = CoroutineHandler::class;
  201. $result = $app->refund->byOutTradeNumber(
  202. $orderMain->global_order_id,
  203. $orderMain->global_order_id.$order_child_id.$order_goods_id,
  204. bcmul($orderMain->money, 100, 0),
  205. bcmul($refundAmount, 100, 0),
  206. [
  207. 'refund_desc' => '订单协商退款[' . $refundType . ']',
  208. 'notify_url' => config('wechat.notify_url.refund_single'),
  209. ]
  210. );
  211. if ($result['return_code'] == 'FAIL') {
  212. $this->log->event(LogLabel::ORDER_REFUND_LOG, [
  213. 'jsonrpc_order_service_exception_onlineSingleRefund' => $result['return_msg'] . '[微信退款失败]',
  214. 'params' => json_encode($result)
  215. ]);
  216. throw new ErrorCodeException(ErrorCode::ORDER_REFUND_FAIL);
  217. }
  218. if ($result['result_code'] == 'FAIL') {
  219. $this->log->event(LogLabel::ORDER_REFUND_LOG, [
  220. 'jsonrpc_order_service_exception_onlineSingleRefund' => $result['err_code_des'] . '[微信退款失败]' . $result['err_code'],
  221. 'params' => json_encode($result)
  222. ]);
  223. throw new ErrorCodeException(ErrorCode::ORDER_REFUND_FAIL);
  224. }
  225. // 退款申请成功,查询退款状态,此处暂时无法传递和记录单品退的信息,所以直接查询退款状态处理,不做回调
  226. $refundResult = $app->refund->queryByRefundId($result['refund_id']);
  227. $this->log->event(LogLabel::ORDER_REFUND_LOG, [
  228. 'jsonrpc_order_service_exception_onlineSingleRefund' => '[微信退款查询]',
  229. 'params' => json_encode($refundResult)
  230. ]);
  231. // 退款成功
  232. if (
  233. !($refundResult['return_code'] == 'SUCCESS'
  234. && isset($refundResult['result_code'])
  235. && $refundResult['result_code'] == 'SUCCESS')
  236. ) {
  237. throw new ErrorCodeException(ErrorCode::ORDER_REFUND_FAIL);
  238. }
  239. $currentTime = time();
  240. // 处理订单状态
  241. $orderMain->state = OrderState::REFUNDED;
  242. $orderMain->total_refund_note = $note;
  243. $orderMain->refund_time = $currentTime;
  244. $orderMain->save();
  245. if ($refundType == 'sub') {
  246. $orderChild->status = 3;
  247. $orderChild->refund_note = $note;
  248. $orderChild->refund_time = $currentTime;
  249. $orderChild->save();
  250. } elseif ($refundType == 'goods') {
  251. $orderGoods->status = 3;
  252. $orderGoods->refund_note = $note;
  253. $orderGoods->refund_time = $currentTime;
  254. $orderGoods->save();
  255. }
  256. // 处理用户和商户流水
  257. if ($refundType == 'main') { # 整单退的话还得处理所有子订单的商户
  258. $orderChildren = Order::query()->with('store:user_id')->where(['order_main_id' => $orderMain->global_order_id])->get();
  259. foreach ($orderChildren as $key => &$order) {
  260. // 占订单金额的比例
  261. $rate = bcdiv($order->money, $totalAmount, 6);
  262. // 计算优惠券所占金额
  263. $couponMoney = bcmul($orderMain->coupon_money, $rate, 6);
  264. // 计算本次退款实际退款金额
  265. $refundStoreAmount = bcsub($order->money, $couponMoney, 2);
  266. $this->financialRecordService->storeRefundDirect($order->store->user_id, $order->id, $refundStoreAmount);
  267. }
  268. } elseif ($refundType == 'sub'||$refundType == 'goods') { # 退子订单或者退单品的话,商户只有一个
  269. $this->financialRecordService->storeRefundDirect($orderChild->store->user_id, $orderChild->id, $refundAmount);
  270. }
  271. $this->financialRecordService->userRefundDirect($orderMain->user_id, $orderMain->global_order_id, $refundAmount);
  272. Db::commit();
  273. return [
  274. "status" => 200,
  275. "code" => 0,
  276. "result" => [],
  277. "message" => '处理成功'
  278. ];
  279. } catch (\Exception $e) {
  280. Db::rollBack();
  281. return [
  282. "status" => 200,
  283. "code" => $e->getCode(),
  284. "result" => [],
  285. "message" => '[退款失败]'.$e->getMessage()
  286. ];
  287. }
  288. }
  289. }