DouYinService.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  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\ExternalConsultation;
  9. use app\common\model\external\ExternalConsultationOrder;
  10. use app\common\model\external\ExternalPlatformGoods;
  11. use app\common\model\goods\Goods;
  12. use app\common\model\goods_category\GoodsCategory;
  13. use app\common\model\recharge\RechargeOrder;
  14. use app\common\model\user\User;
  15. use app\common\model\user\UserAuth;
  16. use app\common\model\works\ServiceWork;
  17. use app\common\service\ConfigService;
  18. use app\common\service\FileService;
  19. use think\facade\Db;
  20. use think\facade\Log;
  21. class DouYinService
  22. {
  23. protected static int $terminal = \app\common\enum\user\UserTerminalEnum::DOUYIN;
  24. protected static int $external_platform_id = 6;
  25. // ********************************* 注册登录
  26. public static function register(array $params)
  27. {
  28. $userSn = User::createUserSn();
  29. $params['password'] = !empty($params['password'])?$params['password']:rand(100000,999999);
  30. $passwordSalt = \think\facade\Config::get('project.unique_identification');
  31. $password = create_password($params['password'], $passwordSalt);
  32. $avatar = ConfigService::get('default_image', 'user_avatar');
  33. $user = User::create([
  34. 'sn' => $userSn,
  35. 'avatar' => $avatar,
  36. 'nickname' => '用户' . $userSn,
  37. 'account' => $params['account'],
  38. 'mobile' => !empty($params['mobile'])?$params['mobile']:'',
  39. 'password' => $password,
  40. 'channel' => self::$terminal,
  41. 'user_type' => $params['user_type']??0,
  42. ]);
  43. return $user;
  44. }
  45. public static function phoneLogin(array $params)
  46. {
  47. try {
  48. $where = ['mobile' => $params['mobile']];
  49. $params['account'] = $params['mobile'];
  50. $user = User::where($where)->findOrEmpty();
  51. if ($user->isEmpty()) {
  52. //直接注册用户
  53. $params['channel'] = self::$terminal;
  54. $user = self::register($params);
  55. }
  56. //更新登录信息
  57. $user->login_time = time();
  58. $user->login_ip = request()->ip();
  59. $user->save();
  60. $userInfo = UserTokenService::setToken($user->id, self::$terminal);
  61. //返回登录信息
  62. $avatar = $user->avatar ?: Config::get('project.default_image.user_avatar');
  63. $avatar = FileService::getFileUrl($avatar);
  64. return [
  65. 'nickname' => $userInfo['nickname'],
  66. 'sn' => $userInfo['sn'],
  67. 'mobile' => $userInfo['mobile'],
  68. 'avatar' => $avatar,
  69. 'token' => $userInfo['token'],
  70. ];
  71. } catch (\Exception $e) {
  72. throw new \Exception($e->getMessage());
  73. }
  74. }
  75. // **************************** 商品管理 goods_category_id goods_id external_platform_id
  76. public static function addProduct($params)
  77. {
  78. $send_url = env('internal_api.api_url_host').'platf/dou_yin/addGoods';
  79. $res = http_request($send_url,http_build_query($params));
  80. Log::info('addProduct:'
  81. .'url:'.$send_url
  82. .'|data:'.json_encode($params,JSON_UNESCAPED_UNICODE)
  83. .'|res:'.json_encode([$res],JSON_UNESCAPED_UNICODE)
  84. );
  85. return $res?:[];
  86. }
  87. public static function addSku($params)
  88. {
  89. $sku_url = config('douyin.host').'goodlife/v1/goods/sku/batch_save/';
  90. $res = http_request($sku_url,self::getSkuParams($params),['Content-Type' => 'application/json;charset=utf-8','access-token' => self::getClientToken()]);
  91. Log::info('addSku:'.json_encode($res));
  92. // 根据返回后更新本地库对应关系 $res['data']['sku_id_list']
  93. if(isset($res['data']['sku_id_list']) && !empty($res['data']['sku_id_list'])){
  94. foreach ($res['data']['sku_id_list'] as $item) {
  95. ExternalPlatformGoods::where('goods_id', $item['out_sku_id'])->where('external_platform_id', $params['external_platform_id'])->update([
  96. 'external_goods_sn' => $item['sku_id']
  97. ]);
  98. }
  99. }
  100. return [];
  101. }
  102. public static function getProductParams($params)
  103. {
  104. $goods = Goods::where('id',$params['goods_id']??0)->findOrEmpty();
  105. if($goods->isEmpty()){
  106. return [];
  107. }
  108. $goods = $goods->toArray();
  109. return [
  110. "account_id" => '7511543640776017961',
  111. "product" => [
  112. "out_id" => $params['goods_id']??0,
  113. "product_name" => $goods['goods_name']??'无',
  114. "product_type" => 22,
  115. "category_id" => 6004003,
  116. "category_full_name" => "其他维修服务",
  117. "biz_line" => 5,
  118. "account_name" => "亿蜂快修·武汉市",
  119. //{\"params\":\"{\"spuId\":\"xxxxx\",\"skuId\":\"xxxxxx\"}\",\"path\":\"pages/any/path\",\"app_id\":\"xxxxx\"}
  120. "out_url" => json_encode(['app_id'=>config('douyin.appId'),'path'=>'pages/detail','params'=>json_encode(['goods_id'=>$params['goods_id']??0])]),
  121. "pois" =>[
  122. [
  123. "poi_id" => "7511543640776017961"
  124. ]
  125. ],
  126. "product_ext" => [
  127. "auto_online" => true,
  128. "display_price"=> ["low_price" => 30,"high_price" => 300],
  129. "test_extra"=> ["test_flag" => true,"uids" => ["15482888"]]
  130. ],
  131. "attr_key_value_map" => self::getAttrKeyValueMapParams('product',$goods),
  132. "sold_end_time" => time() + 180 * 86400,
  133. "sold_start_time" => time()
  134. ]
  135. ];
  136. }
  137. public static function getSkuParams($params)
  138. {
  139. $goods = Goods::where('id',$params['goods_id']??0)->findOrEmpty();
  140. if ($goods->isEmpty()) {
  141. return [];
  142. }
  143. $goods = $goods->toArray();
  144. // 查询商品信息
  145. return [
  146. "account_id" => '7511543640776017961',
  147. "product_out_id" => $params['goods_category_id']??0,
  148. "sku" => [
  149. [
  150. "out_sku_id"=> $goods['id'],
  151. "sku_name"=> $goods['name'],
  152. "origin_amount"=> $goods['service_total'] * 100,
  153. "actual_amount"=> $goods['service_fee'] * 100,
  154. "stock"=> [
  155. "limit_type"=> 2,
  156. "stock_qty"=> 9999
  157. ],
  158. "status"=> 1,
  159. "attr_key_value_map"=> self::getAttrKeyValueMapParams('sku',$goods)
  160. ]
  161. ]
  162. ];
  163. }
  164. public static function getAttrKeyValueMapParams($type,$params)
  165. {
  166. $res = [];
  167. if($type === 'product'){
  168. $res = [
  169. "appointment"=>json_encode([
  170. "need_appointment"=>true,
  171. "ahead_time_type"=>2,
  172. "ahead_hour_num"=> 5,
  173. "external_link"=>"pages/detail",
  174. "order_appointment_time_url"=>"pages/order"
  175. ]),
  176. "auto_renew"=>true,
  177. "can_no_use_date" => json_encode(["enable"=>false]),
  178. "Description" => json_encode([]),
  179. "image_list" => json_encode([["url"=>$params['goods_image']??'']]),
  180. "limit_use_rule" => json_encode(["is_limit_use"=>true, "use_num_per_consume"=>1]),
  181. "Notification" => json_encode([["title"=>$params['goods_name']??'',"content"=>$params['goods_name']??'']]),
  182. "RefundPolicy"=> "2",
  183. "refund_need_merchant_confirm"=> true,
  184. "show_channel"=> 1,
  185. "superimposed_discounts"=> false,
  186. "trade_url"=> json_encode(['app_id'=>config('douyin.appId'),'path'=>'pages/detail','params'=>json_encode(['goods_id'=>$params['id']??0])]),
  187. "use_date"=> json_encode(["use_date_type"=>2, "day_duration"=>15]),
  188. "use_time"=> json_encode(["use_time_type"=>1]),
  189. //"user_num_limit"=> ,
  190. "code_source_type"=> 3,
  191. "settle_type"=> 1,
  192. "use_type"=> 1,
  193. "limit_rule"=> json_encode(["is_limit"=>false]),
  194. "out_id"=> $params['id']??0
  195. ];
  196. }
  197. if($type === 'sku'){
  198. $res = [
  199. "code_source_type"=> 3,
  200. "limit_rule"=> json_encode(["is_limit"=>false]),
  201. "settle_type"=> 1
  202. ];
  203. }
  204. return $res;
  205. }
  206. // ******************************** 订单
  207. /**
  208. * 扩展点回调提交订单
  209. * @param $params
  210. * @throws \Exception
  211. * @author liugc <466014217@qq.com>
  212. * @date 2025/6/4 14:03
  213. */
  214. public static function submitOrderNotify($params)
  215. {
  216. try {
  217. // order_id goods total_amount discount cp_extra create_order_time phone_num contact_name open_id
  218. if(empty($params['user_info']['mobile'])){
  219. throw new \Exception('手机号不能为空!');
  220. }
  221. // goods_id user_info.mobile user_id quantity
  222. $order_number = self::submitOrder([
  223. 'goods_id'=>$params['goods'][0]['goods_id'],
  224. 'user_id'=>$params['user_id'],
  225. 'user_info'=>$params['user_info'],
  226. 'quantity'=>$params['goods'][0]['quantity']
  227. ]);
  228. return [
  229. "outOrderNo" => $order_number,
  230. "orderEntrySchema" => [
  231. "path" => "page/index/index",
  232. "params" => json_encode(['order_number' => $order_number])
  233. ],
  234. "payNotifyUrl" => config('douyin.payNotifyUrl')
  235. ];
  236. } catch (\Exception $e) {
  237. throw new \Exception($e->getMessage());
  238. }
  239. }
  240. /**
  241. * 提交订单
  242. * @param array $params goods_id user_info.mobile user_id quantity
  243. * @return array|false
  244. */
  245. public static function submitOrder($params)
  246. {
  247. Db::startTrans();
  248. try {
  249. $goods = Goods::findOrEmpty($params['goods_id']);
  250. if($goods->isEmpty()){
  251. throw new \Exception('产品不存在!');
  252. }
  253. if(empty($params['user_info']['mobile'])){
  254. throw new \Exception('请先补充您的联系方式后在提交订单');
  255. }
  256. // TODO tmp防抖1m
  257. $isExist = DouyinOrder::where(['user_id'=>$params['user_id'],'goods_id'=>$goods['id']])->where('create_time','>',(time() - 60))->findOrEmpty();
  258. if(!$isExist->isEmpty()){
  259. throw new \Exception('请勿重复下单!');
  260. }
  261. $quantity = $params['quantity']??1;
  262. //生成订单
  263. $create_data = [
  264. 'user_id' => $params['user_id'],
  265. 'mobile' => $params['user_info']['mobile'],
  266. 'title' => $goods['goods_name'],
  267. 'goods_id'=>$goods['id'],
  268. 'unit_price' => $goods['service_fee'],
  269. 'quantity' => $quantity,
  270. 'total_amount' => $goods['service_fee'] * $quantity,
  271. 'order_number' => generate_sn(DouyinOrder::class, 'order_number'),
  272. ];
  273. $order = DouyinOrder::create($create_data);
  274. Db::commit();
  275. return $create_data['order_number'];
  276. } catch (\Exception $e) {
  277. Db::rollback();
  278. throw new \Exception($e->getMessage());
  279. }
  280. }
  281. public static function getByteAuthorization($order_number)
  282. {
  283. /*{
  284. "skuList": [{
  285. "skuId": "商品ID",
  286. "price": 100,//单价-分
  287. "quantity": 1,
  288. "title": "商品标题",
  289. "imageList": ["https://cdn.weixiu.kyjlkj.com/uploads/images/20240914/202409141528015aeaa2357.png"],
  290. "type": 701,
  291. "tagGroupId": "tag_group_7272625659887960076"
  292. }],
  293. "outOrderNo": "202411121413333930",
  294. "totalAmount": 100,//分
  295. "orderEntrySchema": {
  296. "path": "page/path/index",
  297. "params": '{"id":1234, "name":"hello"}'
  298. },
  299. "payNotifyUrl": "https://weixiudev.kyjlkj.com/api/dou_yin/payNotify"
  300. }*/
  301. try {
  302. $douyinOrder = DouyinOrder::where('order_number',$order_number)->findOrEmpty();
  303. if($douyinOrder->isEmpty()){
  304. throw new \Exception('订单不存在!');
  305. }
  306. $order = $douyinOrder->toArray();
  307. $goods_image = Goods::where('id',$order['goods_id'])->value('goods_image')??'';
  308. $data = [
  309. "skuList" => [
  310. [
  311. "skuId" => (string)$order['goods_id'],
  312. "price" => $order['unit_price'] * 100,
  313. "quantity" => $order['quantity'],
  314. "title" => $order['title'],
  315. "imageList" => [$goods_image],
  316. "type" => 701,
  317. "tagGroupId" => "tag_group_7272625659887960076"
  318. ]
  319. ],
  320. "outOrderNo" => $order['order_number'],
  321. "totalAmount" => $order['total_amount'] * 100,
  322. "orderEntrySchema" => [
  323. "path" => "page/index/index",
  324. "params" => json_encode(['order_number' => $order['order_number']])
  325. ],
  326. "payNotifyUrl" => config('douyin.payNotifyUrl'),
  327. ];
  328. $byteAuthorization = self::byteAuthorization(config('douyin.privateKeyStr'), json_encode($data), config('douyin.appId'), self::randStr(10), time(), 1);
  329. return ['byteAuthorization'=>$byteAuthorization,'data'=>json_encode($data)];
  330. } catch (\Exception $e) {
  331. throw new \Exception($e->getMessage());
  332. }
  333. }
  334. public static function cancelOrder($params)
  335. {
  336. // $params['order_number']
  337. Db::startTrans();
  338. try {
  339. $order = DouyinOrder::where('order_number', $params['order_number'])->findOrEmpty();
  340. if(!$order->isEmpty()){
  341. if($order->order_status == 1 && $order->pay_status == 0){
  342. $order->order_status = 4;
  343. $order->save();
  344. }else{
  345. throw new \Exception('订单状态不可取消!');
  346. }
  347. }
  348. Db::commit();
  349. return $order['id'];
  350. } catch (\Exception $e) {
  351. Db::rollback();
  352. throw new \Exception($e->getMessage());
  353. }
  354. }
  355. public static function payNotify($params)
  356. {
  357. Log::write(json_encode($params));
  358. // 查询抖音订单是否完成支付
  359. if ($params['status'] === 'SUCCESS') {
  360. $transaction_id = $params['order_id']??'';
  361. $paid_amount = bcdiv(bcsub($params['total_amount'] ,$params['discount_amount']), '100', 2)??0;
  362. $out_order_no = $params['out_order_no'];
  363. $pay_time = $params['event_time']??time();
  364. $order = DouyinOrder::where('order_number', $out_order_no)->findOrEmpty();
  365. if(!$order->isEmpty()){
  366. // 更新充值订单状态
  367. $order->transaction_id = $transaction_id;
  368. $order->order_status = 2;
  369. $order->pay_time = $pay_time;
  370. $order->paid_amount = $paid_amount;
  371. $user = User::where('id',$order->user_id)->findOrEmpty()->toArray();
  372. $form_detail = [
  373. 'user_name' => $user['real_name']??'',
  374. 'mobile' => $user['mobile'],
  375. 'transaction_id' => $transaction_id,
  376. 'out_trade_no' => $out_order_no,
  377. 'paid_amount' => $paid_amount,
  378. 'params' => $params,
  379. ];
  380. $consultation = ExternalConsultation::create([
  381. 'external_platform_id' => self::$external_platform_id,
  382. 'form_detail' => json_encode($form_detail),
  383. 'user_name' => $user['real_name']??'',
  384. 'mobile' => $user['mobile'],
  385. 'goods_id' => $order->goods_id,
  386. 'amount' => $paid_amount
  387. ]);
  388. $order->consultation_id = $consultation->id;
  389. $order->save();
  390. return true;
  391. }
  392. }
  393. return false;
  394. }
  395. public static function reservation($params)
  396. {
  397. /*$lon_lat = get_address_lat_lng($params['user_address']);
  398. $params['lon'] = $lon_lat['lon'];
  399. $params['lat'] = $lon_lat['lat'];*/
  400. // $params['order_number']
  401. Db::startTrans();
  402. try {
  403. $order = DouyinOrder::where('order_number', $params['order_number'])->findOrEmpty();
  404. if(!$order->isEmpty()){
  405. $consultation = ExternalConsultation::where('id', $order->consultation_id)->findOrEmpty()->toArray();
  406. $consultation['user_name'] = $params['user_name']??$consultation['user_name'];
  407. $consultation['mobile'] = $params['mobile']??$consultation['mobile'];
  408. $consultation['user_address'] = $params['user_address'];
  409. $consultation['lon'] = $params['lon'];
  410. $consultation['lat'] = $params['lat'];
  411. $consultation['appointment_time'] = $params['appointment_time'];
  412. $result = ExternalConsultationLogic::order($consultation);
  413. if (false === $result) {
  414. throw new \Exception('预约失败');
  415. }
  416. $consultationOrder = ExternalConsultationOrder::where('consultation_id', $order->consultation_id)->where('goods_id', $order->goods_id)->where('amount', $order->paid_amount)
  417. ->findOrEmpty()->toArray();
  418. $work_status = ServiceWork::where('id', $consultationOrder['work_id'])->value('work_status');
  419. $order->work_id = $consultationOrder['work_id'];
  420. $order->fulfillment_status = $work_status;
  421. $order->save();
  422. }
  423. Db::commit();
  424. return $order['id'];
  425. } catch (\Exception $e) {
  426. Db::rollback();
  427. throw new \Exception($e->getMessage());
  428. }
  429. }
  430. public static function upReservation($params)
  431. {
  432. // $params['order_number']
  433. Db::startTrans();
  434. try {
  435. $order = DouyinOrder::where('order_number', $params['order_number'])->findOrEmpty();
  436. if(!$order->isEmpty()){
  437. // sn appointment_time
  438. $result = ServiceOrderLogic::approvalChangeAppointment(['sn'=>RechargeOrder::where('work_id', $order->work_id)->value('sn'),'appointment_time'=>$params['appointment_time']]);
  439. if (false === $result) {
  440. throw new \Exception(ServiceOrderLogic::getError());
  441. }
  442. $order->fulfillment_status = ServiceWork::where('id', $order->work_id)->value('work_status');
  443. $order->save();
  444. }
  445. Db::commit();
  446. return $order['id'];
  447. } catch (\Exception $e) {
  448. Db::rollback();
  449. throw new \Exception($e->getMessage());
  450. }
  451. }
  452. public static function getOrderDetail($params)
  453. {
  454. //抖音订单信息/商品信息/预约信息(地址、时间、履约状态与信息)
  455. // $params['order_number'] user_id
  456. $order = DouyinOrder::with(['goods','serviceWork','douyinRefundOrder'])->where('order_number', $params['order_number'])->where('user_id', $params['user_id'])->findOrEmpty();
  457. if($order->isEmpty()){
  458. return [];
  459. }
  460. $orderInfo = $order->toArray();
  461. empty($orderInfo['goods']) && $orderInfo['goods'] = [];
  462. empty($orderInfo['serviceWork']) && $orderInfo['serviceWork'] = [];
  463. empty($orderInfo['douyinRefundOrder']) && $orderInfo['douyinRefundOrder'] = [];
  464. $work_status = $orderInfo['serviceWork']['work_status']??0;
  465. $performance = [];
  466. // tmp
  467. switch ($work_status){
  468. case 0:
  469. $performance[] = ['status' => '待派单','title' => '待派单','time' => date('Y-m-d H:i:s',time())];
  470. break;
  471. case 1:
  472. case 2:
  473. case 3:
  474. $performance[] = ['status' => '待派单','title' => '待派单','time' => date('Y-m-d H:i:s',time())];
  475. $performance[] = ['status' => '已派单','title' => '已派单','time' => date('Y-m-d H:i:s',time())];
  476. break;
  477. case 4:
  478. case 5:
  479. case 6:
  480. $performance[] = ['status' => '待派单','title' => '待派单','time' => date('Y-m-d H:i:s',time())];
  481. $performance[] = ['status' => '已派单','title' => '已派单','time' => date('Y-m-d H:i:s',time())];
  482. $performance[] = ['status' => '服务中','title' => '服务中','time' => date('Y-m-d H:i:s',time())];
  483. break;
  484. case 7:
  485. case 8:
  486. $performance[] = ['status' => '待派单','title' => '待派单','time' => date('Y-m-d H:i:s',time())];
  487. $performance[] = ['status' => '已派单','title' => '已派单','time' => date('Y-m-d H:i:s',time())];
  488. $performance[] = ['status' => '服务中','title' => '服务中','time' => date('Y-m-d H:i:s',time())];
  489. $performance[] = ['status' => '已完结','title' => '已完结','time' => date('Y-m-d H:i:s',time())];
  490. break;
  491. }
  492. $orderInfo['performance'] = $performance;
  493. return $orderInfo;
  494. }
  495. public static function refund($params)
  496. {
  497. Db::startTrans();
  498. try {
  499. // $params['order_number'] user_id
  500. $order = DouyinOrder::with(['goods','serviceWork'])->where('order_number', $params['order_number'])->where('user_id', $params['user_id'])->findOrEmpty();
  501. if($order->isEmpty()){
  502. throw new \Exception('订单不存在');
  503. }
  504. $orderInfo = $order->toArray();
  505. $work_status = $orderInfo['serviceWork']['work_status']??0;
  506. if(3 < $work_status){
  507. throw new \Exception('该订单禁止退款');
  508. }
  509. DouyinRefundOrder::create([
  510. 'refund_number' => generate_sn(DouyinRefundOrder::class, 'refund_number'),
  511. 'order_number' => $orderInfo['order_number'],
  512. 'transaction_id' => $orderInfo['transaction_id'],
  513. 'reason' => $params['reason']??'',
  514. 'refund_status' => 0,
  515. 'user_id' => $orderInfo['user_id'],
  516. 'refund_amount' => $orderInfo['paid_amount'],
  517. ]);
  518. Db::commit();
  519. return true;
  520. } catch (\Exception $e) {
  521. Db::rollback();
  522. throw new \Exception($e->getMessage());
  523. }
  524. }
  525. public static function refundExamine($params)
  526. {
  527. Db::startTrans();
  528. try {
  529. // $params['order_number']
  530. $order = DouyinOrder::with(['goods','serviceWork'])->where('order_number', $params['order_number'])->findOrEmpty();
  531. if($order->isEmpty()){
  532. throw new \Exception('订单不存在');
  533. }
  534. $orderInfo = $order->toArray();
  535. //$refund_number = $params['refund_number']??'';
  536. $douyinRefundOrder = DouyinRefundOrder::where('order_number', $params['order_number'])->order('id', 'desc')->findOrEmpty();
  537. if($params['is_examine_ok'] === 'pass'){
  538. $douyinRefundOrder->refund_status = 2;
  539. RechargeOrder::where('work_id', $orderInfo['work_id'])->update([
  540. 'pay_status' => 2,
  541. 'pay_time' => 0,
  542. 'paid_amount' => 0,
  543. ]);
  544. ServiceWork::where('id', $orderInfo['work_id'])->update([
  545. 'work_status' => 0,
  546. 'user_confirm_status' => 0,
  547. 'service_status' => 4,
  548. 'work_pay_status' => 0
  549. ]);
  550. }else{
  551. $douyinRefundOrder->refund_status = 1;
  552. }
  553. $douyinRefundOrder->save();
  554. Db::commit();
  555. if($params['is_examine_ok'] === 'pass'){
  556. //通过后向抖音申请退款
  557. self::sendRefundCreate($params['order_number']);
  558. }
  559. return true;
  560. } catch (\Exception $e) {
  561. Db::rollback();
  562. throw new \Exception($e->getMessage());
  563. }
  564. }
  565. public static function sendRefundCreate($order_number)
  566. {
  567. try {
  568. // $params['order_number']
  569. $order = DouyinOrder::with(['goods','serviceWork'])->where('order_number', $order_number)->findOrEmpty();
  570. if($order->isEmpty()){
  571. throw new \Exception('订单不存在');
  572. }
  573. $orderInfo = $order->toArray();
  574. $douyinRefundOrder = DouyinRefundOrder::where('order_number', $order_number)->order('id', 'desc')->findOrEmpty();
  575. //通过后向抖音申请退款
  576. //getClientToken()
  577. $url = config('douyin.host').'api/trade_basic/v1/developer/refund_create/';
  578. $data = [
  579. "order_id" => $orderInfo['transaction_id'],
  580. "out_refund_no" => $douyinRefundOrder->refund_number,
  581. "cp_extra" => $orderInfo['id'].'|'.$douyinRefundOrder->id,
  582. "order_entry_schema" => [
  583. "path" => "page/index/index",
  584. "params" => json_encode(['refund_number'=>$douyinRefundOrder->refund_number])
  585. ],
  586. "refund_total_amount " => $douyinRefundOrder->refund_amount * 100,
  587. "notify_url" => config('douyin.refundNotifyUrl'),
  588. "refund_reason" => [
  589. [
  590. "code" => 101,
  591. "text" => "不想要了"
  592. ]
  593. ]
  594. ];
  595. $res = http_request($url,$data,['Content-Type' => 'application/json;charset=utf-8','access_token' => self::getClientToken()]);
  596. if(isset($res['err_msg']) && $res['err_msg'] === 'success'){
  597. $douyinRefundOrder->transaction_id = $res['data']['refund_id'];
  598. $douyinRefundOrder->save();
  599. }
  600. return true;
  601. } catch (\Exception $e) {
  602. Log::info($e->getMessage());
  603. return false;
  604. }
  605. }
  606. public static function refundNotify($params)
  607. {
  608. Db::startTrans();
  609. try {
  610. $douyinRefundOrder = DouyinRefundOrder::where('refund_number', $params['out_refund_no'])->findOrEmpty();
  611. if($douyinRefundOrder->isEmpty()){
  612. throw new \Exception('退款订单不存在');
  613. }
  614. if($douyinRefundOrder->refund_status == 0){
  615. if($params['status'] === 'SUCCESS'){
  616. $douyinRefundOrder->refund_status = 3;
  617. DouyinOrder::where('order_number', $douyinRefundOrder->order_number)->update([
  618. 'order_status' => 4,
  619. 'pay_status' => 3,
  620. ]);
  621. }elseif($params['status'] === 'FAIL'){
  622. $douyinRefundOrder->refund_status = 4;
  623. }else{
  624. throw new \Exception('退款状态未知');
  625. }
  626. $douyinRefundOrder->save();
  627. }
  628. Db::commit();
  629. return true;
  630. } catch (\Exception $e) {
  631. Db::rollback();
  632. throw new \Exception($e->getMessage());
  633. }
  634. }
  635. public static function byteAuthorization($privateKeyStr, $data, $appId, $nonceStr, $timestamp, $keyVersion) {
  636. $byteAuthorization = '';
  637. // 读取私钥
  638. $privateKey = openssl_pkey_get_private($privateKeyStr);
  639. if (!$privateKey) {
  640. throw new \Exception("Invalid private key");
  641. }
  642. // 生成签名
  643. $signature = self::getSignature("POST", "/requestOrder", $timestamp, $nonceStr, $data, $privateKey);
  644. if ($signature === false) {
  645. return null;
  646. }
  647. // 构造 byteAuthorization
  648. $byteAuthorization = sprintf("SHA256-RSA2048 appid=%s,nonce_str=%s,timestamp=%s,key_version=%s,signature=%s", $appId, $nonceStr, $timestamp, $keyVersion, $signature);
  649. return $byteAuthorization;
  650. }
  651. public static function getSignature($method, $url, $timestamp, $nonce, $data, $privateKey) {
  652. Log::info("method:{$method}\n url:{$url}\n timestamp:{$timestamp}\n nonce:{$nonce}\n data:{$data}");
  653. $targetStr = $method. "\n" . $url. "\n" . $timestamp. "\n" . $nonce. "\n" . $data. "\n";
  654. openssl_sign($targetStr, $sign, $privateKey, OPENSSL_ALGO_SHA256);
  655. $sign = base64_encode($sign);
  656. return $sign;
  657. }
  658. public static function randStr($length = 8) {
  659. $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  660. $str = '';
  661. for ($i = 0; $i < $length; $i++) {
  662. $str .= $chars[mt_rand(0, strlen($chars) - 1)];
  663. }
  664. return $str;
  665. }
  666. public static function getClientToken($isRefresh = false) {
  667. $url = config('douyin.host').'oauth/client_token/';
  668. $cache_name = 'dy_client_token';
  669. $cache_data = cache($cache_name);
  670. if(empty($cache_data) || $cache_data == null || $isRefresh){
  671. $data = [
  672. 'client_key'=> config('douyin.appId'),
  673. 'client_secret'=> config('douyin.appSecret'),
  674. 'grant_type'=> "client_credential"
  675. ];
  676. $res = http_request($url,$data,['Content-Type' => 'application/json;charset=utf-8']);
  677. Log::info(json_encode($res));
  678. if($res['message'] === 'success'){
  679. cache($cache_name, json_encode($res['data']), (time()+$res['data']['expires_in']-1));
  680. $cache_data = $res['data'];
  681. }
  682. }
  683. return $cache_data['access_token'];
  684. }
  685. }