DouYinService.php 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985
  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. unset($data['payment']);
  318. $douyinOrder = DouyinOrder::where(['user_id'=>$params['user_id'],'dy_order_id'=>$douyinOrderId])->findOrEmpty();
  319. $rechargeOrder = RechargeOrder::where(['work_id'=>$douyinOrder->work_id,'payment_type'=>2])->findOrEmpty();
  320. if(empty($rechargeOrder->order_amount)) throw new \Exception('尾款报价不存在!');
  321. $data['skuList'] = [
  322. [
  323. "quantity" => (int)$quantity,
  324. "skuId" => (string)$goods_id,
  325. "skuType" => 2, // 1:商品库商品 2:非商品库商品(融合预约品走加价时,固定传2)
  326. "price" => $rechargeOrder->order_amount * 100,
  327. "goodsInfo" => [
  328. "goodsName"=>$goods['goods_name'],
  329. "goodsPhoto"=>$goods['goods_image'], // 商品图片链接 必填
  330. "goodsId"=> (string)$goods_id,
  331. "goodsType"=>2
  332. ],
  333. "extraInfo" =>["feeType"=>14]
  334. ]
  335. ];
  336. $data['payment'] = [
  337. "totalAmount" => $rechargeOrder->order_amount * 100,
  338. ];
  339. $data['callbackUrl'] = env('douyin.pay_tail_notify_url')??'';
  340. $data['tradeOption'] = [
  341. "life_trade_flag" => 1,
  342. "trade_mode" => '3',
  343. "order_relation_info" => [
  344. "related_order_id" => (string)$douyinOrderId?:'', // 加价时上个订单号
  345. "relation_type" => 'multi_buy_as_one'
  346. ]
  347. ];
  348. }
  349. /*else{ // 创建首单订单
  350. $data['callbackUrl'] = '';
  351. }*/
  352. return $data;
  353. } catch (\Exception $e) {
  354. throw new \Exception($e->getMessage());
  355. }
  356. }
  357. // ++++++++++++++++++++ 首次/尾款 扩展点
  358. /**
  359. * 预下单扩展点
  360. * @param $params
  361. * @throws \Exception
  362. * @author liugc <466014217@qq.com>
  363. * @date 2025/6/4 14:03
  364. */
  365. public static function submitOrderNotify($params = [])
  366. {
  367. try {
  368. $params['external_platform_id'] = self::EXTERNAL_PLATFORM_ID;
  369. // order_id goods total_amount discount cp_extra create_order_time phone_num contact_name open_id
  370. $params['cp_extra'] = json_decode($params['cp_extra'], true);
  371. $user_id = $params['cp_extra']['user_id'];
  372. $user = User::where('id',$user_id)->findOrEmpty();
  373. if($params['cp_extra']['douyinOrderId']>0){ // 说明是尾款单
  374. // 创建尾款单
  375. $order_number = self::tailOrder([
  376. 'douyinOrderId'=>$params['cp_extra']['douyinOrderId'],
  377. 'user_id'=>$user_id??0,
  378. 'total_amount'=>$params['total_amount'],
  379. 'discount_amount'=>$params['discount_amount'],
  380. ]);
  381. $payNotifyUrl = 'https://weixiudev.kyjlkj.com/api/dou_yin/payTailNotify';
  382. }else{
  383. // 创建首单 goods_id user_info.mobile user_id quantity
  384. $params['cp_extra']['open_book_info'] = $params['open_book_info'];
  385. $order_number = self::submitOrder([
  386. 'open_id'=>$params['open_id'],
  387. 'order_id'=>$params['order_id'], // 抖音订单号
  388. 'goods_id'=>$params['cp_extra']['skuId'],
  389. 'user_id'=>$user_id??0,
  390. 'mobile'=>$user['mobile']??'',
  391. 'quantity'=>$params['cp_extra']['quantity'],
  392. 'book_info'=>$params['cp_extra'],
  393. ]);
  394. $payNotifyUrl = 'https://weixiudev.kyjlkj.com/api/dou_yin/payNotify';
  395. }
  396. return [
  397. "out_order_no" => $order_number,
  398. "order_entry_schema" => [
  399. "path" => "pages/order/detail",
  400. "params" => json_encode(['order_number' => $order_number])
  401. ],
  402. "payNotifyUrl" => $payNotifyUrl
  403. ];
  404. } catch (\Exception $e) {
  405. throw new \Exception($e->getMessage());
  406. }
  407. }
  408. // ++++++++++++++++++++ 首次创单
  409. /**
  410. * 预下单扩展点-子
  411. * @param array $params goods_id user_info.mobile user_id quantity
  412. * @return array|false
  413. */
  414. public static function submitOrder($params)
  415. {
  416. Db::startTrans();
  417. try {
  418. $platformGoods = ExternalPlatformGoods::where('external_goods_sn', $params['goods_id'])->where('external_platform_id', self::EXTERNAL_PLATFORM_ID)->findOrEmpty();
  419. if($platformGoods->isEmpty()){
  420. throw new \Exception('产品不存在!');
  421. }
  422. $goods = Goods::findOrEmpty($platformGoods['goods_id']);
  423. if($goods->isEmpty()){
  424. throw new \Exception('产品不存在!');
  425. }
  426. if(empty($params['mobile'])){
  427. throw new \Exception('请先补充您的联系方式后在提交订单');
  428. }
  429. // TODO tmp防抖1m
  430. $isExist = DouyinOrder::where(['user_id'=>$params['user_id'],'goods_id'=>$goods['id']])->where('create_time','>',(time() - 60))->findOrEmpty();
  431. if(!$isExist->isEmpty()){
  432. //throw new \Exception('请勿重复下单!');
  433. }
  434. $quantity = $params['quantity']??1;
  435. //生成订单
  436. $create_data = [
  437. 'user_id' => $params['user_id'],
  438. 'mobile' => $params['mobile'],
  439. 'open_id' => $params['open_id'],
  440. 'goods_id'=>$goods['id'],
  441. 'title' => $goods['goods_name'],
  442. 'book_info' => json_encode($params['book_info']??[]),
  443. 'unit_price' => $platformGoods['service_fee'],
  444. 'quantity' => $quantity,
  445. 'total_amount' => $platformGoods['service_fee'] * $quantity,
  446. 'dy_order_id' => $params['order_id']??'',
  447. 'order_number' => generate_sn(DouyinOrder::class, 'order_number'),
  448. ];
  449. $order = DouyinOrder::create($create_data);
  450. Db::commit();
  451. return $create_data['order_number'];
  452. } catch (\Exception $e) {
  453. Db::rollback();
  454. throw new \Exception($e->getMessage());
  455. }
  456. }
  457. // 支付成功回调
  458. public static function payNotify($params)
  459. {
  460. Log::write(json_encode($params));
  461. // 查询抖音订单是否完成支付
  462. if ($params['status'] === 'SUCCESS') {
  463. $params['cp_extra'] = json_decode($params['cp_extra'], true);
  464. $transaction_id = $params['order_id']??'';
  465. $paid_amount = bcdiv(bcsub($params['total_amount'] ,$params['discount_amount']), '100', 2)??0;
  466. $out_order_no = $params['out_order_no'];
  467. $pay_time = time();
  468. $order = DouyinOrder::where('order_number', $out_order_no)->findOrEmpty();
  469. if(!$order->isEmpty() && empty($order->consultation_id)){
  470. // 更新充值订单状态
  471. $order->transaction_id = $transaction_id;
  472. $order->order_status = 2;
  473. $order->pay_time = $pay_time;
  474. $order->paid_amount = $paid_amount;
  475. $user = User::where('id',$order->user_id)->findOrEmpty()->toArray();
  476. $form_detail = [
  477. 'user_name' => $user['real_name']??'',
  478. 'mobile' => $user['mobile'],
  479. 'transaction_id' => $transaction_id,
  480. 'out_trade_no' => $out_order_no,
  481. 'paid_amount' => $paid_amount,
  482. 'params' => $params,
  483. ];
  484. $consultation = ExternalConsultation::create([
  485. 'external_platform_id' => self::EXTERNAL_PLATFORM_ID,
  486. 'form_detail' => json_encode($form_detail),
  487. 'user_name' => $user['real_name']??'',
  488. 'mobile' => $user['mobile'],
  489. 'goods_id' => $order->goods_id,
  490. 'amount' => $paid_amount
  491. ]);
  492. $order->consultation_id = $consultation->id;
  493. $order->save();
  494. //order_number user_address lon lat appointment_time
  495. self::reservation([
  496. 'order_number' => $out_order_no,
  497. 'user_address' => $params['cp_extra']['user_address'],
  498. 'lon' => $params['cp_extra']['lon'],
  499. 'lat' => $params['cp_extra']['lat'],
  500. 'appointment_time' => $params['cp_extra']['appointment_time'],
  501. ]);
  502. return true;
  503. }
  504. }elseif ($params['status'] === 'CANCEL' && $params['message'] == 'TIME_OUT'){
  505. // 超时取消支付
  506. Log::info('支付超时取消:order_id'.$params['order_id']."--out_order_no:" .$params['out_order_no']);
  507. return true;
  508. }
  509. return false;
  510. }
  511. // ++++++++++++++++++++ 首次创单 end
  512. // ++++++++++++++++++++ 尾款创单
  513. /**
  514. * 预下单扩展点-子
  515. * @param array $params goods_id user_info.mobile user_id quantity
  516. * @return array|false
  517. */
  518. public static function tailOrder($params)
  519. {
  520. Db::startTrans();
  521. try {
  522. $amount = bcdiv(bcsub($params['total_amount'] ,$params['discount_amount']), '100', 2)??0;
  523. $work_id = DouyinOrder::where(['id'=>$params['douyinOrderId']])->value('work_id')??0;
  524. $sn = '';
  525. $rechargeOrder = RechargeOrder::where(['work_id'=>$work_id,'payment_type'=>2])->findOrEmpty();
  526. if($work_id && $rechargeOrder->isEmpty()){
  527. //新增待支付尾款
  528. $sn = generate_sn(RechargeOrder::class, 'sn');
  529. $order_data = [
  530. 'order_type' => 0,
  531. 'sn' => $sn,
  532. 'order_terminal' => 1,
  533. 'work_id' => $work_id,
  534. 'user_id' => $params['user_id'],
  535. 'payment_type' => 2,
  536. 'order_total' => $amount,
  537. 'order_amount' => $amount,
  538. 'pay_status' => 0,
  539. 'paid_amount' => 0,
  540. 'pay_way' => 4
  541. ];
  542. RechargeOrder::create($order_data);
  543. }else{
  544. $sn = $rechargeOrder->sn;
  545. }
  546. Db::commit();
  547. return $sn;
  548. } catch (\Exception $e) {
  549. Db::rollback();
  550. throw new \Exception($e->getMessage());
  551. }
  552. }
  553. // 尾款支付成功回调
  554. public static function payTailNotify($params)
  555. {
  556. Log::write(json_encode($params));
  557. // 查询抖音订单是否完成支付
  558. if ($params['status'] === 'SUCCESS') {
  559. $transaction_id = $params['order_id']??'';
  560. $paid_amount = bcdiv(bcsub($params['total_amount'] ,$params['discount_amount']), '100', 2)??0;
  561. $out_order_no = $params['out_order_no'];
  562. $pay_time = time();
  563. $params['cp_extra'] = json_decode($params['cp_extra'], true);
  564. $work_id = DouyinOrder::where(['id'=>$params['cp_extra']['douyinOrderId']])->value('work_id')??0;
  565. $rechargeOrder = RechargeOrder::where(['work_id'=>$work_id,'sn'=>$out_order_no,'payment_type'=>2])->findOrEmpty();
  566. if(!$rechargeOrder->isEmpty()){
  567. // 更新充值订单状态
  568. $rechargeOrder->transaction_id = $transaction_id;
  569. $rechargeOrder->pay_status = 1;
  570. $rechargeOrder->pay_time = $pay_time;
  571. $rechargeOrder->paid_amount = $paid_amount;
  572. $rechargeOrder->save();
  573. // 尾款订单支付成功后续操作 fun
  574. //抖音订单服务完成
  575. $order = DouyinOrder::where('id', $params['cp_extra']['douyinOrderId'])->findOrEmpty();
  576. $order->order_status = 4;
  577. $order->pay_status = 1;
  578. $order->total_amount += $paid_amount;
  579. $order->paid_amount += $paid_amount;
  580. $order->save();
  581. //工单完结
  582. self::paymentSuccessful(['sn'=>$out_order_no,'pay_way'=>4]);
  583. return true;
  584. }
  585. }elseif ($params['status'] === 'CANCEL' && $params['message'] == 'TIME_OUT'){
  586. // 超时取消支付
  587. Log::info('支付超时取消:order_id'.$params['order_id']."--out_order_no:" .$params['out_order_no']);
  588. return true;
  589. }
  590. return false;
  591. }
  592. public static function paymentSuccessful($data = [])
  593. {
  594. try {
  595. $params = $data;
  596. $params['sn'] = mb_substr($params['sn'], 0, 18);
  597. $order = RechargeOrder::where(['sn' => $params['sn']])->findOrEmpty();
  598. if($order->isEmpty()) {
  599. throw new \Exception('内部订单不存在:'.$params['sn'],404);
  600. }
  601. if($order->pay_status == PayEnum::ISPAID) {
  602. return true;
  603. }
  604. if(!empty($params['pay_way']??'')) $params['extra']['pay_way'] = $params['pay_way'];
  605. $payNotifyLogic = PayNotifyLogic::handle('goods', $params['sn'], $params['extra']??[]);
  606. if($payNotifyLogic === true){
  607. // 用户下单后,给订单运营专员(配置固定ID)发送公众号提醒(订单信息)
  608. $order = RechargeOrder::where('sn', $params['sn'])
  609. ->where('payment_type','IN',[0,1])
  610. ->where('pay_status','=',1)
  611. ->findOrEmpty();
  612. if(!$order->isEmpty()){
  613. $workDetail = ServiceWork::findOrEmpty($order->work_id);
  614. if(!$workDetail->isEmpty()){
  615. event('Notice', [
  616. 'scene_id' => 100,
  617. 'params' => [
  618. 'user_id' => 0,
  619. 'order_id' => $workDetail['id'],
  620. 'thing3' => $workDetail['title'],
  621. 'time6' => $workDetail['appointment_time'],
  622. 'phone_number8' => asteriskString($workDetail['mobile']),
  623. 'thing5' => (iconv_strlen($workDetail['address'])>15)?(mb_substr($workDetail['address'],0,15,'UTF-8').'...'):$workDetail['address'],
  624. ]
  625. ]);
  626. }
  627. }
  628. return true;
  629. }
  630. throw new \Exception($payNotifyLogic,404);
  631. }catch(\Exception $e){
  632. throw new \Exception($e->getMessage());
  633. }
  634. }
  635. // ++++++++++++++++++++ 尾款创单 end
  636. // ******************************** 订单预约/改约
  637. // 创建预约单
  638. public static function reservation($params)
  639. {
  640. /*$lon_lat = get_address_lat_lng($params['user_address']);
  641. $params['lon'] = $lon_lat['lon'];
  642. $params['lat'] = $lon_lat['lat'];*/
  643. // $params['order_number'] user_address lon lat appointment_time
  644. Db::startTrans();
  645. try {
  646. $order = DouyinOrder::where('order_number', $params['order_number'])->findOrEmpty();
  647. if(!$order->isEmpty() && $order->consultation_id && empty($order->work_id)){
  648. $consultation = ExternalConsultation::where('id', $order->consultation_id)->findOrEmpty()->toArray();
  649. $consultation['user_name'] = $params['user_name']??$consultation['user_name'];
  650. $consultation['mobile'] = $params['mobile']??$consultation['mobile'];
  651. $consultation['user_address'] = $params['user_address'];
  652. $consultation['lon'] = $params['lon'];
  653. $consultation['lat'] = $params['lat'];
  654. $consultation['appointment_time'] = $params['appointment_time'];
  655. $consultationOrderId = ExternalConsultationLogic::order($consultation);
  656. if (false === $consultationOrderId) {
  657. throw new \Exception('预约失败');
  658. }
  659. if(!empty($consultationOrderId)){
  660. $consultationOrder = ExternalConsultationOrder::where('id', $consultationOrderId)->findOrEmpty()->toArray();
  661. $work_status = ServiceWork::where('id', $consultationOrder['work_id'])->value('work_status');
  662. $order->work_id = $consultationOrder['work_id'];
  663. $order->fulfillment_status = $work_status;
  664. $order->save();
  665. }
  666. $params['dy_order_id'] = $order->dy_order_id;
  667. $params['consultationOrderId'] = $consultationOrderId;
  668. $params['open_id'] = $order->open_id;
  669. $params['goods_id'] = $order->goods_id;
  670. }elseif ($order->consultation_id && $order->work_id){
  671. $consultationOrderId = ExternalConsultationOrder::where('work_id', $order->work_id)->where('consultation_id', $order->consultation_id)->value('id')??0;
  672. $params['dy_order_id'] = $order->dy_order_id;
  673. $params['consultationOrderId'] = $consultationOrderId;
  674. $params['open_id'] = $order->open_id;
  675. $params['goods_id'] = $order->goods_id;
  676. }else{
  677. throw new \Exception('预约失败');
  678. }
  679. Db::commit();
  680. // 抖音创建预约单
  681. //$url = 'api/apps/trade/v2/book/create_book';
  682. //$resData = self::toDyRequestUrl($url,self::getCreateBookParams($params));
  683. //book_id result
  684. // 抖音预约接单结果回调
  685. $bookInfo = json_decode($order->book_info, true);
  686. if(isset($bookInfo['open_book_info']) && $bookInfo['open_book_info']){
  687. $bookurl = 'api/apps/trade/v2/book/book_result_callback';
  688. $res = self::toDyRequestUrl($bookurl,[
  689. 'book_id' => $bookInfo['open_book_info']['book_id']??$params['dy_order_id'],
  690. 'result' => 1,
  691. ]);
  692. }
  693. return $order['id']??0;
  694. } catch (\Exception $e) {
  695. Db::rollback();
  696. throw new \Exception($e->getMessage());
  697. }
  698. }
  699. public static function getCreateBookParams($params)
  700. {
  701. try {
  702. $platformGoods = ExternalPlatformGoods::where('goods_id', $params['goods_id'])->where('external_platform_id', self::EXTERNAL_PLATFORM_ID)->findOrEmpty();
  703. if($platformGoods->isEmpty()){
  704. throw new \Exception('产品不存在!');
  705. }
  706. $appointment_time = strtotime($params['appointment_time']);
  707. $book_start_time = $appointment_time * 1000;
  708. $book_end_time = ($appointment_time + (2 * 86400)) * 1000;
  709. $data = [
  710. "order_id"=> (string)$params['dy_order_id']??'',
  711. "out_book_no"=> (string)$params['consultationOrderId']??'',
  712. "open_id"=> (string)$params['open_id']??'',
  713. "item_book_info_list" => [
  714. [
  715. "poi_id" => '7511543640776017961',
  716. "shop_name" => '亿蜂快修·武汉市',
  717. "ext_shop_id" => (string)self::EXTERNAL_PLATFORM_ID,
  718. "goods_id" => (string)$platformGoods->external_goods_sn,
  719. "book_start_time" => (int)$book_start_time??0,
  720. "book_end_time" => (int)$book_end_time??0,
  721. ]
  722. ]
  723. ];
  724. return $data;
  725. } catch (\Exception $e) {
  726. return [];
  727. }
  728. }
  729. public static function upReservation($params)
  730. {
  731. // $params['order_number']
  732. Db::startTrans();
  733. try {
  734. $order = DouyinOrder::where('order_number', $params['order_number'])->findOrEmpty();
  735. if(!$order->isEmpty()){
  736. // sn appointment_time
  737. $result = ServiceOrderLogic::approvalChangeAppointment(['sn'=>RechargeOrder::where('work_id', $order->work_id)->value('sn'),'appointment_time'=>$params['appointment_time']]);
  738. if (false === $result) {
  739. throw new \Exception(ServiceOrderLogic::getError());
  740. }
  741. $order->fulfillment_status = ServiceWork::where('id', $order->work_id)->value('work_status');
  742. $order->save();
  743. }
  744. Db::commit();
  745. return $order['id'];
  746. } catch (\Exception $e) {
  747. Db::rollback();
  748. throw new \Exception($e->getMessage());
  749. }
  750. }
  751. // ******************************** 订单退款
  752. public static function cancelOrder($params)
  753. {
  754. // $params['order_number']
  755. Db::startTrans();
  756. try {
  757. $order = DouyinOrder::where('order_number', $params['order_number'])->findOrEmpty();
  758. if(!$order->isEmpty()){
  759. if($order->order_status == 1 && $order->pay_status == 0){
  760. $order->order_status = 4;
  761. $order->save();
  762. }else{
  763. throw new \Exception('订单状态不可取消!');
  764. }
  765. }
  766. Db::commit();
  767. return $order['id'];
  768. } catch (\Exception $e) {
  769. Db::rollback();
  770. throw new \Exception($e->getMessage());
  771. }
  772. }
  773. public static function refund($params)
  774. {
  775. Db::startTrans();
  776. try {
  777. // $params['order_number'] user_id
  778. $order = DouyinOrder::with(['goods','serviceWork'])->where('order_number', $params['order_number'])->where('user_id', $params['user_id'])->findOrEmpty();
  779. if($order->isEmpty()){
  780. throw new \Exception('订单不存在');
  781. }
  782. $orderInfo = $order->toArray();
  783. $work_status = $orderInfo['serviceWork']['work_status']??0;
  784. if(3 < $work_status){
  785. throw new \Exception('该订单禁止退款');
  786. }
  787. DouyinRefundOrder::create([
  788. 'refund_number' => generate_sn(DouyinRefundOrder::class, 'refund_number'),
  789. 'order_number' => $orderInfo['order_number'],
  790. 'transaction_id' => $orderInfo['transaction_id'],
  791. 'reason' => $params['reason']??'',
  792. 'refund_status' => 0,
  793. 'user_id' => $orderInfo['user_id'],
  794. 'refund_amount' => $orderInfo['paid_amount'],
  795. ]);
  796. Db::commit();
  797. return true;
  798. } catch (\Exception $e) {
  799. Db::rollback();
  800. throw new \Exception($e->getMessage());
  801. }
  802. }
  803. public static function refundExamine($params)
  804. {
  805. Db::startTrans();
  806. try {
  807. // $params['order_number']
  808. $order = DouyinOrder::with(['goods','serviceWork'])->where('order_number', $params['order_number'])->findOrEmpty();
  809. if($order->isEmpty()){
  810. throw new \Exception('订单不存在');
  811. }
  812. $orderInfo = $order->toArray();
  813. //$refund_number = $params['refund_number']??'';
  814. $douyinRefundOrder = DouyinRefundOrder::where('order_number', $params['order_number'])->order('id', 'desc')->findOrEmpty();
  815. if($params['is_examine_ok'] === 'pass'){
  816. $douyinRefundOrder->refund_status = 2;
  817. RechargeOrder::where('work_id', $orderInfo['work_id'])->update([
  818. 'pay_status' => 2,
  819. 'pay_time' => 0,
  820. 'paid_amount' => 0,
  821. ]);
  822. ServiceWork::where('id', $orderInfo['work_id'])->update([
  823. 'work_status' => 0,
  824. 'user_confirm_status' => 0,
  825. 'service_status' => 4,
  826. 'work_pay_status' => 0
  827. ]);
  828. }else{
  829. $douyinRefundOrder->refund_status = 1;
  830. }
  831. $douyinRefundOrder->save();
  832. Db::commit();
  833. if($params['is_examine_ok'] === 'pass'){
  834. //通过后向抖音申请退款
  835. self::sendRefundCreate($params['order_number']);
  836. }
  837. return true;
  838. } catch (\Exception $e) {
  839. Db::rollback();
  840. throw new \Exception($e->getMessage());
  841. }
  842. }
  843. public static function sendRefundCreate($order_number)
  844. {
  845. try {
  846. // $params['order_number']
  847. $order = DouyinOrder::with(['goods','serviceWork'])->where('order_number', $order_number)->findOrEmpty();
  848. if($order->isEmpty()){
  849. throw new \Exception('订单不存在');
  850. }
  851. $orderInfo = $order->toArray();
  852. $douyinRefundOrder = DouyinRefundOrder::where('order_number', $order_number)->order('id', 'desc')->findOrEmpty();
  853. //通过后向抖音申请退款
  854. $url = 'api/trade_basic/v1/developer/refund_create/';
  855. $data = [
  856. "order_id" => $orderInfo['transaction_id'],
  857. "out_refund_no" => $douyinRefundOrder->refund_number,
  858. "cp_extra" => $orderInfo['id'].'|'.$douyinRefundOrder->id,
  859. "order_entry_schema" => [
  860. "path" => "page/index/index",
  861. "params" => json_encode(['refund_number'=>$douyinRefundOrder->refund_number])
  862. ],
  863. "refund_total_amount " => $douyinRefundOrder->refund_amount * 100,
  864. //"notify_url" => config('douyin.refundNotifyUrl'),
  865. "refund_reason" => [
  866. [
  867. "code" => 101,
  868. "text" => "不想要了"
  869. ]
  870. ]
  871. ];
  872. $resData = self::toDyRequestUrl($url,$data);
  873. if(isset($resData['data']) && $resData['data']){
  874. $douyinRefundOrder->transaction_id = $resData['data']['refund_id'];
  875. $douyinRefundOrder->save();
  876. }
  877. return true;
  878. } catch (\Exception $e) {
  879. Log::info($e->getMessage());
  880. return false;
  881. }
  882. }
  883. public static function refundNotify($params)
  884. {
  885. Db::startTrans();
  886. try {
  887. $douyinRefundOrder = DouyinRefundOrder::where('refund_number', $params['out_refund_no'])->findOrEmpty();
  888. if($douyinRefundOrder->isEmpty()){
  889. throw new \Exception('退款订单不存在');
  890. }
  891. if($douyinRefundOrder->refund_status == 0){
  892. if($params['status'] === 'SUCCESS'){
  893. $douyinRefundOrder->refund_status = 3;
  894. DouyinOrder::where('order_number', $douyinRefundOrder->order_number)->update([
  895. 'order_status' => 4,
  896. 'pay_status' => 3,
  897. ]);
  898. }elseif($params['status'] === 'FAIL'){
  899. $douyinRefundOrder->refund_status = 4;
  900. }else{
  901. throw new \Exception('退款状态未知');
  902. }
  903. $douyinRefundOrder->save();
  904. }
  905. Db::commit();
  906. return true;
  907. } catch (\Exception $e) {
  908. Db::rollback();
  909. throw new \Exception($e->getMessage());
  910. }
  911. }
  912. public static function toDyRequestUrl($url,$data,$headers = [],$resFunction = 'extraErrorCodeReturn',$isHost = 0)
  913. {
  914. $toData = [
  915. 'url' => $url,
  916. 'data' => $data,
  917. 'headers' => $headers,
  918. 'resFunction' => $resFunction,
  919. 'isHost' => $isHost
  920. ];
  921. $res = commonHttpClient(env('internal_api.api_url_host').'platf/dou_yin/toDyRequestUrl', $toData, 'post', 'json', ['Content-Type' => 'application/json']);
  922. Log::info(json_encode($res));
  923. if(isset($res['code']) && $res['code'] === 0){
  924. Log::info("toDyRequestUrl:".json_encode($res));
  925. return $res['data'];
  926. }else{
  927. Log::info("toDyRequestUrl:".$res['msg']);
  928. throw new \Exception($res['msg']);
  929. }
  930. }
  931. }