DouYinService.php 42 KB

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