CronLogic.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  1. <?php
  2. namespace App\Http\Logic\Cron;
  3. use App\Exceptions\CommonException;
  4. use App\Http\Bean\Cron\logic\HandleOrderParamBean;
  5. use App\Http\Bean\Util\Jutuike\GetOrderListParamBean;
  6. use App\Http\Bean\Util\Meituan\OrderListParamBean;
  7. use App\Http\Bean\Util\Pdd\Ddk\OrderListIncrementGetParamBean;
  8. use App\Http\Enum\ErrorEnum;
  9. use App\Http\Enum\OrderStatusEnum;
  10. use App\Http\Enum\PlatformTypeEnum;
  11. use App\Http\Logic\BaseLogic;
  12. use App\Http\Logic\Order\OrderLogic;
  13. use App\Http\Utils\BaseUtil;
  14. use App\Http\Utils\HeiMaUtil;
  15. use App\Http\Utils\Jutuike\JutuikeUtil;
  16. use App\Http\Utils\LoggerFactoryUtil;
  17. use App\Http\Utils\Meituan\MeituanLianmengUtil;
  18. use App\Http\Utils\Meituan\MeituanLianmengUtilV1;
  19. use App\Http\Utils\Pdd\DuoDuoKeUtil;
  20. use App\Http\Utils\WechatAccountUtil;
  21. use App\Models\CategoryModel;
  22. use App\Models\TaobaoPidModel;
  23. use App\Models\UserCashModel;
  24. use App\Models\UserFinanceModel;
  25. use App\Models\UserModel;
  26. use App\Models\UserOrderCommissionModel;
  27. use App\Models\UserOrderModel;
  28. use App\Models\WechatAccountModel;
  29. use EasyWeChat\Factory;
  30. use Illuminate\Support\Facades\DB;
  31. class CronLogic extends BaseLogic
  32. {
  33. /**
  34. * 获取美团订单
  35. */
  36. public static function meituanOrderslogic()
  37. {
  38. $params = request()->all();
  39. $arr = [
  40. "appkey"=>env("MEITUAN_LIANMENG_KEY"),
  41. "type"=>$params["order_type"],
  42. "startTime"=>time()-$params["minute"]*60,
  43. "endTime"=>time(),
  44. // "startTime"=>strtotime("2021-09-22 11:25:00"),
  45. // "endTime"=>time(),
  46. "page"=>1,
  47. "limit"=>100,
  48. "queryTimeType"=>2,
  49. ];
  50. $instance = new LoggerFactoryUtil(CronLogic::class);
  51. $instance->info("获取订单数据开始");
  52. $bean = new OrderListParamBean($arr);
  53. $res = MeituanLianmengUtilV1::orderList($bean);
  54. // dd($res);
  55. $instance->info("美团返回数据:".json_encode($res));
  56. $instance->info("订单数量:".$res["total"]);
  57. if($res){
  58. //存在数据,写入订单数据表
  59. if($res["total"]){
  60. $instance->info("订单数据:".json_encode($res));
  61. BaseUtil::sendBaoJing("","获取到订单数量:".$res["total"],"定时获取美团订单");
  62. //处理订单
  63. self::checkOrder($res["dataList"],$params["order_type"]);
  64. //判断订单数量是否大于分页
  65. $pageNum = ceil($res["total"]/100)-1;
  66. if($pageNum){
  67. for ($i=1;$i<=$pageNum;$i++){
  68. $arr["page"]++;
  69. $bean = new OrderListParamBean($arr);
  70. $res = MeituanLianmengUtil::orderList($bean);
  71. if ($res) {
  72. //存在数据,写入订单数据表
  73. if ($res["total"]) {
  74. self::checkOrder($res["dataList"],$params["order_type"]);
  75. }
  76. }
  77. }
  78. }
  79. }
  80. }
  81. }
  82. /**
  83. * 处理订单
  84. */
  85. protected static function checkOrder($orders,$orderType)
  86. {
  87. foreach ($orders as $data) {
  88. switch ($data["status"]) {
  89. case 1://已付款
  90. $orderStatus = OrderStatusEnum::ALREADY_PAY;
  91. break;
  92. case 8://已收货
  93. $orderStatus = OrderStatusEnum::ALREADY_RECEIVE;
  94. break;
  95. case 9://已退款或风控
  96. $orderStatus = OrderStatusEnum::ALREADY_REFUND;
  97. break;
  98. }
  99. $params = [
  100. "spreadSonType" => 0,//订单子类型
  101. "orderNumber" => $data["orderid"],//订单编号
  102. "payTime" => date("Y-m-d H:i:s", $data["paytime"]),//支付时间
  103. "orderPrice" => $data["payprice"] * 100,//订单金额
  104. "orderCommission" => $data["profit"] * 100,//订单佣金
  105. "orderTitle" => $data["smstitle"],//订单标题
  106. "orderRefundPrice" => isset($data["refundprice"]) ? $data["refundprice"] * 100 : 0,//退款金额
  107. "orderRefundTime" => isset($data["refundtime"]) ? date("Y-m-d H:i:s", $data["refundtime"]) : null,//退款时间
  108. "orderRefundCommission" => isset($data["refundprofit"]) ? $data["refundprofit"] : 0,//退款佣金
  109. "orderStatus" => $orderStatus,//订单状态
  110. "orderCouponPrice" => 0,//订单优惠
  111. "productImgUrl" => "https://pic.rmb.bdstatic.com/bjh/f049242a789a22fb1a412bb6418c52e2.jpeg",//商品图片
  112. "spreadType"=>PlatformTypeEnum::PLATFORM_MEITUAN,//订单类型
  113. "userSpreadId"=>$data["sid"],//用户推广位
  114. "platformSpreadId"=>$data["sid"],//平台推广位
  115. "createdAt"=>date("Y-m-d H:i:s", $data["paytime"])
  116. ];
  117. $bean = new HandleOrderParamBean($params);
  118. OrderLogic::handleOrderLogic($bean);
  119. }
  120. }
  121. /**
  122. * 聚推客订单逻辑
  123. */
  124. public static function jutuikeOrdersLogic()
  125. {
  126. $params = request()->all();
  127. $startTime = date("Y-m-d H:i:s",time()-600);
  128. $endTime = date("Y-m-d H:i:s");
  129. if(isset($params["start_time"])){
  130. $startTime = $params["start_time"];
  131. }
  132. if (isset($params["end_time"])){
  133. $endTime= $params["end_time"];
  134. }
  135. $page = 1;
  136. $params = [
  137. "start_time"=>$startTime,
  138. "end_time"=>$endTime,
  139. "query_type"=>2,
  140. "page"=>$page,
  141. "pageSize"=>100
  142. ];
  143. $bean = new GetOrderListParamBean($params);
  144. $data = JutuikeUtil::getOrderList($bean);
  145. $instance = new LoggerFactoryUtil(CronLogic::class);
  146. $instance->info("上游返回数据:".json_encode($data));
  147. if($data["code"]!=1){
  148. //上游错误
  149. return;
  150. }
  151. //判断是否存在订单
  152. $orderLists = $data["data"]["data"];
  153. if(count($orderLists)){
  154. BaseUtil::sendBaoJing("","获取到订单数量:".count($orderLists),"定时获取聚推客订单");
  155. }
  156. foreach ($orderLists as $orderList){
  157. self::handleOrderLogic($orderList);
  158. }
  159. }
  160. public static function handleOrderLogic($orderList)
  161. {
  162. //判断订单状态
  163. switch ($orderList["status"]){
  164. case 0://未付款
  165. $orderStatus = OrderStatusEnum::PRE_PAY;
  166. break;
  167. case 1://已付款
  168. $orderStatus = OrderStatusEnum::ALREADY_PAY;
  169. break;
  170. case 2://待结算
  171. $orderStatus = OrderStatusEnum::ALREADY_RECEIVE;
  172. break;
  173. case 3://已结算
  174. $orderStatus = OrderStatusEnum::ALREADY_FINISH;
  175. break;
  176. case 4://无效订单
  177. $orderStatus = OrderStatusEnum::ALREADY_CANCEL;
  178. break;
  179. }
  180. //获取活动图片
  181. $actImgUrl = CategoryModel::query()
  182. ->where("platform_type",PlatformTypeEnum::PLATFORM_JUTUIKE)
  183. ->where("activity_id",$orderList["act_id"])
  184. ->value("category_img_url");
  185. $params = [
  186. "spreadSonType" => 0,//订单子类型
  187. "orderNumber" => $orderList["order_sn"],//订单编号
  188. "payTime" => $orderList["pay_time"],//支付时间
  189. "orderPrice" => $orderList["order_price"] * 100,//订单金额
  190. "orderCommission" => $orderList["jtk_share_fee"] * 100,//订单佣金
  191. "orderTitle" => $orderList["order_title"],//订单标题
  192. "orderRefundPrice" => 0,//退款金额
  193. "orderRefundTime" => null,//退款时间
  194. "orderRefundCommission" => 0,//退款佣金
  195. "orderStatus" => $orderStatus,//订单状态
  196. "orderCouponPrice" => 0,//订单优惠
  197. "productImgUrl" => $actImgUrl,//商品图片
  198. "spreadType"=>PlatformTypeEnum::PLATFORM_JUTUIKE,//订单类型
  199. "userSpreadId"=>$orderList["sid"],//用户推广位
  200. "platformSpreadId"=>$orderList["sid"],//平台推广位
  201. "createdAt"=>$orderList["create_time"],//订单创建时间
  202. ];
  203. $bean = new HandleOrderParamBean($params);
  204. OrderLogic::handleOrderLogic($bean);
  205. }
  206. /**
  207. * 定时获取淘宝订单逻辑
  208. */
  209. public static function taobaoOrdersLogic()
  210. {
  211. //获取黑马授权账号
  212. $heimaDatas = $data = TaobaoPidModel::query()
  213. ->select([DB::raw("any_value(heima_app_key) as heima_app_key"),DB::raw("any_value(heima_app_secret) as heima_app_secret"),"heima_sid"])
  214. ->groupBy("heima_sid")
  215. ->get();
  216. $instance = new LoggerFactoryUtil(CronLogic::class);
  217. foreach ($heimaDatas as $heimaData){
  218. //查询黑马账号下的订单
  219. $orders = HeiMaUtil::getOrderList($heimaData);
  220. if(!isset($orders["publisher_order_dto"])){
  221. break;
  222. }
  223. $orders = $orders["publisher_order_dto"];
  224. if($orders){
  225. BaseUtil::sendBaoJing("","获取到淘宝订单:".count($orders),"定时获取黑马淘客订单");
  226. }
  227. $instance->info("黑马淘客订单:".json_encode($orders));
  228. try{
  229. foreach ($orders as $orderList){
  230. switch ($orderList["tk_status"]){
  231. case 3:
  232. //订单结算
  233. $orderStatus = OrderStatusEnum::ALREADY_RECEIVE;
  234. break;
  235. case 12:
  236. //订单付款
  237. $orderStatus = OrderStatusEnum::ALREADY_PAY;
  238. break;
  239. case 13:
  240. //订单失效
  241. $orderStatus = OrderStatusEnum::ALREADY_CANCEL;
  242. break;
  243. case 14:
  244. //订单成功
  245. $orderStatus = OrderStatusEnum::ALREADY_PAY;
  246. break;
  247. }
  248. $params = [
  249. "spreadSonType" => 0,//订单子类型
  250. "orderNumber" => $orderList["trade_id"],//订单编号
  251. "payTime" => $orderList["tb_paid_time"],//支付时间
  252. "orderPrice" => $orderList["alipay_total_price"]*100,//订单金额
  253. "orderCommission" => $orderList["pub_share_pre_fee"]*100,//订单佣金
  254. "orderTitle" => $orderList["item_title"],//订单标题
  255. "orderRefundPrice" => 0,//退款金额
  256. "orderRefundTime" => null,//退款时间
  257. "orderRefundCommission" => 0,//退款佣金
  258. "orderStatus" => $orderStatus,//订单状态
  259. "orderCouponPrice" => 0,//订单优惠
  260. "productImgUrl" => $orderList["item_img"]??"",//商品图片
  261. "spreadType"=>PlatformTypeEnum::PLATFORM_TAOBAO,//订单类型
  262. "userSpreadId"=>$orderList["adzone_id"],//用户推广位
  263. "platformSpreadId"=>$orderList["adzone_id"],//平台推广位
  264. "createdAt"=>$orderList["tk_create_time"],//订单创建时间
  265. ];
  266. $bean = new HandleOrderParamBean($params);
  267. OrderLogic::handleOrderLogic($bean);
  268. }
  269. }catch (\Throwable $exception){
  270. BaseUtil::sendBaoJing("","淘宝订单更新失败:".$exception->getMessage(),"定时获取黑马淘客订单");
  271. }
  272. }
  273. }
  274. /**
  275. * 获取拼多多订单逻辑
  276. */
  277. public static function pddOrdersLogic()
  278. {
  279. $params = [
  280. "startUpdateTime"=>time()-600,
  281. "endUpdateTime"=>time()
  282. ];
  283. $bean = new OrderListIncrementGetParamBean($params);
  284. $res = DuoDuoKeUtil::orderListIncrementGet($bean);
  285. $instance = new LoggerFactoryUtil(CronLogic::class);
  286. $instance->info("上游返回信息:".json_encode($res));
  287. if (isset($res["error_response"])){
  288. return;
  289. }
  290. if($res["order_list_get_response"]["total_count"]){
  291. BaseUtil::sendBaoJing("","获取到订单数量:".$res["order_list_get_response"]["total_count"],"定时获取拼多多订单");
  292. }
  293. //获取数据
  294. $datas = $res["order_list_get_response"]["order_list"];
  295. foreach ($datas as $orderList){
  296. switch ($orderList["order_status"]){
  297. case 0:
  298. //已支付
  299. $orderStatus = OrderStatusEnum::ALREADY_PAY;
  300. break;
  301. case 1:
  302. //已成团
  303. $orderStatus = OrderStatusEnum::ALREADY_PAY;
  304. break;
  305. case 2:
  306. //确认收货
  307. $orderStatus = OrderStatusEnum::ALREADY_RECEIVE;
  308. break;
  309. case 3:
  310. //审核成功
  311. $orderStatus = OrderStatusEnum::ALREADY_RECEIVE;
  312. break;
  313. case 4:
  314. //审核失败(不可提现)
  315. $orderStatus = OrderStatusEnum::ALREADY_CANCEL;
  316. break;
  317. case 5:
  318. //已经结算
  319. $orderStatus = OrderStatusEnum::ALREADY_RECEIVE;
  320. break;
  321. case 10:
  322. //已处罚
  323. $orderStatus = OrderStatusEnum::ALREADY_CANCEL;
  324. break;
  325. }
  326. $params = [
  327. "spreadSonType" => 0,//订单子类型
  328. "orderNumber" => $orderList["order_sn"],//订单编号
  329. "payTime" => date("Y-m-d H:i:s",$orderList["order_pay_time"]),//支付时间
  330. "orderPrice" => $orderList["order_amount"],//订单金额
  331. "orderCommission" => $orderList["promotion_amount"],//订单佣金
  332. "orderTitle" => $orderList["goods_name"],//订单标题
  333. "orderRefundPrice" => 0,//退款金额
  334. "orderRefundTime" => null,//退款时间
  335. "orderRefundCommission" => 0,//退款佣金
  336. "orderStatus" => $orderStatus,//订单状态
  337. "orderCouponPrice" => 0,//订单优惠
  338. "productImgUrl" => "https://pic.rmb.bdstatic.com/bjh/6d9fb4a81eb5fc933da8949854c4fab2.jpeg",//商品图片
  339. "spreadType"=>PlatformTypeEnum::PLATFORM_PINGDUODUO,//订单类型
  340. "userSpreadId"=>$orderList["p_id"],//用户推广位
  341. "platformSpreadId"=>$orderList["p_id"],//平台推广位
  342. "createdAt"=>date("Y-m-d H:i:s",$orderList["order_create_time"]),//订单创建时间
  343. ];
  344. $bean = new HandleOrderParamBean($params);
  345. OrderLogic::handleOrderLogic($bean);
  346. }
  347. }
  348. /**
  349. * 发送用户下单模版
  350. */
  351. public static function sendOrderTemplateLogic()
  352. {
  353. $instance = new LoggerFactoryUtil(CronLogic::class);
  354. //1.新增粉丝通知
  355. $userFans = UserModel::query()
  356. ->where("invite_user_id","<>",0)
  357. ->where("user_notify_status",0)
  358. ->get();
  359. foreach ($userFans as $userFan){
  360. //获取推荐人
  361. $inviteUser = UserModel::findById($userFan->invite_user_id);
  362. if($inviteUser){
  363. try{
  364. //获取公众号实例
  365. $app = WechatAccountUtil::getAppByID($userFan->wechat_account_id);
  366. $data = [
  367. 'touser' => $inviteUser->user_open_id,
  368. 'template_id' => env("WECHAT_FANS_TEMPLATE_URL"),
  369. 'url' => env("WECHAT_FANS_URL"),
  370. 'data' => [
  371. 'first' => "亲,您有新的粉丝",
  372. 'keyword1' => $userFan->user_nickname,
  373. 'keyword2' => $userFan->id+100000,
  374. "remark"=>"粉丝将提供分享佣金,粉丝越多比例越高哦,点击查看详情"
  375. ],
  376. ];
  377. $res = $app->template_message->send($data);
  378. $instance->info("粉丝通知微信返回结果:".json_encode($res));
  379. }catch (\Throwable $exception){
  380. $instance->info("粉丝通知结果异常:".$exception->getMessage());
  381. }
  382. UserModel::query()->where("id",$userFan->id)->update(
  383. [
  384. "user_notify_status"=>1
  385. ]
  386. );
  387. }
  388. }
  389. //2.获取自购已支付且未通知进行模版推送
  390. $orders = UserOrderCommissionModel::query()
  391. ->where("commission_status",0)
  392. ->where("order_commission",">",0)
  393. ->where("user_id","<>",0)
  394. ->where("order_notify_status",0)
  395. ->limit(10)
  396. ->get();
  397. foreach ($orders as $order){
  398. //判断是否自购订单
  399. if($order->user_provider_id){
  400. //反佣订单
  401. $user = UserModel::findById($order->user_id);
  402. if($user){
  403. try{
  404. //获取公众号实例
  405. $app = WechatAccountUtil::getAppByID($user->wechat_account_id);
  406. $tmpOrder = UserOrderModel::query()->where("order_number",$order->order_number)->first();
  407. $privideUser = UserModel::findById($order->user_provider_id);
  408. $data = [
  409. 'touser' => $user->user_open_id,
  410. 'template_id' => env("WECHAT_FANS_ORDER_TEMPLATE_URL"),
  411. 'url' => env("WECHAT_FANS_ORDER_URL"),
  412. 'data' => [
  413. 'first' => "粉丝下单成功通知",
  414. 'keyword1' => $order->order_number,
  415. 'keyword2' => $tmpOrder->product_name,
  416. 'keyword3' => $order->created_at,
  417. 'keyword4' => round($tmpOrder->order_price/100,2)."元",
  418. 'keyword5' => $privideUser->user_nickname,
  419. "remark"=>"您的粉丝有新的订单,分享佣金已产生,3天后结算到您账户中,点击详情跳转粉丝订单"
  420. ],
  421. ];
  422. $res = $app->template_message->send($data);
  423. $instance->info("粉丝下单微信返回结果:".json_encode($res));
  424. }catch (\Throwable $exception){
  425. $instance->info("粉丝下单通知结果异常:".$exception->getMessage());
  426. }
  427. }
  428. }else{
  429. $user = UserModel::findById($order->user_id);
  430. if($user){
  431. try{
  432. //获取公众号实例
  433. $app = WechatAccountUtil::getAppByID($user->wechat_account_id);
  434. $tmpOrder = UserOrderModel::query()->where("order_number",$order->order_number)->first();
  435. $data = [
  436. 'touser' => $user->user_open_id,
  437. 'template_id' => env("WECHAT_ORDER_TEMPLATE_URL"),
  438. 'url' => env("WECHAT_ORDER_URL"),
  439. 'data' => [
  440. 'first' => "下单成功通知",
  441. 'keyword1' => $order->created_at,
  442. 'keyword2' => $tmpOrder->product_name,
  443. 'keyword3' => $order->order_number,
  444. "remark"=>"感谢您的使用,每月20号结算上个月的佣金,将会结算到您的账户中点击详情跳转我的订单"
  445. ],
  446. ];
  447. $res = $app->template_message->send($data);
  448. $instance->info("自购下单微信返回结果:".json_encode($res));
  449. }catch (\Throwable $exception){
  450. $instance->info("自购下单通知结果异常:".$exception->getMessage());
  451. }
  452. }
  453. }
  454. UserOrderCommissionModel::query()->where("id",$order->id)->update(
  455. [
  456. "order_notify_status"=>1
  457. ]
  458. );
  459. }
  460. //3.获取上月已结算订单,并通知
  461. $completeOrders = UserOrderCommissionModel::query()
  462. ->where("commission_status",1)
  463. ->where("order_commission",">",0)
  464. ->where("user_id","<>",0)
  465. ->where("order_complete_notify_status",0)
  466. ->groupBy("user_id")
  467. ->select(["user_id",DB::Raw("sum(order_commission) as total_order_commission"),DB::Raw("GROUP_CONCAT(id) as ids")])
  468. ->get();
  469. foreach ($completeOrders as $order){
  470. $user = UserModel::findById($order->user_id);
  471. if($user){
  472. try{
  473. //获取公众号实例
  474. $app = WechatAccountUtil::getAppByID($user->wechat_account_id);
  475. $data = [
  476. 'touser' => $user->user_open_id,
  477. 'template_id' => env("WECHAT_COMPLETE_ORDER_TEMPLATE_URL"),
  478. 'url' => env("WECHAT_BALANCE_URL"),
  479. 'data' => [
  480. 'first' => "上月订单佣金已结算完成",
  481. 'keyword1' => round($order["total_order_commission"]/100,2)."元",
  482. 'keyword2' => round($order["total_order_commission"]/100,2)."元",
  483. 'keyword3' => date("Y-m-d H:i:s"),
  484. "remark"=>"订单佣金已结算完成,可以立即提现哦!零钱秒到账"
  485. ],
  486. ];
  487. $res = $app->template_message->send($data);
  488. $instance->info("订单结算微信返回结果:".json_encode($res));
  489. }catch (\Throwable $exception){
  490. $instance->info("订单结算通知结果异常:".$exception->getMessage());
  491. }
  492. }
  493. UserOrderCommissionModel::query()->whereIn("id",explode(",",$order["ids"]))->update(
  494. [
  495. "order_complete_notify_status"=>1
  496. ]
  497. );
  498. }
  499. }
  500. /**
  501. * 结算佣金逻辑(每月的20号18点结算上个月的佣金)
  502. */
  503. public static function settlementOrderCommissionLogic()
  504. {
  505. //获取上个月的开始结束时间
  506. $startTime = date("Y-m-d",strtotime("-1 month"))." 00:00:00";
  507. $endTime = date("Y-m-")."01 00:00:00";
  508. //获取上个月未结算的订单且未退款
  509. //这里有个bug,chunk里面自己改自己会导致有的数据娶不到
  510. UserOrderCommissionModel::query()
  511. ->where("commission_status",0)
  512. ->where("order_commission",">",0)
  513. ->where("user_id","<>",0)
  514. ->where("order_complete_notify_status",0)
  515. ->where("created_at","<",$endTime)
  516. ->chunk(300,function ($orderCommissions){
  517. foreach ($orderCommissions as $orderCommission){
  518. try{
  519. //开启事务
  520. DB::beginTransaction();
  521. //1.修改用户的余额
  522. $user = UserModel::query()->lock(true)->find($orderCommission["user_id"]);
  523. if($user){
  524. $userRes = UserModel::query()
  525. ->where("id",$orderCommission["user_id"])
  526. ->increment("user_balance",$orderCommission["order_commission"]);
  527. if(!$userRes){
  528. DB::rollBack();
  529. throw new CommonException(ErrorEnum::ERROR_SYSTEM);
  530. }
  531. //2.添加用户流水记录
  532. $logRes = UserFinanceModel::query()
  533. ->insert(
  534. [
  535. "user_id"=>$orderCommission["id"],
  536. "order_number"=>$orderCommission["order_number"],
  537. "user_before_balance"=>$user["user_balance"],
  538. "user_after_balance"=>$orderCommission["order_commission"]+$user["user_balance"],
  539. "finance_balance"=>$orderCommission["order_commission"],
  540. "finance_remark"=>"订单佣金结算",
  541. "finance_type"=>1,
  542. "finance_number"=>uniqid("fbt-"),
  543. "created_at"=>date("Y-m-d H:i:s"),
  544. "updated_at"=>date("Y-m-d H:i:s"),
  545. "cash_status"=>1
  546. ]
  547. );
  548. if(!$logRes){
  549. DB::rollBack();
  550. throw new CommonException(ErrorEnum::ERROR_SYSTEM);
  551. }
  552. //3.修改佣金记录为已结算
  553. $commissionRes = UserOrderCommissionModel::query()
  554. ->where("id",$orderCommission["id"])
  555. ->update(
  556. [
  557. "commission_status"=>1,
  558. "updated_at"=>date("Y-m-d H:i:s")
  559. ]
  560. );
  561. if(!$commissionRes){
  562. DB::rollBack();
  563. throw new CommonException(ErrorEnum::ERROR_SYSTEM);
  564. }
  565. DB::commit();
  566. }
  567. }catch (\Throwable $exception){}
  568. }
  569. });
  570. }
  571. /**
  572. * 处理提现打款逻辑
  573. */
  574. public static function transferFinanceLogic()
  575. {
  576. $account = WechatAccountModel::query()
  577. ->where("wechat_app_code","fanbuting")
  578. ->first();
  579. $config = [
  580. "app_id"=>$account["wechat_app_id"],
  581. "mch_id"=>$account["account_mch_id"],
  582. "key"=>$account["account_key"],
  583. "cert_path"=>$account["account_cert_path"],
  584. "key_path"=>$account["account_key_path"]
  585. ];
  586. $app = Factory::payment($config);
  587. //获取已审核且未打款的提现记录
  588. $cashLogs = UserCashModel::query()
  589. ->where("check_status",2)
  590. ->where("cash_status",0)
  591. ->get();
  592. if(!$cashLogs){
  593. return ;
  594. }
  595. //将打款记录修改为执行中
  596. $logIds = [];
  597. foreach ($cashLogs as $cashLog){
  598. $logIds[] = $cashLog["id"];
  599. }
  600. UserCashModel::query()
  601. ->whereIn("id",$logIds)
  602. ->update(
  603. [
  604. "cash_status"=>1
  605. ]
  606. );
  607. foreach ($cashLogs as $cashLog){
  608. //1.获取用户的openId
  609. $user = UserModel::query()->find($cashLog["user_id"]);
  610. if($user){
  611. $res = $app->transfer->toBalance(
  612. [
  613. "partner_trade_no"=>$cashLog["cash_order_number"],
  614. "openid"=>$user["user_open_id"],
  615. "check_name"=>"NO_CHECK",//不校验姓名
  616. "re_user_name"=>"",//真实姓名
  617. "amount"=>$cashLog["cash_money"],
  618. "desc"=>"用户提现"
  619. ]
  620. );
  621. //判断是否支付成功
  622. if($res["return_code"]=="SUCCESS" && $res["result_code"]=="SUCCESS"){
  623. UserCashModel::query()
  624. ->where("id",$cashLog["id"])
  625. ->update(
  626. [
  627. "cash_status"=>2,
  628. "upstream_response"=>json_encode($res),
  629. "cash_receive_at"=>date("Y-m-d H:i:s")
  630. ]
  631. );
  632. $cash_status = 1;//打款成功
  633. }else{
  634. //打款失败
  635. UserCashModel::query()
  636. ->where("id",$cashLog["id"])
  637. ->update(
  638. [
  639. "cash_status"=>3,
  640. "upstream_response"=>json_encode($res)
  641. ]
  642. );
  643. $cash_status = 2;//打款失败
  644. }
  645. //修改提现流水的状态
  646. UserFinanceModel::query()->where("id",$cashLog["user_finance_id"])
  647. ->update(
  648. [
  649. "cash_status"=>$cash_status,
  650. "updated_at"=>date("Y-m-d H:i:s")
  651. ]
  652. );
  653. }
  654. }
  655. }
  656. /**
  657. * 打款失败退款逻辑
  658. */
  659. public static function callbackCashLogic()
  660. {
  661. //获取已审核且未打款的提现记录
  662. $cashLogs = UserCashModel::query()
  663. ->where("callback_status",0)
  664. ->where(function ($query){
  665. $query->where("check_status",3)
  666. ->orWhere("cash_status",3);
  667. })
  668. ->get();
  669. if(!$cashLogs){
  670. return;
  671. }
  672. foreach ($cashLogs as $cashLog){
  673. DB::beginTransaction();
  674. //获取用户
  675. $user = UserModel::query()->lock(true)->find($cashLog["user_id"]);
  676. //1.用户金额增加
  677. $userRes = UserModel::query()
  678. ->where("id",$user["user_id"])
  679. ->increment("user_balance",$cashLog["cash_money"]);
  680. if(!$userRes){
  681. DB::rollBack();
  682. break;
  683. }
  684. //2.添加流水记录
  685. $financeRes = UserFinanceModel::query()->insert(
  686. [
  687. "user_id"=>$cashLog["user_id"],
  688. "user_before_balance"=>$user["user_balance"],
  689. "user_after_balance"=>$user["user_balance"]+$cashLog["cash_money"],
  690. "finance_balance"=>$cashLog["cash_money"],
  691. "finance_remark"=>"提现失败退回,原提现记录ID为:".$cashLog["id"],
  692. "finance_type"=>1,
  693. "finance_number"=>BaseUtil::getOrderNumber(),
  694. "created_at"=>date("Y-m-d H:i:s"),
  695. "updated_at"=>date("Y-m-d H:i:s"),
  696. ]
  697. );
  698. if(!$financeRes){
  699. DB::rollBack();
  700. break;
  701. }
  702. //3.修改提现记录为退款成功
  703. $cashRes = UserCashModel::query()
  704. ->where("id",$cashLog["id"])
  705. ->update([
  706. "callback_status"=>1
  707. ]);
  708. if(!$cashRes){
  709. DB::rollBack();
  710. break;
  711. }
  712. DB::commit();
  713. }
  714. }
  715. }