DouYinService.php 31 KB

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