DouYinService.php 37 KB

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