PayNotifyLogic.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | LikeShop100%开源免费商用电商系统
  4. // +----------------------------------------------------------------------
  5. // | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
  6. // | 开源版本可自由商用,可去除界面版权logo
  7. // | 商业版本务必购买商业授权,以免引起法律纠纷
  8. // | 禁止对系统程序代码以任何目的,任何形式的再发布
  9. // | Gitee下载:https://gitee.com/likeshop_gitee/likeshop
  10. // | 访问官网:https://www.likemarket.net
  11. // | 访问社区:https://home.likemarket.net
  12. // | 访问手册:http://doc.likemarket.net
  13. // | 微信公众号:好象科技
  14. // | 好象科技开发团队 版权所有 拥有最终解释权
  15. // +----------------------------------------------------------------------
  16. // | Author: LikeShopTeam
  17. // +----------------------------------------------------------------------
  18. namespace app\common\logic;
  19. use app\adminapi\logic\distribution\DistributionLevelLogic;
  20. use app\common\cache\YlyPrinterCache;
  21. use app\common\enum\AccountLogEnum;
  22. use app\common\enum\DeliveryEnum;
  23. use app\common\enum\FootprintEnum;
  24. use app\common\enum\IntegralGoodsEnum;
  25. use app\common\enum\IntegralOrderEnum;
  26. use app\common\enum\NoticeEnum;
  27. use app\common\enum\OrderEnum;
  28. use app\common\enum\OrderLogEnum;
  29. use app\common\enum\PayEnum;
  30. use app\common\enum\PrinterEnum;
  31. use app\common\model\Goods;
  32. use app\common\model\IntegralGoods;
  33. use app\common\model\IntegralOrder;
  34. use app\common\model\Order;
  35. use app\common\model\OrderGoods;
  36. use app\common\model\OrderLog;
  37. use app\common\model\Presell;
  38. use app\common\model\PresellGoodsItem;
  39. use app\common\model\RechargeOrder;
  40. use app\common\model\SeckillGoodsItem;
  41. use app\common\model\SelffetchShop;
  42. use app\common\model\TeamFound;
  43. use app\common\model\TeamGoodsItem;
  44. use app\common\model\User;
  45. use app\common\service\ConfigService;
  46. use app\common\service\printer\YlyPrinterService;
  47. use app\shopapi\logic\TeamLogic;
  48. use think\facade\Db;
  49. use think\facade\Log;
  50. /**
  51. * 支付成功后处理订单状态
  52. * Class PayNotifyLogic
  53. * @package app\api\logic
  54. */
  55. class PayNotifyLogic extends BaseLogic
  56. {
  57. public static function handle($action, $orderSn, $extra = [])
  58. {
  59. Db::startTrans();
  60. try {
  61. outFileLog($action,'prepay','$action');
  62. outFileLog($orderSn,'prepay','$orderSn');
  63. self::$action($orderSn, $extra);
  64. Db::commit();
  65. return true;
  66. } catch (\Exception $e) {
  67. Db::rollback();
  68. Log::write($e->__toString(), 'PayNotifyLogic');
  69. self::setError($e->getMessage());
  70. return $e->getMessage();
  71. }
  72. }
  73. //下单回调 //调用回调方法统一处理 更新订单支付状态
  74. private static function order($orderSn, $extra = [])
  75. {
  76. $order = Order::with(['order_goods'])->where(['sn' => $orderSn])->findOrEmpty();
  77. outFileLog($order,'prepay','$order');
  78. // 汽泡足迹(异常不影响订单事务)
  79. try {
  80. event('Footprint', ['type' => FootprintEnum::ORDER_SETTLEMENT, 'user_id' => $order['user_id']]);
  81. } catch (\Throwable $e) {
  82. Log::write($e->__toString(), 'FootprintError');
  83. }
  84. //增加用户累计消费额度
  85. User::where(['id' => $order['user_id']])
  86. ->inc('total_order_amount', $order['order_amount'])
  87. ->inc('total_order_num')
  88. ->update();
  89. //赠送积分
  90. $open_award = ConfigService::get('award_integral', 'open_award', 0);
  91. if ($open_award == 1) {
  92. $award_event = ConfigService::get('award_integral', 'award_event', 0);
  93. $award_ratio = ConfigService::get('award_integral', 'award_ratio', 0);
  94. if ($award_ratio > 0) {
  95. $award_integral = floor($order['order_amount'] * ($award_ratio / 100));
  96. }
  97. }
  98. outFileLog($open_award,'prepay','$open_award');
  99. //更新订单状态
  100. $ret = Order::update([
  101. 'pay_status' => PayEnum::ISPAID,
  102. 'pay_time' => time(),
  103. // 自提变为待收货
  104. 'order_status' => $order['delivery_type'] == DeliveryEnum::SELF_DELIVERY ? OrderEnum::STATUS_WAIT_RECEIVE: OrderEnum::STATUS_WAIT_DELIVERY,
  105. 'transaction_id' => $extra['transaction_id'] ?? '',
  106. 'award_integral_event' => $award_event ?? 0,
  107. 'award_integral' => $award_integral ?? 0
  108. ], ['id' => $order['id']]);
  109. outFileLog($ret,'prepay','$ret');
  110. // 秒杀订单更新销售数据
  111. if ($order['order_type'] == OrderEnum::SECKILL_ORDER) {
  112. $orderGoods = OrderGoods::where('order_id', $order['id'])->findOrEmpty()->toArray();
  113. if (empty($orderGoods)) {
  114. return false;
  115. }
  116. $seckillGoodsItem = SeckillGoodsItem::where([
  117. 'seckill_id' => $order['seckill_id'],
  118. 'item_id' => $orderGoods['item_id'],
  119. ])->findOrEmpty();
  120. if ($seckillGoodsItem->isEmpty()) {
  121. return false;
  122. }
  123. $seckillGoodsItem->sales_amount += $orderGoods['total_pay_price'];
  124. $seckillGoodsItem->sales_volume += $orderGoods['goods_num'];
  125. $seckillGoodsItem->closing_order ++;
  126. $seckillGoodsItem->save();
  127. }
  128. // 拼团订单数据更新
  129. if ($order['order_type'] == OrderEnum::TEAM_ORDER) {
  130. if (empty($order['order_goods'])) {
  131. return false;
  132. }
  133. $teamId = (new TeamFound())->where(['id'=>$order['team_found_id']])->value('team_id');
  134. TeamGoodsItem::update([
  135. 'sales_amount' => ['inc', $order['order_amount']],
  136. 'sales_volume' => ['inc', $order['total_num']],
  137. 'closing_order' => ['inc', 1]
  138. ], ['team_id'=>$teamId, 'item_id'=>$order['order_goods'][0]['item_id']]);
  139. }
  140. // 预售订单数据更新
  141. if ($order['order_type'] == OrderEnum::PRESELL_ORDER) {
  142. PresellGoodsItem::update([
  143. 'sale_order' => Db::raw('sale_order+1'),
  144. 'sale_money' => Db::raw('sale_money+' . $order['order_amount']),
  145. 'sale_nums' => Db::raw('sale_nums+' . $order['total_num']),
  146. ], [
  147. [ 'item_id' , '=', $order['order_goods'][0]['item_id'] ],
  148. [ 'presell_id' , '=', $order['presell_id'] ],
  149. ]);
  150. Presell::update([
  151. 'sale_order' => Db::raw('sale_order+1'),
  152. 'sale_money' => Db::raw('sale_money+' . $order['order_amount']),
  153. 'sale_nums' => Db::raw('sale_nums+' . $order['total_num']),
  154. ], [ [ 'id' , '=', $order['presell_id'] ] ]);
  155. }
  156. // 生成分销订单
  157. DistributionOrderGoodsLogic::add($order['id']);
  158. // 更新分销商等级
  159. DistributionLevelLogic::updateDistributionLevel($order['user_id']);
  160. //下架库存为零的商品
  161. // $goods_ids = OrderGoods::where('order_id',$order['id'])->column('goods_id');
  162. // Goods::update(['status'=>0],['id'=>$goods_ids,'total_stock'=>0]);
  163. //订单日志
  164. (new OrderLog())->record([
  165. 'type' => OrderLogEnum::TYPE_USER,
  166. 'channel' => OrderLogEnum::USER_PAID_ORDER,
  167. 'order_id' => $order['id'],
  168. 'operator_id' => $order['user_id']
  169. ]);
  170. // 如果是拼团订单
  171. if ($order['order_type'] == OrderEnum::TEAM_ORDER) {
  172. TeamLogic::checkTeamSuccess($order['team_found_id']);
  173. }
  174. // // 消息通知 - 通知买家
  175. // event('Notice', [
  176. // 'scene_id' => NoticeEnum::ORDER_PAY_NOTICE,
  177. // 'params' => [
  178. // 'user_id' => $order['user_id'],
  179. // 'order_id' => $order['id'],
  180. // 'mobile' => $order['address']->mobile,
  181. // ]
  182. // ]);
  183. //
  184. // // 消息通知 - 通知卖家
  185. // $mobile = ConfigService::get('shop', 'mall_contact_mobile', '');
  186. // event('Notice', [
  187. // 'scene_id' => NoticeEnum::SELLER_ORDER_PAY_NOTICE,
  188. // 'params' => [
  189. // 'mobile' => $mobile,
  190. // 'order_id' => $order['id'],
  191. // ]
  192. // ]);
  193. // //更新虚拟订单
  194. try{
  195. outFileLog(1,'prepay','$ret1');
  196. GoodsVirtualLogic::afterPayVirtualDelivery($order['id']);
  197. outFileLog(2,'prepay','$ret2');
  198. } catch (\Throwable $e) {
  199. Log::write($e->__toString(), 'FootprintError');
  200. }
  201. //更新用户等级
  202. UserLogic::updateLevel($order['user_id']);
  203. //
  204. // // 自动小票打印
  205. // self::orderPrint($order['id']);
  206. outFileLog(3,'prepay','$ret3');
  207. }
  208. /**
  209. * @notes 充值成功回调
  210. * @param $orderSn
  211. * @param array $extra
  212. * @author Tab
  213. * @date 2021/8/11 14:43
  214. */
  215. public static function recharge($orderSn, $extra = [])
  216. {
  217. $order = RechargeOrder::where('sn', $orderSn)->findOrEmpty();
  218. // 增加用户累计充值金额及用户余额
  219. $user = User::findOrEmpty($order->user_id);
  220. $user->total_recharge_amount = $user->total_recharge_amount + $order->order_amount;
  221. $user->user_money = $user->user_money + $order->order_amount;
  222. $user->save();
  223. // 记录账户流水
  224. AccountLogLogic::add($order->user_id, AccountLogEnum::BNW_INC_RECHARGE, AccountLogEnum::INC, $order->order_amount, $order->sn, '用户充值');
  225. // 更新充值订单状态
  226. $order->transaction_id = $extra['transaction_id'];
  227. $order->pay_status = PayEnum::ISPAID;
  228. $order->pay_time = time();
  229. $order->save();
  230. // 充值奖励
  231. foreach($order->award as $item) {
  232. if(isset($item['give_money']) && $item['give_money'] > 0) {
  233. // 充值送余额
  234. self::awardMoney($order, $item['give_money']);
  235. }
  236. }
  237. }
  238. /**
  239. * @notes 充值送余额
  240. * @param $userId
  241. * @param $giveMoney
  242. * @author Tab
  243. * @date 2021/8/11 14:35
  244. */
  245. public static function awardMoney($order, $giveMoney)
  246. {
  247. // 充值送余额
  248. $user = User::findOrEmpty($order->user_id);
  249. $user->user_money = $user->user_money + $giveMoney;
  250. $user->save();
  251. // 记录账户流水
  252. AccountLogLogic::add($order->user_id, AccountLogEnum::BNW_INC_RECHARGE_GIVE, AccountLogEnum::INC, $giveMoney, $order->sn, '充值赠送');
  253. }
  254. /**
  255. * @notes 积分商城订单
  256. * @param $order_sn
  257. * @param array $extra
  258. * @author 段誉
  259. * @date 2022/3/31 12:13
  260. */
  261. private static function integral($order_sn, $extra = [])
  262. {
  263. $order = IntegralOrder::where(['sn' => $order_sn])->findOrEmpty();
  264. $goods = $order['goods_snap'];
  265. // 更新订单状态
  266. $data = [
  267. 'order_status' => IntegralOrderEnum::ORDER_STATUS_DELIVERY,
  268. 'pay_status' => PayEnum::ISPAID,
  269. 'pay_time' => time(),
  270. ];
  271. // 红包类型 或者 无需物流 支付完即订单完成
  272. if ($goods['type'] == IntegralGoodsEnum::TYPE_BALANCE || $goods['delivery_way'] == IntegralGoodsEnum::DELIVERY_NO_EXPRESS) {
  273. $data['order_status'] = IntegralOrderEnum::ORDER_STATUS_COMPLETE;
  274. $data['confirm_time'] = time();
  275. }
  276. // 第三方流水号
  277. if (isset($extra['transaction_id'])) {
  278. $data['transaction_id'] = $extra['transaction_id'];
  279. }
  280. IntegralOrder::update($data, ['id' => $order['id']]);
  281. // 更新商品销量
  282. IntegralGoods::where([['id', '=', $goods['id']], ['stock', '>=', $order['total_num']]])
  283. ->dec('stock', $order['total_num'])
  284. ->inc('sales', $order['total_num'])
  285. ->update();
  286. // 红包类型,直接增加余额
  287. if ($goods['type'] == IntegralGoodsEnum::TYPE_BALANCE) {
  288. $reward = round($goods['balance'] * $order['total_num'], 2);
  289. User::where(['id' => $order['user_id']])
  290. ->inc('user_money', $reward)
  291. ->update();
  292. AccountLogLogic::add(
  293. $order['user_id'],
  294. AccountLogEnum::BNW_INC_INTEGRAL_ORDER,
  295. AccountLogEnum::INC, $reward, $order['sn']
  296. );
  297. }
  298. }
  299. /**
  300. * @notes 小票打印
  301. * @param $orderId
  302. * @author Tab
  303. * @date 2021/11/17 9:53
  304. */
  305. public static function orderPrint($orderId)
  306. {
  307. try {
  308. $order = self::getOrderInfo($orderId);
  309. (new YlyPrinterService())->startPrint($order, PrinterEnum::ORDER_PAY);
  310. } catch (\Exception $e) {
  311. self::handleCatch($e);
  312. }
  313. }
  314. public static function getOrderInfo($orderId)
  315. {
  316. $field = [
  317. 'id',
  318. 'sn',
  319. 'order_type',
  320. 'pay_way',
  321. 'delivery_type',
  322. 'goods_price',
  323. 'order_amount',
  324. 'discount_amount',
  325. 'express_price',
  326. 'user_remark',
  327. 'pickup_code',
  328. 'address',
  329. 'selffetch_shop_id',
  330. 'create_time',
  331. 'pickup_code',
  332. 'change_price',
  333. 'member_amount',
  334. ];
  335. $order = Order::field($field)->with(['orderGoods' => function($query) {
  336. $query->field(['goods_num', 'order_id', 'goods_price', 'goods_snap', 'original_price' ]);
  337. }])
  338. ->append(['delivery_address', 'pay_way_desc', 'delivery_type_desc'])
  339. ->findOrEmpty($orderId);
  340. if ($order->isEmpty()) {
  341. throw new \Exception("订单不存在");
  342. }
  343. // 门店自提
  344. if ($order->delivery_type == DeliveryEnum::SELF_DELIVERY) {
  345. $field = [
  346. 'id',
  347. 'name',
  348. 'contact',
  349. 'province',
  350. 'city',
  351. 'district',
  352. 'address',
  353. ];
  354. $selffetchShop = SelffetchShop::field($field)
  355. ->append(['detailed_address'])
  356. ->findOrEmpty($order->selffetch_shop_id);
  357. $order->selffetch_shop = $selffetchShop;
  358. }
  359. return $order->toArray();
  360. }
  361. /**
  362. * @notes 处理易联云异常
  363. * @param $e
  364. * @return false
  365. * @author Tab
  366. * @date 2021/11/17 10:01
  367. */
  368. public static function handleCatch($e)
  369. {
  370. $msg = json_decode($e->getMessage(),true);
  371. if(18 === $e->getCode()){
  372. //access_token过期,清除缓存中的access_token
  373. (new YlyPrinterCache())->deleteTag();
  374. };
  375. if($msg && isset($msg['error'])){
  376. Log::write('小票打印出错1:易联云'.$msg['error_description']);
  377. }
  378. Log::write('小票打印出错2:'.$e->getMessage());
  379. }
  380. }