DouYinService.php 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  1. <?php
  2. namespace app\api\service;
  3. use app\adminapi\logic\external\ExternalConsultationLogic;
  4. use app\api\logic\ServiceOrderLogic;
  5. use app\common\enum\PayEnum;
  6. use app\common\logic\PayNotifyLogic;
  7. use app\common\model\Config;
  8. use app\common\model\external\DouyinOrder;
  9. use app\common\model\external\DouyinRefundOrder;
  10. use app\common\model\external\DouyinUserAuth;
  11. use app\common\model\external\ExternalConsultation;
  12. use app\common\model\external\ExternalConsultationOrder;
  13. use app\common\model\external\ExternalPlatformGoods;
  14. use app\common\model\goods\Goods;
  15. use app\common\model\goods_category\GoodsCategory;
  16. use app\common\model\recharge\RechargeOrder;
  17. use app\common\model\user\User;
  18. use app\common\model\user\UserAuth;
  19. use app\common\model\works\ServiceWork;
  20. use app\common\service\ConfigService;
  21. use app\common\service\FileService;
  22. use GuzzleHttp\Client;
  23. use think\facade\Db;
  24. use think\facade\Log;
  25. class DouYinService
  26. {
  27. protected static int $terminal = \app\common\enum\user\UserTerminalEnum::DOUYIN;
  28. protected static int $external_platform_id = 6;
  29. protected CONST EXTERNAL_PLATFORM_ID = 6;
  30. // ********************************* 注册登录
  31. public static function register(array $params)
  32. {
  33. $userSn = User::createUserSn();
  34. $params['password'] = !empty($params['password'])?$params['password']:rand(100000,999999);
  35. $passwordSalt = \think\facade\Config::get('project.unique_identification');
  36. $password = create_password($params['password'], $passwordSalt);
  37. $avatar = ConfigService::get('default_image', 'user_avatar');
  38. $user = User::create([
  39. 'sn' => $userSn,
  40. 'avatar' => $avatar,
  41. 'nickname' => '用户' . $userSn,
  42. 'account' => $params['account'],
  43. 'mobile' => !empty($params['mobile'])?$params['mobile']:'',
  44. 'password' => $password,
  45. 'channel' => self::$terminal,
  46. 'user_type' => $params['user_type']??0,
  47. ]);
  48. return $user;
  49. }
  50. public static function phoneLogin(array $params)
  51. {
  52. try {
  53. $where = ['mobile' => $params['mobile']];
  54. $params['account'] = $params['mobile'];
  55. $user = User::where($where)->findOrEmpty();
  56. if ($user->isEmpty()) {
  57. //直接注册用户
  58. $params['channel'] = self::$terminal;
  59. $user = self::register($params);
  60. }
  61. //更新登录信息
  62. $user->login_time = time();
  63. $user->login_ip = request()->ip();
  64. $user->save();
  65. $userInfo = UserTokenService::setToken($user->id, self::$terminal);
  66. //返回登录信息
  67. $avatar = $user->avatar ?: Config::get('project.default_image.user_avatar');
  68. $avatar = FileService::getFileUrl($avatar);
  69. return [
  70. 'nickname' => $userInfo['nickname'],
  71. 'sn' => $userInfo['sn'],
  72. 'mobile' => $userInfo['mobile'],
  73. 'avatar' => $avatar,
  74. 'token' => $userInfo['token'],
  75. ];
  76. } catch (\Exception $e) {
  77. throw new \Exception($e->getMessage());
  78. }
  79. }
  80. public static function getDouyinUserByOpenId(array $openId)
  81. {
  82. try {
  83. $user = DouyinUserAuth::where('openid',$openId)->findOrEmpty();
  84. if ($user->isEmpty()) {
  85. //直接注册用户
  86. $params['channel'] = self::$terminal;
  87. $user = self::register($params);
  88. }
  89. //更新登录信息
  90. $user->login_time = time();
  91. $user->login_ip = request()->ip();
  92. $user->save();
  93. $userInfo = UserTokenService::setToken($user->id, self::$terminal);
  94. //返回登录信息
  95. $avatar = $user->avatar ?: Config::get('project.default_image.user_avatar');
  96. $avatar = FileService::getFileUrl($avatar);
  97. return [
  98. 'nickname' => $userInfo['nickname'],
  99. 'sn' => $userInfo['sn'],
  100. 'mobile' => $userInfo['mobile'],
  101. 'avatar' => $avatar,
  102. 'token' => $userInfo['token'],
  103. ];
  104. } catch (\Exception $e) {
  105. throw new \Exception($e->getMessage());
  106. }
  107. }
  108. // **************************** 商品管理 goods_category_id goods_id external_platform_id
  109. public static function addProduct($params)
  110. {
  111. $send_url = env('internal_api.api_url_host').'platf/dou_yin/addGoods';
  112. $res = http_request($send_url,http_build_query($params));
  113. Log::info('addProduct:'
  114. .'url:'.$send_url
  115. .'|data:'.json_encode($params,JSON_UNESCAPED_UNICODE)
  116. .'|res:'.json_encode([$res],JSON_UNESCAPED_UNICODE)
  117. );
  118. return $res?:[];
  119. }
  120. // ******************************** 订单业务
  121. public static function getOrderDetail($params)
  122. {
  123. //抖音订单信息/商品信息/预约信息(地址、时间、履约状态与信息)
  124. // $params['order_number'] user_id
  125. $order = DouyinOrder::with(['goods','serviceWork','douyinRefundOrder'])->where('order_number', $params['order_number'])->where('user_id', $params['user_id'])->findOrEmpty();
  126. if($order->isEmpty()){
  127. return [];
  128. }
  129. $orderInfo = $order->toArray();
  130. empty($orderInfo['goods']) && $orderInfo['goods'] = [];
  131. empty($orderInfo['serviceWork']) && $orderInfo['serviceWork'] = [];
  132. if($orderInfo['serviceWork'] && $orderInfo['serviceWork']['service_status'] == 3 && in_array($orderInfo['order_status'],[1,2])){
  133. $order->order_status = 4;
  134. $order->pay_status = 1;
  135. $order->save();
  136. }
  137. empty($orderInfo['douyinRefundOrder']) && $orderInfo['douyinRefundOrder'] = [];
  138. $orderInfo['book_info'] = json_decode($orderInfo['book_info']?:'{}',true);
  139. $rechargeOrder = RechargeOrder::where(['work_id'=>$orderInfo['work_id']?:0,'payment_type'=>2])->findOrEmpty();
  140. if($rechargeOrder->isEmpty()){
  141. $orderInfo['tail_order'] = [];
  142. }else{
  143. $orderInfo['tail_order'] = $rechargeOrder->toArray();
  144. // 尾款未支付时 展示尾单信息加入临时总金额用于展示
  145. if(isset($orderInfo['tail_order']['pay_status']) && $orderInfo['tail_order']['pay_status'] == 0){
  146. $orderInfo['total_amount'] += $orderInfo['tail_order']['order_amount'];
  147. }
  148. }
  149. $work_status = $orderInfo['serviceWork']['work_status']??0;
  150. $performance = [];
  151. // tmp
  152. switch ($work_status){
  153. case 0:
  154. $performance[] = ['status' => '待派单','title' => '待派单','time' => date('Y-m-d H:i:s',time())];
  155. break;
  156. case 1:
  157. case 2:
  158. case 3:
  159. $performance[] = ['status' => '待派单','title' => '待派单','time' => date('Y-m-d H:i:s',time())];
  160. $performance[] = ['status' => '已派单','title' => '已派单','time' => date('Y-m-d H:i:s',time())];
  161. break;
  162. case 4:
  163. case 5:
  164. case 6:
  165. $performance[] = ['status' => '待派单','title' => '待派单','time' => date('Y-m-d H:i:s',time())];
  166. $performance[] = ['status' => '已派单','title' => '已派单','time' => date('Y-m-d H:i:s',time())];
  167. $performance[] = ['status' => '服务中','title' => '服务中','time' => date('Y-m-d H:i:s',time())];
  168. break;
  169. case 7:
  170. case 8:
  171. $performance[] = ['status' => '待派单','title' => '待派单','time' => date('Y-m-d H:i:s',time())];
  172. $performance[] = ['status' => '已派单','title' => '已派单','time' => date('Y-m-d H:i:s',time())];
  173. $performance[] = ['status' => '服务中','title' => '服务中','time' => date('Y-m-d H:i:s',time())];
  174. $performance[] = ['status' => '已完结','title' => '已完结','time' => date('Y-m-d H:i:s',time())];
  175. break;
  176. }
  177. $orderInfo['performance'] = $performance;
  178. return $orderInfo;
  179. }
  180. public static function createOrder($params)
  181. {
  182. try {
  183. $goods_id = $params['goods_id']??0;
  184. $open_id = '_000o7ntqTR--_hCTBOBCSR_NJkyp_hiqlEK';
  185. $goods = Goods::where('id',$goods_id)->findOrEmpty();
  186. if($goods->isEmpty()){
  187. throw new \Exception('商品不存在!');
  188. }
  189. $goods = $goods->toArray();
  190. $platformGoods = ExternalPlatformGoods::where('goods_id', $goods_id)->where('external_platform_id', self::EXTERNAL_PLATFORM_ID)->findOrEmpty();
  191. if($platformGoods->isEmpty()){
  192. throw new \Exception('外部商品不存在!');
  193. }
  194. $platformGoods = $platformGoods->toArray();
  195. $quantity = $params['quantity']?:1;
  196. $appointment_time = strtotime($params['appointment_time']??date('Y-m-d H:i:s',time()));
  197. $bookStartTime = $appointment_time * 1000;
  198. $bookEndTime = ($appointment_time + (2 * 86400)) * 1000;
  199. $order_number = self::submitOrder([
  200. 'open_id'=>$open_id,
  201. 'goods_id'=>$goods_id,
  202. 'user_id'=>$params['user_id']??0,
  203. 'mobile'=>$params['user_info']['mobile']??'',
  204. 'quantity'=>$quantity
  205. ]);
  206. $data = [
  207. "total_amount" => $platformGoods['service_fee'] * $quantity * 100,
  208. "open_id" => $open_id,
  209. "out_order_no" => $order_number,
  210. "order_entry_schema" => ['path'=>'pages/order/detail','params'=>json_encode(['order_number'=>$order_number??0])],
  211. "cp_extra" => json_encode([
  212. "outShopId" => self::EXTERNAL_PLATFORM_ID,
  213. "skuId" => (string)$platformGoods['external_goods_sn'],
  214. "quantity" => $quantity,
  215. "user_id" => $params['user_id'],
  216. "user_address" => $params['user_address'],
  217. "lon" => $params['lon'],
  218. "lat" => $params['lat'],
  219. "appointment_time" => $params['appointment_time']
  220. ]),
  221. "goods_list" => [
  222. [
  223. "goods_id_type" => 1,
  224. "goods_id" => (string)$platformGoods['external_goods_sn'],
  225. "quantity" => 1
  226. ]
  227. ],
  228. "goods_book_info" => [
  229. "book_type" => 2,
  230. "cancel_policy" => 3,
  231. "cancel_advance_hour" => 5
  232. ],
  233. ];
  234. // 服务器向抖音发起创建订单
  235. $url = 'api/apps/trade/v2/order/create_order';
  236. $resData = self::toDyRequestUrl($url,$data);
  237. return $resData;
  238. } catch (\Exception $e) {
  239. throw new \Exception($e->getMessage());
  240. }
  241. }
  242. // 预下单接口 - 前端 首次/尾款
  243. public static function getPluginCreateOrderData($goods_id, $quantity, $douyinOrderId,$params)
  244. {
  245. try {
  246. $goods = Goods::where('id',$goods_id)->findOrEmpty();
  247. if($goods->isEmpty()){
  248. throw new \Exception('商品不存在!');
  249. }
  250. $goods = $goods->toArray();
  251. $platformGoods = ExternalPlatformGoods::where('goods_id', $goods_id)->where('external_platform_id', self::EXTERNAL_PLATFORM_ID)->findOrEmpty();
  252. if($platformGoods->isEmpty()){
  253. throw new \Exception('外部商品不存在!');
  254. }
  255. $platformGoods = $platformGoods->toArray();
  256. $quantity = $quantity?:1;
  257. $appointment_time = strtotime($params['appointment_time']??date('Y-m-d H:i:s',time()));
  258. $bookStartTime = $appointment_time * 1000;
  259. $bookEndTime = ($appointment_time + (2 * 86400)) * 1000;
  260. $data = [
  261. /*"goodsList" => [
  262. "quantity" => $quantity,
  263. "price" => $platformGoods['service_fee'] * 100,
  264. "goodsName" => $goods['goods_name'],
  265. "goodsPhoto" => $goods['goods_image']??'',
  266. "goodsId" => '',
  267. "goodsType" => 1
  268. ],*/
  269. "skuList" => [
  270. [
  271. "quantity" => (int)$quantity,
  272. "skuId" => (string)$platformGoods['external_goods_sn'],
  273. "skuType" => 1, // 1:商品库商品 2:非商品库商品(融合预约品走加价时,固定传2)
  274. "price" => $platformGoods['service_fee'] * 100,
  275. ]
  276. ],
  277. "bookInfo" => [
  278. "itemBookInfoList"=>[
  279. [
  280. "poiId" => '7511543640776017961',
  281. "shopName" => '亿蜂快修·武汉市',
  282. "outShopId" => (string)self::EXTERNAL_PLATFORM_ID,
  283. "skuId" => (string)$platformGoods['external_goods_sn'],
  284. "bookStartTime" => $bookStartTime?:'',
  285. "bookEndTime" => $bookEndTime?:'',
  286. ]
  287. ]
  288. ],
  289. "payment" => [
  290. "totalAmount" => $quantity * $platformGoods['service_fee'] * 100,
  291. ],
  292. //"callbackUrl" => $callbackUrl?:'',
  293. "callbackData" => [
  294. "outShopId" => self::EXTERNAL_PLATFORM_ID,
  295. "skuId" => (string)$platformGoods['external_goods_sn'],
  296. "quantity" => $quantity,
  297. "user_id" => $params['user_id'],
  298. "douyinOrderId" => (string)$douyinOrderId?:'',
  299. "user_name" => $params['user_name']??'',
  300. "mobile" => $params['mobile']??'',
  301. "user_address" => $params['user_address']??'',
  302. "lon" => $params['lon']??'',
  303. "lat" => $params['lat']??'',
  304. "appointment_time" => $params['appointment_time']??''
  305. ],
  306. /*"tradeOption" => json_encode([
  307. "life_trade_flag" => 1,
  308. "order_relation_info" => [
  309. "related_order_id" => 0, // 加价时上个订单号
  310. "relation_type" => 'multi_buy_as_one'
  311. ]
  312. ])*/
  313. ];
  314. if($douyinOrderId){ // 说明是来自首单订单即要创建尾款
  315. unset($data['skuList']);
  316. unset($data['bookInfo']);
  317. $data['callbackUrl'] = env('douyin.pay_tail_notify_url')??'';
  318. $data['tradeOption'] = [
  319. //"life_trade_flag" => 1,
  320. "order_relation_info" => [
  321. "related_order_id" => (string)$douyinOrderId?:'', // 加价时上个订单号
  322. "relation_type" => 'multi_buy_as_one'
  323. ]
  324. ];
  325. }
  326. /*else{ // 创建首单订单
  327. $data['callbackUrl'] = '';
  328. }*/
  329. return $data;
  330. } catch (\Exception $e) {
  331. throw new \Exception($e->getMessage());
  332. }
  333. }
  334. // ++++++++++++++++++++ 首次/尾款 扩展点
  335. /**
  336. * 预下单扩展点
  337. * @param $params
  338. * @throws \Exception
  339. * @author liugc <466014217@qq.com>
  340. * @date 2025/6/4 14:03
  341. */
  342. public static function submitOrderNotify($params = [])
  343. {
  344. try {
  345. $params['external_platform_id'] = self::EXTERNAL_PLATFORM_ID;
  346. // order_id goods total_amount discount cp_extra create_order_time phone_num contact_name open_id
  347. $params['cp_extra'] = json_decode($params['cp_extra'], true);
  348. $user_id = $params['cp_extra']['user_id'];
  349. $user = User::where('id',$user_id)->findOrEmpty();
  350. if($params['cp_extra']['douyinOrderId']>0){ // 说明是尾款单
  351. // 创建尾款单
  352. $order_number = self::tailOrder([
  353. 'douyinOrderId'=>$params['cp_extra']['douyinOrderId'],
  354. 'user_id'=>$user_id??0,
  355. 'total_amount'=>$params['total_amount'],
  356. 'discount_amount'=>$params['discount_amount'],
  357. ]);
  358. $payNotifyUrl = 'https://weixiudev.kyjlkj.com/api/dou_yin/payTailNotify';
  359. }else{
  360. // 创建首单 goods_id user_info.mobile user_id quantity
  361. $params['cp_extra']['open_book_info'] = $params['open_book_info'];
  362. $order_number = self::submitOrder([
  363. 'open_id'=>$params['open_id'],
  364. 'order_id'=>$params['order_id'], // 抖音订单号
  365. 'goods_id'=>$params['cp_extra']['skuId'],
  366. 'user_id'=>$user_id??0,
  367. 'mobile'=>$user['mobile']??'',
  368. 'quantity'=>$params['cp_extra']['quantity'],
  369. 'book_info'=>$params['cp_extra'],
  370. ]);
  371. $payNotifyUrl = 'https://weixiudev.kyjlkj.com/api/dou_yin/payNotify';
  372. }
  373. return [
  374. "out_order_no" => $order_number,
  375. "order_entry_schema" => [
  376. "path" => "pages/order/detail",
  377. "params" => json_encode(['order_number' => $order_number])
  378. ],
  379. "payNotifyUrl" => $payNotifyUrl
  380. ];
  381. } catch (\Exception $e) {
  382. throw new \Exception($e->getMessage());
  383. }
  384. }
  385. // ++++++++++++++++++++ 首次创单
  386. /**
  387. * 预下单扩展点-子
  388. * @param array $params goods_id user_info.mobile user_id quantity
  389. * @return array|false
  390. */
  391. public static function submitOrder($params)
  392. {
  393. Db::startTrans();
  394. try {
  395. $platformGoods = ExternalPlatformGoods::where('external_goods_sn', $params['goods_id'])->where('external_platform_id', self::EXTERNAL_PLATFORM_ID)->findOrEmpty();
  396. if($platformGoods->isEmpty()){
  397. throw new \Exception('产品不存在!');
  398. }
  399. $goods = Goods::findOrEmpty($platformGoods['goods_id']);
  400. if($goods->isEmpty()){
  401. throw new \Exception('产品不存在!');
  402. }
  403. if(empty($params['mobile'])){
  404. throw new \Exception('请先补充您的联系方式后在提交订单');
  405. }
  406. // TODO tmp防抖1m
  407. $isExist = DouyinOrder::where(['user_id'=>$params['user_id'],'goods_id'=>$goods['id']])->where('create_time','>',(time() - 60))->findOrEmpty();
  408. if(!$isExist->isEmpty()){
  409. //throw new \Exception('请勿重复下单!');
  410. }
  411. $quantity = $params['quantity']??1;
  412. //生成订单
  413. $create_data = [
  414. 'user_id' => $params['user_id'],
  415. 'mobile' => $params['mobile'],
  416. 'open_id' => $params['open_id'],
  417. 'goods_id'=>$goods['id'],
  418. 'title' => $goods['goods_name'],
  419. 'book_info' => json_encode($params['book_info']??[]),
  420. 'unit_price' => $platformGoods['service_fee'],
  421. 'quantity' => $quantity,
  422. 'total_amount' => $platformGoods['service_fee'] * $quantity,
  423. 'dy_order_id' => $params['order_id']??'',
  424. 'order_number' => generate_sn(DouyinOrder::class, 'order_number'),
  425. ];
  426. $order = DouyinOrder::create($create_data);
  427. Db::commit();
  428. return $create_data['order_number'];
  429. } catch (\Exception $e) {
  430. Db::rollback();
  431. throw new \Exception($e->getMessage());
  432. }
  433. }
  434. // 支付成功回调
  435. public static function payNotify($params)
  436. {
  437. Log::write(json_encode($params));
  438. // 查询抖音订单是否完成支付
  439. if ($params['status'] === 'SUCCESS') {
  440. $params['cp_extra'] = json_decode($params['cp_extra'], true);
  441. $transaction_id = $params['order_id']??'';
  442. $paid_amount = bcdiv(bcsub($params['total_amount'] ,$params['discount_amount']), '100', 2)??0;
  443. $out_order_no = $params['out_order_no'];
  444. $pay_time = time();
  445. $order = DouyinOrder::where('order_number', $out_order_no)->findOrEmpty();
  446. if(!$order->isEmpty() && empty($order->consultation_id)){
  447. // 更新充值订单状态
  448. $order->transaction_id = $transaction_id;
  449. $order->order_status = 2;
  450. $order->pay_time = $pay_time;
  451. $order->paid_amount = $paid_amount;
  452. $user = User::where('id',$order->user_id)->findOrEmpty()->toArray();
  453. $form_detail = [
  454. 'user_name' => $user['real_name']??'',
  455. 'mobile' => $user['mobile'],
  456. 'transaction_id' => $transaction_id,
  457. 'out_trade_no' => $out_order_no,
  458. 'paid_amount' => $paid_amount,
  459. 'params' => $params,
  460. ];
  461. $consultation = ExternalConsultation::create([
  462. 'external_platform_id' => self::EXTERNAL_PLATFORM_ID,
  463. 'form_detail' => json_encode($form_detail),
  464. 'user_name' => $user['real_name']??'',
  465. 'mobile' => $user['mobile'],
  466. 'goods_id' => $order->goods_id,
  467. 'amount' => $paid_amount
  468. ]);
  469. $order->consultation_id = $consultation->id;
  470. $order->save();
  471. //order_number user_address lon lat appointment_time
  472. self::reservation([
  473. 'order_number' => $out_order_no,
  474. 'user_address' => $params['cp_extra']['user_address'],
  475. 'lon' => $params['cp_extra']['lon'],
  476. 'lat' => $params['cp_extra']['lat'],
  477. 'appointment_time' => $params['cp_extra']['appointment_time'],
  478. ]);
  479. return true;
  480. }
  481. }elseif ($params['status'] === 'CANCEL' && $params['message'] == 'TIME_OUT'){
  482. // 超时取消支付
  483. Log::info('支付超时取消:order_id'.$params['order_id']."--out_order_no:" .$params['out_order_no']);
  484. return true;
  485. }
  486. return false;
  487. }
  488. // ++++++++++++++++++++ 首次创单 end
  489. // ++++++++++++++++++++ 尾款创单
  490. /**
  491. * 预下单扩展点-子
  492. * @param array $params goods_id user_info.mobile user_id quantity
  493. * @return array|false
  494. */
  495. public static function tailOrder($params)
  496. {
  497. Db::startTrans();
  498. try {
  499. $amount = bcdiv(bcsub($params['total_amount'] ,$params['discount_amount']), '100', 2)??0;
  500. $work_id = DouyinOrder::where(['id'=>$params['douyinOrderId']])->value('work_id')??0;
  501. $sn = '';
  502. $rechargeOrder = RechargeOrder::where(['work_id'=>$work_id,'payment_type'=>2])->findOrEmpty();
  503. if($work_id && $rechargeOrder->isEmpty()){
  504. //新增待支付尾款
  505. $sn = generate_sn(RechargeOrder::class, 'sn');
  506. $order_data = [
  507. 'order_type' => 0,
  508. 'sn' => $sn,
  509. 'order_terminal' => 1,
  510. 'work_id' => $work_id,
  511. 'user_id' => $params['user_id'],
  512. 'payment_type' => 2,
  513. 'order_total' => $amount,
  514. 'order_amount' => $amount,
  515. 'pay_status' => 0,
  516. 'paid_amount' => 0,
  517. 'pay_way' => 4
  518. ];
  519. RechargeOrder::create($order_data);
  520. }else{
  521. $sn = $rechargeOrder->sn;
  522. }
  523. Db::commit();
  524. return $sn;
  525. } catch (\Exception $e) {
  526. Db::rollback();
  527. throw new \Exception($e->getMessage());
  528. }
  529. }
  530. // 尾款支付成功回调
  531. public static function payTailNotify($params)
  532. {
  533. Log::write(json_encode($params));
  534. // 查询抖音订单是否完成支付
  535. if ($params['status'] === 'SUCCESS') {
  536. $transaction_id = $params['order_id']??'';
  537. $paid_amount = bcdiv(bcsub($params['total_amount'] ,$params['discount_amount']), '100', 2)??0;
  538. $out_order_no = $params['out_order_no'];
  539. $pay_time = time();
  540. $params['cp_extra'] = json_decode($params['cp_extra'], true);
  541. $work_id = DouyinOrder::where(['id'=>$params['cp_extra']['douyinOrderId']])->value('work_id')??0;
  542. $rechargeOrder = RechargeOrder::where(['work_id'=>$work_id,'sn'=>$out_order_no,'payment_type'=>2])->findOrEmpty();
  543. if(!$rechargeOrder->isEmpty()){
  544. // 更新充值订单状态
  545. $rechargeOrder->transaction_id = $transaction_id;
  546. $rechargeOrder->pay_status = 1;
  547. $rechargeOrder->pay_time = $pay_time;
  548. $rechargeOrder->paid_amount = $paid_amount;
  549. $rechargeOrder->save();
  550. // 尾款订单支付成功后续操作 fun
  551. //抖音订单服务完成
  552. $order = DouyinOrder::where('id', $params['cp_extra']['douyinOrderId'])->findOrEmpty();
  553. $order->order_status = 4;
  554. $order->pay_status = 1;
  555. $order->total_amount += $paid_amount;
  556. $order->paid_amount += $paid_amount;
  557. $order->save();
  558. //工单完结
  559. self::paymentSuccessful(['sn'=>$out_order_no,'pay_way'=>4]);
  560. return true;
  561. }
  562. }elseif ($params['status'] === 'CANCEL' && $params['message'] == 'TIME_OUT'){
  563. // 超时取消支付
  564. Log::info('支付超时取消:order_id'.$params['order_id']."--out_order_no:" .$params['out_order_no']);
  565. return true;
  566. }
  567. return false;
  568. }
  569. public static function paymentSuccessful($data = [])
  570. {
  571. try {
  572. $params = $data;
  573. $params['sn'] = mb_substr($params['sn'], 0, 18);
  574. $order = RechargeOrder::where(['sn' => $params['sn']])->findOrEmpty();
  575. if($order->isEmpty()) {
  576. throw new \Exception('内部订单不存在:'.$params['sn'],404);
  577. }
  578. if($order->pay_status == PayEnum::ISPAID) {
  579. return true;
  580. }
  581. if(!empty($params['pay_way']??'')) $params['extra']['pay_way'] = $params['pay_way'];
  582. $payNotifyLogic = PayNotifyLogic::handle('goods', $params['sn'], $params['extra']??[]);
  583. if($payNotifyLogic === true){
  584. // 用户下单后,给订单运营专员(配置固定ID)发送公众号提醒(订单信息)
  585. $order = RechargeOrder::where('sn', $params['sn'])
  586. ->where('payment_type','IN',[0,1])
  587. ->where('pay_status','=',1)
  588. ->findOrEmpty();
  589. if(!$order->isEmpty()){
  590. $workDetail = ServiceWork::findOrEmpty($order->work_id);
  591. if(!$workDetail->isEmpty()){
  592. event('Notice', [
  593. 'scene_id' => 100,
  594. 'params' => [
  595. 'user_id' => 0,
  596. 'order_id' => $workDetail['id'],
  597. 'thing3' => $workDetail['title'],
  598. 'time6' => $workDetail['appointment_time'],
  599. 'phone_number8' => asteriskString($workDetail['mobile']),
  600. 'thing5' => (iconv_strlen($workDetail['address'])>15)?(mb_substr($workDetail['address'],0,15,'UTF-8').'...'):$workDetail['address'],
  601. ]
  602. ]);
  603. }
  604. }
  605. return true;
  606. }
  607. throw new \Exception($payNotifyLogic,404);
  608. }catch(\Exception $e){
  609. throw new \Exception($e->getMessage());
  610. }
  611. }
  612. // ++++++++++++++++++++ 尾款创单 end
  613. // ******************************** 订单预约/改约
  614. // 创建预约单
  615. public static function reservation($params)
  616. {
  617. /*$lon_lat = get_address_lat_lng($params['user_address']);
  618. $params['lon'] = $lon_lat['lon'];
  619. $params['lat'] = $lon_lat['lat'];*/
  620. // $params['order_number'] user_address lon lat appointment_time
  621. Db::startTrans();
  622. try {
  623. $order = DouyinOrder::where('order_number', $params['order_number'])->findOrEmpty();
  624. if(!$order->isEmpty() && $order->consultation_id && empty($order->work_id)){
  625. $consultation = ExternalConsultation::where('id', $order->consultation_id)->findOrEmpty()->toArray();
  626. $consultation['user_name'] = $params['user_name']??$consultation['user_name'];
  627. $consultation['mobile'] = $params['mobile']??$consultation['mobile'];
  628. $consultation['user_address'] = $params['user_address'];
  629. $consultation['lon'] = $params['lon'];
  630. $consultation['lat'] = $params['lat'];
  631. $consultation['appointment_time'] = $params['appointment_time'];
  632. $consultationOrderId = ExternalConsultationLogic::order($consultation);
  633. if (false === $consultationOrderId) {
  634. throw new \Exception('预约失败');
  635. }
  636. if(!empty($consultationOrderId)){
  637. $consultationOrder = ExternalConsultationOrder::where('id', $consultationOrderId)->findOrEmpty()->toArray();
  638. $work_status = ServiceWork::where('id', $consultationOrder['work_id'])->value('work_status');
  639. $order->work_id = $consultationOrder['work_id'];
  640. $order->fulfillment_status = $work_status;
  641. $order->save();
  642. }
  643. $params['dy_order_id'] = $order->dy_order_id;
  644. $params['consultationOrderId'] = $consultationOrderId;
  645. $params['open_id'] = $order->open_id;
  646. $params['goods_id'] = $order->goods_id;
  647. }elseif ($order->consultation_id && $order->work_id){
  648. $consultationOrderId = ExternalConsultationOrder::where('work_id', $order->work_id)->where('consultation_id', $order->consultation_id)->value('id')??0;
  649. $params['dy_order_id'] = $order->dy_order_id;
  650. $params['consultationOrderId'] = $consultationOrderId;
  651. $params['open_id'] = $order->open_id;
  652. $params['goods_id'] = $order->goods_id;
  653. }else{
  654. throw new \Exception('预约失败');
  655. }
  656. Db::commit();
  657. // 抖音创建预约单
  658. //$url = 'api/apps/trade/v2/book/create_book';
  659. //$resData = self::toDyRequestUrl($url,self::getCreateBookParams($params));
  660. //book_id result
  661. // 抖音预约接单结果回调
  662. $bookInfo = json_decode($order->book_info, true);
  663. if(isset($bookInfo['open_book_info']) && $bookInfo['open_book_info']){
  664. $bookurl = 'api/apps/trade/v2/book/book_result_callback';
  665. $res = self::toDyRequestUrl($bookurl,[
  666. 'book_id' => $bookInfo['open_book_info']['book_id']??$params['dy_order_id'],
  667. 'result' => 1,
  668. ]);
  669. }
  670. return $order['id']??0;
  671. } catch (\Exception $e) {
  672. Db::rollback();
  673. throw new \Exception($e->getMessage());
  674. }
  675. }
  676. public static function getCreateBookParams($params)
  677. {
  678. try {
  679. $platformGoods = ExternalPlatformGoods::where('goods_id', $params['goods_id'])->where('external_platform_id', self::EXTERNAL_PLATFORM_ID)->findOrEmpty();
  680. if($platformGoods->isEmpty()){
  681. throw new \Exception('产品不存在!');
  682. }
  683. $appointment_time = strtotime($params['appointment_time']);
  684. $book_start_time = $appointment_time * 1000;
  685. $book_end_time = ($appointment_time + (2 * 86400)) * 1000;
  686. $data = [
  687. "order_id"=> (string)$params['dy_order_id']??'',
  688. "out_book_no"=> (string)$params['consultationOrderId']??'',
  689. "open_id"=> (string)$params['open_id']??'',
  690. "item_book_info_list" => [
  691. [
  692. "poi_id" => '7511543640776017961',
  693. "shop_name" => '亿蜂快修·武汉市',
  694. "ext_shop_id" => (string)self::EXTERNAL_PLATFORM_ID,
  695. "goods_id" => (string)$platformGoods->external_goods_sn,
  696. "book_start_time" => (int)$book_start_time??0,
  697. "book_end_time" => (int)$book_end_time??0,
  698. ]
  699. ]
  700. ];
  701. return $data;
  702. } catch (\Exception $e) {
  703. return [];
  704. }
  705. }
  706. public static function upReservation($params)
  707. {
  708. // $params['order_number']
  709. Db::startTrans();
  710. try {
  711. $order = DouyinOrder::where('order_number', $params['order_number'])->findOrEmpty();
  712. if(!$order->isEmpty()){
  713. // sn appointment_time
  714. $result = ServiceOrderLogic::approvalChangeAppointment(['sn'=>RechargeOrder::where('work_id', $order->work_id)->value('sn'),'appointment_time'=>$params['appointment_time']]);
  715. if (false === $result) {
  716. throw new \Exception(ServiceOrderLogic::getError());
  717. }
  718. $order->fulfillment_status = ServiceWork::where('id', $order->work_id)->value('work_status');
  719. $order->save();
  720. }
  721. Db::commit();
  722. return $order['id'];
  723. } catch (\Exception $e) {
  724. Db::rollback();
  725. throw new \Exception($e->getMessage());
  726. }
  727. }
  728. // ******************************** 订单退款
  729. public static function cancelOrder($params)
  730. {
  731. // $params['order_number']
  732. Db::startTrans();
  733. try {
  734. $order = DouyinOrder::where('order_number', $params['order_number'])->findOrEmpty();
  735. if(!$order->isEmpty()){
  736. if($order->order_status == 1 && $order->pay_status == 0){
  737. $order->order_status = 4;
  738. $order->save();
  739. }else{
  740. throw new \Exception('订单状态不可取消!');
  741. }
  742. }
  743. Db::commit();
  744. return $order['id'];
  745. } catch (\Exception $e) {
  746. Db::rollback();
  747. throw new \Exception($e->getMessage());
  748. }
  749. }
  750. public static function refund($params)
  751. {
  752. Db::startTrans();
  753. try {
  754. // $params['order_number'] user_id
  755. $order = DouyinOrder::with(['goods','serviceWork'])->where('order_number', $params['order_number'])->where('user_id', $params['user_id'])->findOrEmpty();
  756. if($order->isEmpty()){
  757. throw new \Exception('订单不存在');
  758. }
  759. $orderInfo = $order->toArray();
  760. $work_status = $orderInfo['serviceWork']['work_status']??0;
  761. if(3 < $work_status){
  762. throw new \Exception('该订单禁止退款');
  763. }
  764. DouyinRefundOrder::create([
  765. 'refund_number' => generate_sn(DouyinRefundOrder::class, 'refund_number'),
  766. 'order_number' => $orderInfo['order_number'],
  767. 'transaction_id' => $orderInfo['transaction_id'],
  768. 'reason' => $params['reason']??'',
  769. 'refund_status' => 0,
  770. 'user_id' => $orderInfo['user_id'],
  771. 'refund_amount' => $orderInfo['paid_amount'],
  772. ]);
  773. Db::commit();
  774. return true;
  775. } catch (\Exception $e) {
  776. Db::rollback();
  777. throw new \Exception($e->getMessage());
  778. }
  779. }
  780. public static function refundExamine($params)
  781. {
  782. Db::startTrans();
  783. try {
  784. // $params['order_number']
  785. $order = DouyinOrder::with(['goods','serviceWork'])->where('order_number', $params['order_number'])->findOrEmpty();
  786. if($order->isEmpty()){
  787. throw new \Exception('订单不存在');
  788. }
  789. $orderInfo = $order->toArray();
  790. //$refund_number = $params['refund_number']??'';
  791. $douyinRefundOrder = DouyinRefundOrder::where('order_number', $params['order_number'])->order('id', 'desc')->findOrEmpty();
  792. if($params['is_examine_ok'] === 'pass'){
  793. $douyinRefundOrder->refund_status = 2;
  794. RechargeOrder::where('work_id', $orderInfo['work_id'])->update([
  795. 'pay_status' => 2,
  796. 'pay_time' => 0,
  797. 'paid_amount' => 0,
  798. ]);
  799. ServiceWork::where('id', $orderInfo['work_id'])->update([
  800. 'work_status' => 0,
  801. 'user_confirm_status' => 0,
  802. 'service_status' => 4,
  803. 'work_pay_status' => 0
  804. ]);
  805. }else{
  806. $douyinRefundOrder->refund_status = 1;
  807. }
  808. $douyinRefundOrder->save();
  809. Db::commit();
  810. if($params['is_examine_ok'] === 'pass'){
  811. //通过后向抖音申请退款
  812. self::sendRefundCreate($params['order_number']);
  813. }
  814. return true;
  815. } catch (\Exception $e) {
  816. Db::rollback();
  817. throw new \Exception($e->getMessage());
  818. }
  819. }
  820. public static function sendRefundCreate($order_number)
  821. {
  822. try {
  823. // $params['order_number']
  824. $order = DouyinOrder::with(['goods','serviceWork'])->where('order_number', $order_number)->findOrEmpty();
  825. if($order->isEmpty()){
  826. throw new \Exception('订单不存在');
  827. }
  828. $orderInfo = $order->toArray();
  829. $douyinRefundOrder = DouyinRefundOrder::where('order_number', $order_number)->order('id', 'desc')->findOrEmpty();
  830. //通过后向抖音申请退款
  831. $url = 'api/trade_basic/v1/developer/refund_create/';
  832. $data = [
  833. "order_id" => $orderInfo['transaction_id'],
  834. "out_refund_no" => $douyinRefundOrder->refund_number,
  835. "cp_extra" => $orderInfo['id'].'|'.$douyinRefundOrder->id,
  836. "order_entry_schema" => [
  837. "path" => "page/index/index",
  838. "params" => json_encode(['refund_number'=>$douyinRefundOrder->refund_number])
  839. ],
  840. "refund_total_amount " => $douyinRefundOrder->refund_amount * 100,
  841. //"notify_url" => config('douyin.refundNotifyUrl'),
  842. "refund_reason" => [
  843. [
  844. "code" => 101,
  845. "text" => "不想要了"
  846. ]
  847. ]
  848. ];
  849. $resData = self::toDyRequestUrl($url,$data);
  850. if(isset($resData['data']) && $resData['data']){
  851. $douyinRefundOrder->transaction_id = $resData['data']['refund_id'];
  852. $douyinRefundOrder->save();
  853. }
  854. return true;
  855. } catch (\Exception $e) {
  856. Log::info($e->getMessage());
  857. return false;
  858. }
  859. }
  860. public static function refundNotify($params)
  861. {
  862. Db::startTrans();
  863. try {
  864. $douyinRefundOrder = DouyinRefundOrder::where('refund_number', $params['out_refund_no'])->findOrEmpty();
  865. if($douyinRefundOrder->isEmpty()){
  866. throw new \Exception('退款订单不存在');
  867. }
  868. if($douyinRefundOrder->refund_status == 0){
  869. if($params['status'] === 'SUCCESS'){
  870. $douyinRefundOrder->refund_status = 3;
  871. DouyinOrder::where('order_number', $douyinRefundOrder->order_number)->update([
  872. 'order_status' => 4,
  873. 'pay_status' => 3,
  874. ]);
  875. }elseif($params['status'] === 'FAIL'){
  876. $douyinRefundOrder->refund_status = 4;
  877. }else{
  878. throw new \Exception('退款状态未知');
  879. }
  880. $douyinRefundOrder->save();
  881. }
  882. Db::commit();
  883. return true;
  884. } catch (\Exception $e) {
  885. Db::rollback();
  886. throw new \Exception($e->getMessage());
  887. }
  888. }
  889. public static function toDyRequestUrl($url,$data,$headers = [],$resFunction = 'extraErrorCodeReturn',$isHost = 0)
  890. {
  891. $toData = [
  892. 'url' => $url,
  893. 'data' => $data,
  894. 'headers' => $headers,
  895. 'resFunction' => $resFunction,
  896. 'isHost' => $isHost
  897. ];
  898. $res = commonHttpClient(env('internal_api.api_url_host').'platf/dou_yin/toDyRequestUrl', $toData, 'post', 'json', ['Content-Type' => 'application/json']);
  899. Log::info(json_encode($res));
  900. if(isset($res['code']) && $res['code'] === 0){
  901. Log::info("toDyRequestUrl:".json_encode($res));
  902. return $res['data'];
  903. }else{
  904. Log::info("toDyRequestUrl:".$res['msg']);
  905. throw new \Exception($res['msg']);
  906. }
  907. }
  908. }