DouYinService.php 35 KB

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