1
0

DouYinService.php 37 KB

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