ReferrerController.php 62 KB

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