ReferrerController.php 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254
  1. <?php
  2. namespace app\admin\controller\order;
  3. use app\admin\service\coupon\CouponService;
  4. use app\admin\service\member\MemberService;
  5. use app\admin\service\order\OrderService;
  6. use app\admin\service\order\OrderSheetService;
  7. use app\admin\service\order\PayDetailService;
  8. use app\admin\validate\order\OrderValidate;
  9. use app\controller\Curd;
  10. use app\model\Appointment;
  11. use app\model\ClientConfig;
  12. use app\model\Coupon;
  13. use app\model\Goods;
  14. use app\model\GoodsComponent;
  15. use app\model\GoodsRunning;
  16. use app\model\GoodsSku;
  17. use app\model\Member;
  18. use app\model\MemberAccount;
  19. use app\model\MemberBenefit;
  20. use app\model\MemberRole;
  21. use app\model\Order;
  22. use app\model\OrderExpress;
  23. use app\model\OrderReturn;
  24. use app\model\OrderSheet;
  25. use app\model\PayDetail;
  26. use app\model\Supplier;
  27. use app\model\SysDept;
  28. use app\model\SysUser;
  29. use support\Db;
  30. use support\exception\BusinessException;
  31. use support\Redis;
  32. use support\Request;
  33. use support\Response;
  34. use Tinywan\Jwt\JwtToken;
  35. use Webman\Event\Event;
  36. use Yansongda\Pay\Pay;
  37. class ReferrerController extends Curd
  38. {
  39. public function __construct()
  40. {
  41. $this->model = new Order();
  42. $this->validate = true;
  43. $this->validateClass = new OrderValidate();
  44. }
  45. /**
  46. * @Desc 列表
  47. * @Author Gorden
  48. * @Date 2024/3/28 15:01
  49. *
  50. * @param Request $request
  51. * @return Response
  52. * @throws \support\exception\BusinessException
  53. */
  54. public function select(Request $request): Response
  55. {
  56. $timeType = $request->get('time_type', 'add');
  57. [$where, $format, $limit, $field, $order] = $this->selectInput($request);
  58. $where['order_classify'] = 'REFERRER';
  59. if (!empty($where['order_addtimes']) && $timeType == 'add') {
  60. $where['order_addtimes'][0] = strtotime($where['order_addtimes'][0]);
  61. $where['order_addtimes'][1] = strtotime($where['order_addtimes'][1]);
  62. }
  63. $order = $request->get('order', 'desc');
  64. $orderId = $request->get('orderId');
  65. $field = $field ?? 'order_addtimes';
  66. $orderIds = [];
  67. if (!empty($orderId)) {
  68. $orderIds = Order::where('order_id', 'like', '%' . $orderId . '%')
  69. ->where('order_classify', 'REFERRER')
  70. ->pluck('order_id')
  71. ->toArray();
  72. }
  73. $goodsName = trim($request->get('goods_name', ''));
  74. if (!empty($goodsName)) {
  75. $goodsIds = Goods::where('goods_classify', 'REFERRER')
  76. ->where('goods_name', 'like', '%' . $goodsName . '%')
  77. ->pluck('goods_id')
  78. ->toArray();
  79. $goodsOrderIds = OrderSheet::whereIn('join_sheet_goods_id', $goodsIds)->pluck('join_sheet_order_id')->toArray();
  80. if (!empty($where['order_id'])) {
  81. $orderIds = array_intersect($orderIds, $goodsOrderIds);
  82. } else {
  83. $orderIds = $goodsOrderIds;
  84. }
  85. }
  86. // 付款时间
  87. $payOrderIds = [];
  88. if ($timeType == 'pay' && !empty($where['order_addtimes'])) {
  89. $payTimeStart = strtotime($where['order_addtimes'][0]);
  90. $payTimeEnd = strtotime($where['order_addtimes'][1]);
  91. unset($where['order_addtimes']);
  92. $payOrderIds = PayDetailService::getPayOrderId($payTimeStart, $payTimeEnd, ['REFERRER']);
  93. }
  94. if ((!empty($orderId) || !empty($goodsName)) && $timeType == 'pay') {
  95. $orderIds = array_intersect($orderIds, $payOrderIds);
  96. $where['order_id'] = ['in', implode(',', $orderIds)];
  97. } elseif (!empty($orderId) || !empty($goodsName)) {
  98. $where['order_id'] = ['in', implode(',', $orderIds)];
  99. } elseif ($timeType == 'pay') {
  100. $where['order_id'] = ['in', implode(',', $payOrderIds)];
  101. }
  102. $query = $this->doSelect($where, $field, $order);
  103. return $this->doFormat($query, $format, $limit);
  104. }
  105. protected function doSelect(array $where, string $field = null, string $order = 'desc')
  106. {
  107. $model = $this->model->with([
  108. 'sheets' => function ($query) {
  109. $query->select('join_sheet_order_id', 'order_sheet_id', 'join_sheet_goods_id', 'order_sheet_num', 'order_sheet_price');
  110. },
  111. 'member' => function ($query) {
  112. $query->select('member_id', 'member_mobile');
  113. },
  114. 'cert' => function ($query) {
  115. $query->select('join_cert_member_id', 'member_cert_name');
  116. },
  117. ])->leftJoin('order_return', 'order_return.join_return_order_id', '=', 'order.order_id')
  118. ->leftJoin('order_express', 'order_express.join_express_order_id', '=', 'order.order_id');
  119. // ->leftJoin('order_sheet','join_sheet_order_id','=','order.order_id');
  120. foreach ($where as $column => $value) {
  121. if (is_array($value)) {
  122. if ($value[0] === 'like' || $value[0] === 'not like') {
  123. $model = $model->where($column, $value[0], "%$value[1]%");
  124. } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
  125. $model = $model->where($column, $value[0], $value[1]);
  126. } elseif ($value[0] == 'in' && !empty($value[1])) {
  127. $valArr = $value[1];
  128. if (is_string($value[1])) {
  129. $valArr = explode(",", trim($value[1]));
  130. }
  131. $model = $model->whereIn($column, $valArr);
  132. } elseif ($value[0] == 'not in' && !empty($value[1])) {
  133. $valArr = $value[1];
  134. if (is_string($value[1])) {
  135. $valArr = explode(",", trim($value[1]));
  136. }
  137. $model = $model->whereNotIn($column, $valArr);
  138. } elseif ($value[0] == 'null') {
  139. $model = $model->whereNull($column);
  140. } elseif ($value[0] == 'not null') {
  141. $model = $model->whereNotNull($column);
  142. } elseif ($value[0] !== '' || $value[1] !== '') {
  143. $model = $model->whereBetween($column, $value);
  144. }
  145. } else {
  146. $model = $model->where($column, $value);
  147. }
  148. }
  149. if ($field) {
  150. $model = $model->orderBy($field, $order);
  151. }
  152. $model = $model->select('order.*', 'order_express.join_express_order_id', 'order_express.order_express_type', 'order_return.orders_return_id', 'order_return.join_return_order_id', 'order_return.order_return_status', 'order_return.order_return_apply_json', 'order_return.order_return_remark');
  153. return $model;
  154. }
  155. public function afterQuery($items)
  156. {
  157. foreach ($items as &$item) {
  158. $sheetDeng = '';
  159. $item['sheet'] = $item['sheets'][0] ?? [];
  160. if (!empty($item['sheet'])) {
  161. $goods = Goods::where('goods_id', $item['sheet']['join_sheet_goods_id'])->first();
  162. if (count($item['sheets']) > 1 && $goods->goods_classify == 'MEALS') {
  163. $sheetDeng = ' 等餐品';
  164. }
  165. $item['sheet']['goods_name'] = ($goods && $goods->goods_name) ? $goods->goods_name . $sheetDeng : '';
  166. $item['sheet']['goods_classify'] = $goods->goods_classify ?? '';
  167. $item['sheet']['order_sheet_num'] = intval($item['sheet']['order_sheet_num']);
  168. }
  169. unset($item['sheets']);
  170. if (isset($item['orders_return_id'])) {
  171. $item['return'] = [
  172. 'orders_return_id' => $item['orders_return_id'],
  173. 'join_return_order_id' => $item['join_return_order_id'],
  174. 'order_return_status' => $item['order_return_status'],
  175. 'order_return_apply_json' => $item['order_return_apply_json'],
  176. 'order_return_remark' => $item['order_return_remark']
  177. ];
  178. }
  179. if (isset($item['join_express_order_id'])) {
  180. $item['express'] = [
  181. 'join_express_order_id' => $item['join_express_order_id'],
  182. 'order_express_type' => $item['order_express_type']
  183. ];
  184. unset($item['join_express_order_id'], $item['order_express_type']);
  185. }
  186. $item['payDetail'] = PayDetailService::getPayWay($item['order_groupby'], $item['order_id']);
  187. }
  188. return $items;
  189. }
  190. /**
  191. * @Desc 下单+支付
  192. * @Author Gorden
  193. * @Date 2024/9/5 13:13
  194. *
  195. * @param Request $request
  196. * @return Response
  197. */
  198. public function insert(Request $request): Response
  199. {
  200. $params = $request->post();
  201. // 判断餐品是否连带着服务或实体
  202. $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify'));
  203. $params['goods_classify'] = $goodsClassifys[0];
  204. $orderExtendJson = [];
  205. Db::beginTransaction();
  206. try {
  207. // 验证线下付款密码
  208. if ($params['settlement_now'] == 'Y' && $params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['OFFLINE', 'MONEY'])) {
  209. $password = $params['offline_password'];
  210. if ($password != '666888') {
  211. throw new BusinessException('密码错误,请重新输入');
  212. }
  213. }
  214. if (!empty($params['dept_id'])) {
  215. $dept = SysDept::where('dept_id', $params['dept_id'])->first();
  216. if (!$dept) {
  217. throw new BusinessException("入伙场所不存在");
  218. }
  219. $params['dept_name'] = $dept->dept_name;
  220. $orderExtendJson = ['dept_id' => $params['dept_id'], 'dept_name' => $params['dept_name']];
  221. }
  222. // 下单账户
  223. if (empty($params['join_order_member_id']) && !empty($params['mobile'])) {
  224. if (Member::where('member_mobile', $params['mobile'])->exists()) {
  225. throw new BusinessException('会员已存在');
  226. }
  227. $params['join_order_member_id'] = $params['member_id'] = 'MR' . date('ymdHi') . random_string(4, 'up');
  228. // 创建会员
  229. MemberService::createMember($params);
  230. } else if (empty($params['join_order_member_id']) && empty($params['mobile'])) {
  231. $params['join_order_member_id'] = Member::where('member_mobile', '0000')->value('member_id');
  232. }
  233. if (empty($params['join_order_member_id'])) {
  234. throw new BusinessException('检查下单账户');
  235. }
  236. $params['orderId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  237. $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  238. // 查询是否有未完全支付订单
  239. $paidOrder = Order::where('join_order_member_id', $params['join_order_member_id'])
  240. ->where('order_category', 'REFERRER')
  241. ->where('order_status_system', 'PAYING')
  242. ->first();
  243. if (!empty($paidOrder)) {
  244. $paidOrder->order_groupby = $params['orderGroupId'];
  245. $params['orderId'] = $paidOrder->order_id;
  246. }
  247. $systemStatus = 'PAYING';
  248. // 立即结算
  249. if ($params['settlement_now'] == 'Y') {
  250. if ($params['goods_classify'] == 'REFERRER') {
  251. $params['order_is_complete'] = 'Y';
  252. $systemStatus = 'DONE';
  253. }
  254. }
  255. if ($params['settlement_now'] == 'Y' && ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY')) {
  256. if ($params['pay_category'] == 'OFFLINE' && !empty($params['pay_category_sub'])) {
  257. $params['pay_category'] = $params['pay_category_sub'];
  258. }
  259. $params['order_status_system'] = $systemStatus;
  260. $params['order_status_payment'] = 'SUCCESS';
  261. }
  262. if ($params['pay_category'] == 'QRCODE' && $params['settlement_now'] == 'Y' && !empty($params['qrcode_nbr'])) { // 付款码
  263. $result = OrderService::qrcodePay($params);
  264. $result = json_encode($result);
  265. $params['pay_json_response'] = $result;
  266. $result = json_decode($result, true);
  267. $prefix = substr($params['qrcode_nbr'], 0, 2);
  268. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  269. $params['pay_category'] = 'WXPAY';
  270. if ((!isset($result['return_code']) || $result['return_code'] != 'SUCCESS') || (!isset($result['result_code']) || $result['result_code'] != 'SUCCESS') || (empty($result['trade_state']) || $result['trade_state'] != 'SUCCESS')) {
  271. $params['order_status_system'] = 'PAYING';
  272. $params['order_status_payment'] = 'PENDING';
  273. $params['order_is_complete'] = 'N';
  274. } else {
  275. $params['order_status_system'] = $systemStatus;
  276. $params['order_status_payment'] = 'SUCCESS';
  277. }
  278. } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  279. $params['pay_category'] = 'ALIPAY';
  280. if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
  281. $params['order_status_system'] = 'PAYING';
  282. $params['order_status_payment'] = 'PENDING';
  283. $params['order_is_complete'] = 'N';
  284. } else {
  285. $params['order_status_system'] = $systemStatus;
  286. $params['order_status_payment'] = 'SUCCESS';
  287. }
  288. } else {
  289. throw new BusinessException('付款码无效');
  290. }
  291. }
  292. if (empty($paidOrder)) {
  293. $params['order_extend_json'] = $orderExtendJson;
  294. // 写入主订单
  295. $this->insertMain($params);
  296. // 订单详情
  297. $this->insertSheet($params);
  298. } else {
  299. $params['orderGroupId'] = $paidOrder->order_groupby;
  300. if ($params['order_status_payment'] == 'SUCCESS') {
  301. $params['order_amount_paid'] = $paidOrder->order_amount_paid;
  302. $paidOrder->order_amount_paid = $paidOrder->order_amount_paid + $params['order_amount_pay'];
  303. $paidOrder->order_amount_pay = $paidOrder->order_amount_paid;
  304. if (floatval($paidOrder->order_amount_paid) >= $paidOrder->order_amount_total) {
  305. $paidOrder->order_is_complete = 'Y';
  306. $paidOrder->order_status_system = 'DONE';
  307. $paidOrder->order_status_payment = 'SUCCESS';
  308. // 更新sheet
  309. OrderSheet::where('join_sheet_order_id', $paidOrder->order_id)->update(['order_sheet_status' => 'DONE']);
  310. }
  311. }
  312. $paidOrder->save();
  313. // 清除此订单的未支付记录
  314. PayDetail::whereJsonContains('join_pay_object_json->order_id', $paidOrder->order_id)->where('pay_status', 'WAITING')->delete();
  315. }
  316. // 支付记录
  317. $this->insertPayDetail($params);
  318. Db::commit();
  319. // 分期付完
  320. $full = '';
  321. if ($params['goods_classify'] == 'REFERRER' && $params['order_status_payment'] == 'SUCCESS' && (!empty($paidOrder) && floatval($paidOrder->order_amount_paid) >= $paidOrder->order_amount_total || floatval($params['order_amount_pay']) >= $params['order_amount_total'])) {
  322. $full = '-满额';
  323. $params['member_id'] = $params['join_order_member_id'];
  324. Event::dispatch('order.referrer.grant', $params);
  325. }
  326. if ($params['order_status_payment'] == 'SUCCESS') {
  327. // 入收支明细表
  328. $params['inout_category'] = '购买康养推荐官' . $full;
  329. Event::dispatch('statistics.inout.in', $params);
  330. }
  331. if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] != 'SUCCESS') {
  332. _syslog("订单", "支付异常,检查是否有轮询");
  333. return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
  334. }
  335. _syslog("订单", "创建订单成功");
  336. return json_success('创建订单成功');
  337. } catch (BusinessException $e) {
  338. Db::rollBack();
  339. dump($e->getMessage());
  340. dump($e->getTrace());
  341. _syslog("订单", $e->getMessage());
  342. return json_fail($e->getMessage());
  343. } catch (\Exception $e) {
  344. Db::rollBack();
  345. dump($e->getMessage());
  346. dump($e->getTrace());
  347. _syslog("订单", "创建订单失败");
  348. return json_fail('创建订单失败');
  349. }
  350. }
  351. /**
  352. * @Desc 支付
  353. * @Author Gorden
  354. * @Date 2024/9/5 13:12
  355. *
  356. * @param Request $request
  357. * @return Response
  358. */
  359. public function pay(Request $request)
  360. {
  361. $params = $request->post();
  362. // 验证线下付款密码
  363. if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['OFFLINE', 'MONEY'])) {
  364. $password = $params['offline_password'];
  365. if ($password != '666888') {
  366. return json_fail("密码错误,请重新输入");
  367. }
  368. }
  369. $order = Order::where('order_id', $params['order_id'])->first();
  370. if (!$order) {
  371. return json_fail('订单异常');
  372. }
  373. if ($order->order_status_system != 'PAYING') {
  374. return json_fail('订单不是可支付状态');
  375. }
  376. $params['orderId'] = $params['order_id'];
  377. $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  378. $order->order_groupby = $params['orderGroupId'];
  379. $goods = Goods::where('goods_id', $params['join_sheet_goods_id'])
  380. ->select('goods_id', 'goods_name', 'goods_classify')
  381. ->first();
  382. if (!$goods) {
  383. return json_fail('产品数据异常');
  384. }
  385. $goods = $goods->toArray();
  386. $params['goods_classify'] = $goods['goods_classify'] ?? '';
  387. // 入伙场所
  388. if (!empty($params['dept_id'])) {
  389. $orderExtendJson = [];
  390. if (!empty($order->order_extend_json)) {
  391. $orderExtendJson = json_decode($order->order_extend_json, true);
  392. }
  393. $dept = SysDept::where('dept_id', $params['dept_id'])->first();
  394. if (!$dept) {
  395. throw new BusinessException("入伙场所不存在");
  396. }
  397. $params['dept_name'] = $dept->dept_name;
  398. $orderExtendJson['dept_id'] = $params['dept_id'];
  399. $orderExtendJson['dept_name'] = $params['dept_name'];
  400. $order->order_extend_json = json_encode($orderExtendJson);
  401. }
  402. // 立即结算
  403. if ($params['goods_classify'] == 'REFERRER') {
  404. $order->order_is_complete = 'Y';
  405. $systemStatus = 'DONE';
  406. }
  407. $paymentStatus = 'PENDING';
  408. Db::beginTransaction();
  409. try {
  410. // 组合支付时,付款码应收金额
  411. $qrcodePayAmount = 0;
  412. if ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY') {
  413. $order->order_status_system = $systemStatus;
  414. $order->order_status_payment = 'SUCCESS';
  415. $paymentStatus = 'SUCCESS';
  416. if ($params['pay_category'] == 'OFFLINE' && !empty($params['pay_category_sub'])) {
  417. $params['pay_category'] = $params['pay_category_sub'];
  418. }
  419. }
  420. if (($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && !empty($params['qrcode_nbr'])) { // 付款码
  421. // 提交过来的支付分类
  422. $submitPayCategory = $params['pay_category'];
  423. // 账户支付的金额
  424. $accountAmount = $params['order_amount_pay'];
  425. if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0) {
  426. // 组合支付,改成需要付款码需要支付的金额
  427. $params['order_amount_pay'] = $qrcodePayAmount;
  428. }
  429. // 去支付
  430. $result = OrderService::qrcodePay($params);
  431. $result = json_encode($result);
  432. $params['pay_json_response'] = $result;
  433. $result = json_decode($result, true);
  434. $prefix = substr($params['qrcode_nbr'], 0, 2);
  435. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  436. $params['pay_category'] = 'WXPAY';
  437. if ((!isset($result['return_code']) || $result['return_code'] != 'SUCCESS') || (!isset($result['result_code']) || $result['result_code'] != 'SUCCESS') || (empty($result['trade_state']) || $result['trade_state'] != 'SUCCESS')) {
  438. $order->order_status_system = 'PAYING';
  439. $order->order_status_payment = 'PENDING';
  440. $order->order_is_complete = 'N';
  441. // Db::rollBack();
  442. // return json_fail('支付失败');
  443. } else {
  444. $order->order_status_system = $systemStatus;
  445. $order->order_status_payment = 'SUCCESS';
  446. $paymentStatus = 'SUCCESS';
  447. }
  448. } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  449. $params['pay_category'] = 'ALIPAY';
  450. if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
  451. $order->order_status_system = 'PAYING';
  452. $order->order_status_payment = 'PENDING';
  453. $order->order_is_complete = 'N';
  454. // Db::rollBack();
  455. // return json_fail('支付失败');
  456. } else {
  457. $order->order_status_system = $systemStatus;
  458. $order->order_status_payment = 'SUCCESS';
  459. $paymentStatus = 'SUCCESS';
  460. }
  461. } else {
  462. throw new BusinessException('付款码无效');
  463. }
  464. // 账户支付的金额
  465. $params['order_amount_pay'] = $accountAmount;
  466. }
  467. if ($order->order_status_payment == 'SUCCESS') {
  468. $order->order_amount_paid = $order->order_amount_paid + $params['order_amount_pay'];
  469. $order->order_amount_pay = $order->order_amount_paid;
  470. }
  471. // 分期,支付完就结束了
  472. if ($order->order_status_payment == 'SUCCESS' && $params['goods_classify'] == 'REFERRER' && floatval($order->order_amount_paid) >= $order->order_amount_total) {
  473. $order->order_is_complete = 'Y';
  474. }
  475. if (floatval($order->order_amount_paid) < $order->order_amount_total) {
  476. $order->order_status_system = 'PAYING';
  477. $order->order_status_payment = 'PENDING';
  478. $order->order_is_complete = 'N';
  479. }
  480. // 主订单
  481. $order->save();
  482. // sheet
  483. if ($order->order_status_payment == 'SUCCESS') {
  484. $data = [
  485. 'order_sheet_status' => $systemStatus
  486. ];
  487. if (floatval($order->order_amount_paid) < $order->order_amount_total) {
  488. $data['order_sheet_status'] = 'BEING';
  489. }
  490. OrderSheet::where('join_sheet_order_id', $params['order_id'])->update($data);
  491. }
  492. // payDetail
  493. $payData = [
  494. 'pay_amount' => $params['order_amount_pay']
  495. ];
  496. if ($paymentStatus == 'SUCCESS') {
  497. $payData['pay_paytimes'] = date('Y-m-d H:i:s');
  498. $payData['pay_status'] = 'SUCCESS';
  499. }
  500. if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
  501. $payData['pay_prepayid'] = $params['pay_category'];
  502. $payData['pay_json_response'] = $params['pay_json_response'];
  503. } else if ($params['pay_category'] == 'CASH') {
  504. $payData['pay_prepayid'] = $params['join_order_member_id'] . '-CASH';
  505. } else if ($params['pay_category'] == 'WELFARE') {
  506. $payData['pay_prepayid'] = $params['join_order_member_id'] . '-WELFARE';
  507. } else if ($params['pay_category'] == 'CARD') {
  508. $payData['pay_prepayid'] = $params['card_nbr'];
  509. } else if ($params['pay_category'] == 'OFFLINE') {
  510. $payData['pay_prepayid'] = 'OFFLINE';
  511. } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
  512. $payData['pay_prepayid'] = 'OFFLINE_ALIPAY';
  513. } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {
  514. $payData['pay_prepayid'] = 'OFFLINE_WXPAY';
  515. } else if ($params['pay_category'] == 'MONEY') {
  516. $payData['pay_prepayid'] = 'MONEY';
  517. }
  518. // 清除此订单的未支付记录
  519. PayDetail::whereJsonContains('join_pay_object_json->order_id', $order->order_id)->where('pay_status', 'WAITING')->delete();
  520. $payData['join_pay_member_id'] = $params['join_order_member_id'];
  521. $payData['join_pay_order_id'] = $order->order_groupby;
  522. $payData['pay_status'] = !empty($payData['pay_status']) && $payData['pay_status'] == 'SUCCESS' ? $payData['pay_status'] : 'WAITING';
  523. $payData['pay_category'] = $params['goods_classify'] ?? '';
  524. $payData['pay_paytimes'] = date('Y-m-d H:i:s');
  525. $payData['pay_json_request'] = json_encode($params); // {"pay-result": "支付成功", "result-datetime": "2024-07-29 18:38:21"}
  526. $payData['pay_json_response'] = !empty($payData['pay_status']) && $payData['pay_status'] == 'SUCCESS' ? json_encode([
  527. 'pay-result' => '支付成功', 'result-datetime' => date('Y-m-d H:i:s')
  528. ]) : '[]';
  529. $payData['join_pay_object_json'] = !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]';
  530. $payData['pay_addtimes'] = time();
  531. PayDetail::insert($payData);
  532. Db::commit();
  533. $full = '';
  534. // 分期付款完成
  535. if ($params['goods_classify'] == 'REFERRER' && $order->order_status_payment == 'SUCCESS' && floatval($order->order_amount_paid) >= $order->order_amount_total) {
  536. $full = '-满额';
  537. $params['member_id'] = $params['join_order_member_id'];
  538. Event::dispatch('order.complete', $params);
  539. Event::dispatch('order.referrer.grant', $params);
  540. }
  541. if ($paymentStatus == 'SUCCESS') {
  542. // 加销售量
  543. OrderSheetService::addGoodsSales($params['orderId']);
  544. // 入收支明细表
  545. $params['inout_category'] = '购买康养推荐官' . $full;
  546. Event::dispatch('statistics.inout.in', $params);
  547. }
  548. if ($order->order_status_payment != 'SUCCESS' && $paymentStatus != 'SUCCESS') {
  549. _syslog("订单", "支付异常,检查是否有轮询");
  550. return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
  551. }
  552. _syslog("订单", "订单支付成功");
  553. return json_success('支付成功');
  554. } catch (BusinessException $e) {
  555. dump($e->getMessage());
  556. Db::rollBack();
  557. _syslog("订单", "订单支付失败:" . $e->getMessage());
  558. return json_fail("支付失败:" . $e->getMessage());
  559. } catch (\Exception $e) {
  560. dump($e->getMessage());
  561. Db::rollBack();
  562. _syslog("订单", "订单支付失败");
  563. return json_fail('支付失败');
  564. }
  565. }
  566. /**
  567. * @Desc
  568. * @Author Gorden
  569. * @Date 2024/6/7 10:30
  570. *
  571. * @param $params
  572. * @return void
  573. * @throws BusinessException
  574. */
  575. public function insertMain($params)
  576. {
  577. try {
  578. $orderCategory = 'NORMAL';
  579. if (!empty($params['order_category'])) {
  580. $orderCategory = $params['order_category'];
  581. } else if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  582. $orderCategory = 'DISHES';
  583. } else if (isset($params['goods_classify'])) {
  584. $orderCategory = $params['goods_classify'];
  585. }
  586. if (empty($params['order_extend_json'])) {
  587. $params['order_extend_json'] = [];
  588. } else {
  589. if (is_json($params['order_extend_json'])) {
  590. $params['order_extend_json'] = json_decode($params['order_extend_json'], true);
  591. }
  592. }
  593. // 推荐人
  594. $params['order_extend_json']['referee'] = $params['referee'] ?? '';
  595. $data = [
  596. 'order_id' => $params['orderId'],
  597. 'order_groupby' => $params['orderGroupId'],
  598. 'join_order_member_id' => $params['join_order_member_id'],
  599. 'order_name' => date('Y-m-d H:i:s') . '-订单',
  600. 'order_amount_total' => $params['order_amount_total'],
  601. 'order_amount_pay' => $params['order_status_payment'] == 'SUCCESS' ? $params['order_amount_pay'] : 0,
  602. 'order_amount_paid' => $params['order_status_payment'] == 'SUCCESS' ? $params['order_amount_pay'] : 0,
  603. 'order_category' => $orderCategory,
  604. 'order_classify' => $orderCategory,
  605. 'order_is_complete' => floatval($params['order_amount_pay']) >= floatval($params['order_amount_total']) && $params['order_status_payment'] == 'SUCCESS' ? 'Y' : 'N',
  606. 'order_status_system' => floatval($params['order_amount_pay']) >= floatval($params['order_amount_total']) && $params['order_status_payment'] == 'SUCCESS' ? 'DONE' : 'PAYING',
  607. 'order_status_payment' => floatval($params['order_amount_pay']) >= floatval($params['order_amount_total']) && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'PENDING',
  608. 'order_status_storage' => $params['order_status_storage'],
  609. 'order_platform' => $params['order_platform'],
  610. 'order_remark' => $params['order_remark'] ?? '',
  611. 'order_discount_json' => $params['order_discount_json'] ?? '[]',
  612. 'order_config_json' => $params['order_config_json'] ?? '[]',
  613. 'order_express_json' => $params['order_express_json'] ?? '[]',
  614. 'order_extend_json' => $params['order_extend_json'] ? json_encode($params['order_extend_json']) : '[]',
  615. 'order_addtimes' => time(),
  616. 'order_add_user_id'=>JwtToken::getCurrentId()
  617. ];
  618. Order::insert($data);
  619. } catch (\Exception $e) {
  620. dump($e->getMessage());
  621. throw new BusinessException('订单创建信息失败');
  622. }
  623. }
  624. /**
  625. * @Desc
  626. * @Author Gorden
  627. * @Date 2024/6/7 10:25
  628. *
  629. * @param $params
  630. * @return void
  631. * @throws BusinessException
  632. */
  633. public function insertSheet($params)
  634. {
  635. try {
  636. $orderSheetIds = [];
  637. foreach ($params['goodsContentList'] as $goods) {
  638. //{"unit": "份", "table": null, "premises": "15"}
  639. $price = floatval($goods['goods_sales_price']);
  640. $extendJson['unit'] = $goods['sku_name'];
  641. if (isset($params['submit_premises_id'])) {
  642. $extendJson['premises'] = $params['submit_premises_id'];
  643. }
  644. if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  645. $extendJson['table'] = null;
  646. }
  647. $orderSheetStatus = 'PAYING';
  648. if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS') {
  649. if (floatval($params['order_amount_pay']) >= floatval($params['order_amount_total'])) {
  650. $orderSheetStatus = 'DONE';
  651. } else {
  652. $orderSheetStatus = 'BEING';
  653. }
  654. }
  655. $data = [
  656. 'join_sheet_member_id' => $params['join_order_member_id'],
  657. 'join_sheet_order_id' => $params['orderId'],
  658. 'join_sheet_goods_id' => $goods['goods_id'],
  659. 'join_sheet_goods_sku_id' => $goods['sku_id'],
  660. 'order_sheet_status' => $orderSheetStatus,
  661. 'order_sheet_category' => 'REFERRER',
  662. 'order_sheet_num' => $goods['nbr'],
  663. 'order_sheet_price' => $goods['goods_sales_price'],
  664. 'order_sheet_price_pay' => $goods['goods_sales_price'],
  665. 'order_sheet_amount' => $price * $goods['nbr'],
  666. 'order_sheet_pay' => $price * $goods['nbr'],
  667. 'order_sheet_task_status' => 'NONE',
  668. 'order_sheet_remark' => $params['order_remark'] ?? '',
  669. 'order_sheet_addtimes' => time(),
  670. 'order_sheet_extend_json' => json_encode($extendJson)
  671. ];
  672. $orderSheetId = OrderSheet::insertGetId($data);
  673. $orderSheetIds[] = $orderSheetId;
  674. // 减库存,规格和总库存
  675. if (!isset($params['submit_goods_classify']) || !in_array($params['submit_goods_classify'], ['MEALS', 'PACKAGE'])) {
  676. $goodsSku = GoodsSku::where('goods_sku_id', $goods['sku_id'])->first();
  677. $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
  678. if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) {
  679. $skuStorageJson['storage'] = $skuStorageJson['storage'] - $goods['nbr'];
  680. }
  681. if (!isset($skuStorageJson['storage']) || (!empty($skuStorageJson['storage']) && $skuStorageJson['storage'] < 0)) {
  682. throw new BusinessException('库存不足');
  683. }
  684. $goodsSku->goods_sku_storage_json = json_encode($skuStorageJson);
  685. $goodsSku->save();
  686. }
  687. $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
  688. $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
  689. if ($goodsRunning->goods_running_storage < 0) {
  690. throw new BusinessException('库存不足');
  691. }
  692. if ($params['order_status_payment'] == 'SUCCESS') {
  693. $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale + $goods['nbr'];
  694. }
  695. $goodsRunning->save();
  696. }
  697. return $orderSheetIds;
  698. } catch (\support\exception\BusinessException $e) {
  699. dump($e->getMessage() . '||' . $e->getLine());
  700. throw new BusinessException($e->getMessage());
  701. } catch (\Exception $e) {
  702. dump($e->getMessage() . '||' . $e->getLine());
  703. throw new BusinessException('订单创建失败');
  704. }
  705. }
  706. /**
  707. * @Desc
  708. * @Author Gorden
  709. * @Date 2024/6/7 10:35
  710. *
  711. * @param $params
  712. * @return void
  713. * @throws BusinessException
  714. */
  715. public function insertPayDetail($params)
  716. {
  717. try {
  718. if (in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
  719. $payPrepayid = $params['pay_category'];
  720. } else if ($params['pay_category'] == 'OFFLINE') {
  721. $payPrepayid = 'OFFLINE';
  722. } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
  723. $payPrepayid = 'OFFLINE_ALIPAY';
  724. } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {
  725. $payPrepayid = 'OFFLINE_WXPAY';
  726. } else if ($params['pay_category'] == 'MONEY') {
  727. $payPrepayid = 'MONEY';
  728. } else {
  729. $payPrepayid = $params['join_order_member_id'] . '-' . $params['pay_category'];
  730. }
  731. $data = [
  732. 'join_pay_member_id' => $params['join_order_member_id'],
  733. 'join_pay_order_id' => $params['orderGroupId'],
  734. 'pay_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
  735. 'pay_category' => $params['goods_classify'],
  736. 'pay_amount' => $params['order_amount_pay'],
  737. 'pay_prepayid' => $payPrepayid,
  738. 'pay_paytimes' => date('Y-m-d H:i:s'),
  739. 'join_pay_object_json' => !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]',
  740. 'pay_json_request' => json_encode($params),
  741. 'pay_json_response' => $params['pay_json_response'] ?? '[]',
  742. 'pay_remark' => $params['order_remark'] ?? '',
  743. 'pay_addtimes' => time(),
  744. ];
  745. PayDetail::insert($data);
  746. } catch (\Exception $e) {
  747. dump($e->getMessage());
  748. throw new BusinessException('创建支付记录失败');
  749. }
  750. }
  751. /**
  752. * @Desc 订单商品详情
  753. * @Author Gorden
  754. * @Date 2024/3/29 8:50
  755. *
  756. * @param Request $request
  757. * @return Response
  758. */
  759. public function sheet(Request $request)
  760. {
  761. try {
  762. $orderId = $request->get('order_id');
  763. $orderSheet = OrderSheet::with([
  764. 'member' => function ($query) {
  765. $query->select('member_id', 'member_mobile', 'member_is_owner', 'join_member_role_id', 'member_is_vip', 'member_is_partner', 'member_is_referrer');
  766. },
  767. 'goods' => function ($query) {
  768. $query->select('goods_id', 'goods_name', 'goods_cover', 'goods_market_price', 'goods_sales_price', 'goods_classify', 'goods_if_express');
  769. },
  770. 'memberInfo',
  771. 'cert',
  772. 'sku' => function ($query) {
  773. $query->where('goods_sku_status', 'ON')
  774. ->select('goods_sku_id', 'join_sku_goods_id', 'goods_sku_specs_json', 'goods_sku_sales_price');
  775. },
  776. 'skus',
  777. 'refund' => function ($query) {
  778. $query->select('join_return_order_id', 'order_return_status');
  779. }
  780. ])->where('join_sheet_order_id', $orderId)
  781. ->orderBy('order_sheet_id', 'DESC')
  782. ->get()
  783. ->toArray();
  784. $order = Order::where('order_id', $orderId)->first();
  785. $express = OrderExpress::where('join_express_order_id', $orderId)->first();
  786. $premises = '';
  787. if ($express && $express->order_express_type == '自提') {
  788. $premises = $express->order_express_company;
  789. }
  790. $sheetAmount = 0;
  791. foreach ($orderSheet as &$item) {
  792. $sheetAmount += $item['order_sheet_amount'];
  793. $item['goods']['goods_cover'] = getenv('STORAGE_DOMAIN') . $item['goods']['goods_cover'];
  794. if (!empty($item['goods']) && $item['goods']['goods_classify'] == 'PACKAGE') {
  795. $components = GoodsComponent::with('goods')
  796. ->where('join_component_master_goods_id', $item['goods']['goods_id'])
  797. ->select('join_component_master_goods_id', 'join_component_goods_id', 'goods_component_price',
  798. 'goods_component_price', 'goods_component_json')
  799. ->get()
  800. ->toArray();
  801. $goodsArr = [];
  802. foreach ($components as $component) {
  803. $configJson = !empty($component['goods_component_json']) ? json_decode($component['goods_component_json'], true) : [];
  804. if (!empty($component['goods'])) {
  805. $supplierName = Supplier::where('supplier_id', $component['goods']['join_goods_supplier_id'])->value('supplier_name');
  806. $benefit = MemberBenefit::where('join_benefit_member_id', $item['join_sheet_member_id'])
  807. ->where('join_benefit_goods_id', $component['goods']['goods_id'])
  808. ->where('join_benefit_order_id', $orderId)
  809. ->first();
  810. $goodsArr[] = [
  811. 'goods_name' => $component['goods']['goods_name'],
  812. 'goods_cover' => getenv('STORAGE_DOMAIN') . $component['goods']['goods_cover'],
  813. 'supplier_name' => $supplierName,
  814. 'nbr' => $configJson['nbr'] ?? 0,
  815. 'used' => !empty($benefit->member_benefit_used_count) ? intval($benefit->member_benefit_used_count) : ''
  816. ];
  817. }
  818. }
  819. $item['goods']['components'] = $goodsArr;
  820. }
  821. if (!empty($item['sku'])) {
  822. if (!empty($item['sku']['goods_sku_specs_json'])) {
  823. $specsJson = json_decode($item['sku']['goods_sku_specs_json'], true);
  824. $skuName = '';
  825. foreach ($specsJson as $specsKey => $skuSpecs) {
  826. if (is_array($skuSpecs)) {
  827. $skuName = $skuName . ' ' . implode(' ', $skuSpecs) . ';';
  828. } else {
  829. $skuName = $skuName . ' ' . $skuSpecs . ';';
  830. }
  831. }
  832. $item['sku']['goods_sku_title'] = rtrim($skuName, ';');
  833. }
  834. }
  835. if (!empty($item['skus'])) {
  836. foreach ($item['skus'] as $key => $skus) {
  837. if (!empty($skus['goods_sku_specs_json'])) {
  838. $item['skus'][$key]['goods_sku_specs_json'] = json_decode($skus['goods_sku_specs_json']);
  839. $skuName = '';
  840. foreach ($item['skus'][$key]['goods_sku_specs_json'] as $specsKey => $skuSpecs) {
  841. $keyStr = ($specsKey == '规格') ? '' : ($specsKey . ':');
  842. if (is_array($skuSpecs)) {
  843. $skuName = $skuName . $keyStr . ' ' . implode(' ', $skuSpecs) . '; ';
  844. } else {
  845. $skuName = $skuName . $keyStr . ' ' . $skuSpecs . '; ';
  846. }
  847. }
  848. $item['skus'][$key]['sku_name'] = rtrim($skuName, '; ');
  849. }
  850. }
  851. } else {
  852. $item['skus'] = [];
  853. }
  854. if (in_array($item['goods']['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $order->order_status_system == 'DONE') {
  855. $item['appontment'] = [];
  856. $appontments = Appointment::where('join_appointment_order_id', $orderId)
  857. ->where('appointment_status', 'DONE')
  858. ->select('appointment_status', 'appointment_id', 'appointment_done_datetime', 'appointment_done_json', 'appointment_apply_json')
  859. ->get()
  860. ->toArray();
  861. foreach ($appontments as $appontment) {
  862. $doneJson = [];
  863. $username = '';
  864. if (!empty($appontment['appointment_done_json'])) {
  865. $doneJson = json_decode($appontment['appointment_done_json'], true);
  866. if (isset($doneJson['charge'])) {
  867. $username = SysUser::where('user_id', $doneJson['charge']['charge_user_id'])->value('user_name');
  868. }
  869. }
  870. $person = 1;
  871. if (!empty($appontment->appointment_apply_json)) {
  872. $applyJson = json_decode($appontment->appointment_apply_json, true);
  873. if (isset($applyJson['person'])) {
  874. $person = $applyJson['person'];
  875. }
  876. }
  877. $item['appontment'][] = [
  878. 'member' => ($item['cert'] ? $item['cert']['member_cert_name'] . '-' : '') . ($item['member'] ? $item['member']['member_mobile'] : ''),
  879. 'goods_name' => $item['goods']['goods_name'],
  880. 'premisses' => isset($doneJson['charge']) ? $doneJson['charge']['charge_premises'] : '',
  881. 'username' => $username,
  882. 'nbr' => $person,
  883. 'done_time' => $appontment['appointment_done_datetime'],
  884. 'appointment_status' => $appontment['appointment_status'],
  885. ];
  886. }
  887. }
  888. if (!empty($item['order_sheet_extend_json']) && !$express) {
  889. $extendJson = json_decode($item['order_sheet_extend_json'], true);
  890. if (isset($extendJson['address_id'])) {
  891. $address = ClientConfig::where('client_config_id', $extendJson['address_id'])->first();
  892. if (!empty($address)) {
  893. $valJson = json_decode($address->client_config_val_json, true);
  894. $express = [
  895. 'order_express_address' => $valJson['address'] . ($valJson['numbers'] ?? ''),
  896. 'order_express_city' => $valJson['city'],
  897. 'order_express_mobile' => $valJson['mobile'],
  898. 'order_express_person' => $valJson['person']
  899. ];
  900. }
  901. }
  902. }
  903. $item['member']['level'] = '普通会员';
  904. if (!empty($item['member']['join_member_role_id'])) {
  905. $item['member']['level'] = MemberRole::where('member_role_id', $item['member']['join_member_role_id'])->value('member_role_name');
  906. }
  907. $item['member_info']['member_info_nickname'] = MemberService::getNickname(!empty($item['member_info']) ? $item['member_info']['member_info_nickname'] : '', (!empty($item['member']) ? $item['member']['member_mobile'] : ''));
  908. $item['member_info']['member_info_headimg'] = MemberService::getAvatarUrl(!empty($item['member_info']) && !empty($item['member_info']['member_info_headimg']) ? $item['member_info']['member_info_headimg'] : '');
  909. }
  910. $order->sheet_amount = number_format($sheetAmount, 2);
  911. $payDetails = PayDetail::whereJsonContains('join_pay_object_json->order_id', $order->order_id)
  912. ->where('pay_category', 'REFERRER')
  913. ->where('pay_status', 'SUCCESS')
  914. ->select('pay_id', 'pay_category', 'pay_prepayid', 'pay_paytimes', 'pay_status', 'pay_amount', 'pay_extend_json')
  915. ->orderBy('pay_addtimes', 'DESC')
  916. ->get();
  917. $order->pay_amount_total = 0;
  918. foreach ($payDetails as &$payDetail) {
  919. $categoryArray = explode('-', $payDetail->pay_prepayid);
  920. if (isset($categoryArray[1])) {
  921. $payDetail->pay_category = $categoryArray[1];
  922. } else if (in_array($categoryArray[0], ['WXPAY', 'ALIPAY', 'OFFLINE', 'OFFLINE_ALIPAY', 'OFFLINE_WXPAY', 'MONEY'])) {
  923. $payDetail->pay_category = $categoryArray[0];
  924. }
  925. if (!empty($payDetail->pay_extend_json)) {
  926. $payExtendJson = json_decode($payDetail->pay_extend_json, true);
  927. $order->cancel_times = $payExtendJson['cancel_times'] ?? '';
  928. if (isset($payExtendJson['ticket'])) {
  929. $payDetail->ticket = str_replace('/thumb', '', getenv("STORAGE_DOMAIN") . $payExtendJson['ticket']);
  930. }
  931. }
  932. $order->pay_amount_total += $payDetail->pay_amount;
  933. }
  934. if (!empty($order->order_config_json)) {
  935. $orderConfigJson = json_decode($order->order_config_json, true);
  936. if (isset($orderConfigJson['reach'])) {
  937. $order->reach = $orderConfigJson['reach'];
  938. }
  939. if (isset($orderConfigJson['table'])) {
  940. $order->table = $orderConfigJson['table'];
  941. }
  942. if (isset($orderConfigJson['eat'])) {
  943. $order->eat = $orderConfigJson['eat'];
  944. }
  945. if (isset($orderConfigJson['express'])) {
  946. $order->express = $orderConfigJson['express'];
  947. }
  948. if (isset($orderConfigJson['premises'])) {
  949. $order->premises = $orderConfigJson['premises'];
  950. }
  951. if (isset($orderConfigJson['tableid'])) {
  952. $order->dept_table_id = $orderConfigJson['tableid'];
  953. }
  954. }
  955. if (!empty($order->order_extend_json)) {
  956. $orderExtendJson = json_decode($order->order_extend_json, true);
  957. $order->referee = $orderExtendJson['referee'] ?? '';
  958. if (isset($orderExtendJson['cancel_times'])) {
  959. $order->cancel_times = $orderExtendJson['cancel_times'];
  960. }
  961. if (isset($orderExtendJson['free_remark'])) {
  962. $order->free_remark = $orderExtendJson['free_remark'];
  963. }
  964. if (isset($orderExtendJson['dept_id'])) {
  965. $order->dept_id = $orderExtendJson['dept_id'];
  966. }
  967. }
  968. $discount = ['coupon_name' => '', 'classify' => '', 'value' => 0];
  969. if (!empty($order->order_discount_json)) {
  970. $orderDiscountJson = json_decode($order->order_discount_json, true);
  971. foreach ($orderDiscountJson as $discountItem) {
  972. if (!empty($discountItem['coupon_id'])) {
  973. $coupon = Coupon::where('coupon_id', $discountItem['coupon_id'])
  974. ->select('coupon_name', 'coupon_classify', 'coupon_category', 'coupon_value', 'coupon_minimum_limit')
  975. ->first();
  976. if (!$coupon) {
  977. continue;
  978. }
  979. $classify = CouponService::couponClassifyInfo($coupon->coupon_classify, $coupon->coupon_category, $coupon->coupon_value, $coupon->coupon_minimum_limit);
  980. $discount['coupon_name'] .= $coupon->coupon_classify . ':' . $coupon->coupon_name . '(优惠¥' . sprintf("%.2f", $discountItem['coupon_value']) . '), ';
  981. }
  982. if ($discountItem['coupon_classify'] == '退款') {
  983. continue;
  984. }
  985. if (empty($discountItem['coupon_id']) && !empty($discountItem['coupon_classify'])) {
  986. if (!empty($discountItem['coupon_detail_id'])) {
  987. $discount['classify'] .= $discountItem['coupon_detail_id'][0] . '(优惠¥' . sprintf("%.2f", $discountItem['coupon_value']) . '), ';
  988. } else {
  989. $discount['classify'] .= $discountItem['coupon_classify'] . '(优惠¥' . sprintf("%.2f", $discountItem['coupon_value']) . '), ';
  990. }
  991. }
  992. if (!empty($discountItem['coupon_value'])) {
  993. $discount['value'] += $discountItem['coupon_value'];
  994. }
  995. }
  996. if (!empty($discount['coupon_name'])) {
  997. $discount['coupon_name'] = rtrim($discount['coupon_name'], ', ');
  998. }
  999. if (!empty($discount['classify'])) {
  1000. $discount['classify'] = rtrim($discount['classify'], ', ');
  1001. }
  1002. }
  1003. $discount['value'] = sprintf("%.2f", $discount['value']);
  1004. $order->discount = $discount;
  1005. $order->premises = $order->premises ?? $premises;
  1006. $data = [
  1007. 'order' => $order,
  1008. 'sheet' => json_decode(json_encode($orderSheet)),
  1009. 'express' => json_decode(json_encode($express)),
  1010. 'payDetails' => json_decode(json_encode($payDetails))
  1011. ];
  1012. return json_success('', $data);
  1013. } catch (\Exception $e) {
  1014. dump($e->getMessage());
  1015. }
  1016. }
  1017. /**
  1018. * @Desc 获取分期的订单
  1019. * @Author Gorden
  1020. * @Date 2024/9/10 15:14
  1021. *
  1022. * @param Request $request
  1023. * @return Response
  1024. */
  1025. public function getPaidOrder(Request $request)
  1026. {
  1027. $memberId = $request->get('member_id');
  1028. if (!$memberId) {
  1029. return json_fail('参数异常');
  1030. }
  1031. $order = Order::where('join_order_member_id', $memberId)
  1032. ->where('order_category', 'REFERRER')
  1033. ->where('order_status_system', 'PAYING')
  1034. ->select('order_id', 'order_amount_total', 'order_amount_paid', 'order_amount_pay', 'order_extend_json')
  1035. ->first();
  1036. return json_success('', $order);
  1037. }
  1038. /**
  1039. * @Desc 上传支付凭证
  1040. * @Author Gorden
  1041. * @Date 2024/9/12 10:14
  1042. *
  1043. * @param Request $request
  1044. * @return Response
  1045. */
  1046. public function uploadTicket(Request $request)
  1047. {
  1048. $payId = $request->post('pay_id');
  1049. $url = $request->post('url');
  1050. if (!$payId || !$url) {
  1051. return json_fail("参数异常");
  1052. }
  1053. $url = str_replace(getenv("STORAGE_DOMAIN"), '', $url);
  1054. try {
  1055. $payDetail = PayDetail::where('pay_id', $payId)->first();
  1056. if (!$payDetail) {
  1057. return json_fail('数据异常');
  1058. }
  1059. $extendJson = [];
  1060. if (!empty($payDetail->pay_extend_json)) {
  1061. $extendJson = json_decode($payDetail->pay_extend_json, true);
  1062. }
  1063. $extendJson['ticket'] = $url;
  1064. $payDetail->pay_extend_json = json_encode($extendJson);
  1065. dump($payDetail->save());
  1066. return json_success('success');
  1067. } catch (\Exception $e) {
  1068. return json_fail("上传附件失败");
  1069. }
  1070. }
  1071. /**
  1072. * @Desc 查询订单状态
  1073. * @Author Gorden
  1074. * @Date 2024/8/19 11:55
  1075. *
  1076. * @param Request $request
  1077. * @return Response|void
  1078. */
  1079. public function getOrderPayStatus(Request $request)
  1080. {
  1081. $groupId = $request->get('group_id');
  1082. if (!$groupId) {
  1083. return json_fail('参数异常');
  1084. }
  1085. $order = Order::where('order_groupby', $groupId)->first();
  1086. if (empty($order)) {
  1087. return json_fail('订单不存在');
  1088. }
  1089. $order = $order->toArray();
  1090. $sheet = OrderSheet::where('join_sheet_order_id', $order['order_id'])
  1091. ->select('order_sheet_id', 'join_sheet_goods_id', 'join_sheet_goods_sku_id')
  1092. ->first();
  1093. $payDetailType = PayDetail::where('join_pay_order_id', $groupId)->pluck('pay_prepayid')->toArray();
  1094. try {
  1095. Db::beginTransaction();
  1096. $payStatus = 'N';
  1097. $payAmount = 0;
  1098. if (in_array('WXPAY', $payDetailType)) {
  1099. $result = Pay::wechat(config('payment.wxpay'))->find($groupId, 'pos');
  1100. $result = json_decode(json_encode($result), true);
  1101. // $result = '{"return_code":"SUCCESS","return_msg":"OK","result_code":"SUCCESS","mch_id":"1680393367","appid":"wxc6274da7198e3eb4","openid":"o3JAn6Ii_bAlxS-jbNEC4WnPhdwM","is_subscribe":"N","trade_type":"MICROPAY","trade_state":"SUCCESS","bank_type":"OTHERS","total_fee":"3","fee_type":"CNY","cash_fee":"1000","cash_fee_type":"CNY","transaction_id":"4200067718202409250802875650","out_trade_no":"OD24092518408RV7","attach":[],"time_end":"20240925184009","trade_state_desc":"支付成功","nonce_str":"OeGOkjch4eaV5qIt","sign":"6DCB3BFC594EBC018A2BEE2C3DFEA4E3"}';
  1102. // $result = json_decode($result, true);
  1103. if (!empty($result['return_code']) && $result['return_code'] == 'SUCCESS' && !empty($result['result_code']) && $result['result_code'] == 'SUCCESS' && !empty($result['trade_state']) && $result['trade_state'] == 'SUCCESS') {
  1104. $payStatus = 'Y';
  1105. $payAmount = ($result['total_fee'] / 100);
  1106. $orderUpdateData['order_status_payment'] = 'PENDING';
  1107. $orderUpdateData['order_amount_paid'] = $order['order_amount_paid'] + $payAmount;
  1108. $orderUpdateData['order_amount_pay'] = $order['order_amount_pay'] + $payAmount;
  1109. if ($order['order_amount_paid'] + $payAmount >= $order['order_amount_total']) {
  1110. $orderUpdateData['order_status_payment'] = 'SUCCESS';
  1111. $orderUpdateData['order_status_system'] = 'DONE';
  1112. $orderUpdateData['order_is_complete'] = 'Y';
  1113. }
  1114. // 主订单
  1115. Order::where('order_groupby', $groupId)->update($orderUpdateData);
  1116. // Sheet
  1117. OrderSheet::where('join_sheet_order_id', $order['order_id'])->where('order_sheet_status', 'PAYING')->update(['order_sheet_status' => 'DONE']);
  1118. // 支付记录
  1119. PayDetail::where('join_pay_order_id', $order['order_groupby'])->where('pay_prepayid', 'WXPAY')->update([
  1120. 'pay_status' => 'SUCCESS',
  1121. 'pay_paytimes' => date('Y-m-d H:i:s'),
  1122. 'pay_json_response' => json_encode($result)
  1123. ]);
  1124. }
  1125. } else if (in_array('ALIPAY', $payDetailType)) {
  1126. $result = Pay::alipay(config('payment.alipay'))->find($groupId);
  1127. $result = json_decode(json_encode($result), true);
  1128. // $result = '{"code":"10000","msg":"Success","buyer_logon_id":"138******93","buyer_pay_amount":"5.87","fund_bill_list":[{"amount":"5.69","fund_channel":"ALIPAYACCOUNT"},{"amount":"0.18","fund_channel":"COUPON"},{"amount":"0.13","fund_channel":"DISCOUNT"}],"invoice_amount":"5.69","out_trade_no":"OD2409251550Q07A","point_amount":"0.00","receipt_amount":"0.01","send_pay_date":"2024-09-25 15:50:22","total_amount":"0.01","trade_no":"2024092523001439431419750998","trade_status":"TRADE_SUCCESS","buyer_open_id":"04309N2aVhSZz4cKwN_DN2DQa7ekM3z5n8kscQHsmIZOJsf"}';
  1129. // $result = json_decode($result, true);
  1130. if (!empty($result['code']) && $result['code'] == '10000' && !empty($result['trade_status']) && $result['trade_status'] == 'TRADE_SUCCESS') {
  1131. $payStatus = 'Y';
  1132. $payAmount = $result['total_amount'];
  1133. $orderUpdateData['order_status_payment'] = 'PENDING';
  1134. $orderUpdateData['order_amount_paid'] = $order['order_amount_paid'] + $payAmount;
  1135. $orderUpdateData['order_amount_pay'] = $order['order_amount_pay'] + $payAmount;
  1136. if ($order['order_amount_paid'] + $payAmount >= $order['order_amount_total']) {
  1137. $orderUpdateData['order_status_payment'] = 'SUCCESS';
  1138. $orderUpdateData['order_status_system'] = 'DONE';
  1139. $orderUpdateData['order_is_complete'] = 'Y';
  1140. }
  1141. // 主订单
  1142. Order::where('order_groupby', $groupId)->update($orderUpdateData);
  1143. // Sheet
  1144. OrderSheet::where('join_sheet_order_id', $order['order_id'])->where('order_sheet_status', 'PAYING')->update(['order_sheet_status' => 'DONE']);
  1145. // 支付记录
  1146. PayDetail::where('join_pay_order_id', $order['order_groupby'])->where('pay_prepayid', 'ALIPAY')->update([
  1147. 'pay_status' => 'SUCCESS',
  1148. 'pay_paytimes' => date('Y-m-d H:i:s'),
  1149. 'pay_json_response' => json_encode($result)
  1150. ]);
  1151. }
  1152. }
  1153. $full = '';
  1154. if ($payStatus == 'Y') {
  1155. if ($order['order_amount_paid'] + $payAmount >= $order['order_amount_total']) {
  1156. $full = '-满额';
  1157. $params['member_id'] = $order['join_order_member_id'];
  1158. $params['orderId'] = $order['order_id'];
  1159. $params['order_amount_pay'] = $payAmount;
  1160. $params['order_amount_total'] = $order['order_amount_total'];
  1161. $params['join_sheet_goods_id'] = $sheet->join_sheet_goods_id;
  1162. if (!empty($order['order_extend_json'])) {
  1163. $orderExtendJson = json_decode($order['order_extend_json'], true);
  1164. $params['dept_id'] = $orderExtendJson['dept_id'] ?? '';
  1165. $params['dept_name'] = $orderExtendJson['dept_name'] ?? '';
  1166. }
  1167. Event::dispatch('order.referrer.grant', $params);
  1168. }
  1169. Db::commit();
  1170. // 入收支明细表
  1171. $params['orderId'] = $order['order_id'];
  1172. $params['inout_category'] = '购买康养推荐官' . $full;
  1173. Event::dispatch('statistics.inout.in', $params);
  1174. return json_success('success');
  1175. }
  1176. Db::rollBack();
  1177. return json_fail('没有查询到记录');
  1178. } catch (BusinessException $e) {
  1179. Db::rollBack();
  1180. _syslog("支付轮询", '订单支付异常:' . $e->getMessage());
  1181. return json_fail($e->getMessage());
  1182. } catch (\Exception $e) {
  1183. dump($e->getMessage());
  1184. Db::rollBack();
  1185. return json_fail('查询失败');
  1186. }
  1187. }
  1188. }