DouYinService.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  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. * @return bool
  217. * @throws \Exception
  218. * @author liugc <466014217@qq.com>
  219. * @date 2025/6/4 14:03
  220. */
  221. public static function submitOrderNotify($params)
  222. {
  223. Db::startTrans();
  224. try {
  225. // order_id goods total_amount discount cp_extra create_order_time phone_num contact_name open_id
  226. /*$params
  227. "order_id": "614167279916",
  228. "goods": [
  229. {
  230. "img_url": "http://xxx",
  231. "title": "xxx",
  232. "sub_title": "xxx",
  233. "labels": "过期退|随时退",
  234. "date_rule": "xxx",
  235. "origin_price": 800,
  236. "price": 750,
  237. "quantity": 2,
  238. "poi_id": "",
  239. "goods_id": "xxx",
  240. "item_order_id_list": [
  241. "1xxx",
  242. "2xxx"
  243. ]
  244. }
  245. ],*/
  246. Db::commit();
  247. return true;
  248. } catch (\Exception $e) {
  249. Db::rollback();
  250. throw new \Exception($e->getMessage());
  251. }
  252. }
  253. /**
  254. * 提交订单
  255. * @param array $params
  256. * @return array|false
  257. */
  258. public static function submitOrder($params)
  259. {
  260. Db::startTrans();
  261. try {
  262. $goods = Goods::findOrEmpty($params['goods_id']);
  263. if($goods->isEmpty()){
  264. throw new \Exception('产品不存在!');
  265. }
  266. if(empty($params['user_info']['mobile'])){
  267. throw new \Exception('请先补充您的联系方式后在提交订单');
  268. }
  269. // TODO tmp防抖1m
  270. $isExist = DouyinOrder::where(['user_id'=>$params['user_id'],'goods_id'=>$goods['id']])->where('create_time','>',(time() - 60))->findOrEmpty();
  271. if(!$isExist->isEmpty()){
  272. throw new \Exception('请勿重复下单!');
  273. }
  274. $quantity = $params['quantity']??1;
  275. //生成订单
  276. $create_data = [
  277. 'user_id' => $params['user_id'],
  278. 'mobile' => $params['user_info']['mobile'],
  279. 'title' => $goods['goods_name'],
  280. 'goods_id'=>$goods['id'],
  281. 'unit_price' => $goods['service_fee'],
  282. 'quantity' => $quantity,
  283. 'total_amount' => $goods['service_fee'] * $quantity,
  284. 'order_number' => generate_sn(DouyinOrder::class, 'order_number'),
  285. ];
  286. $order = DouyinOrder::create($create_data);
  287. Db::commit();
  288. return $create_data['order_number'];
  289. } catch (\Exception $e) {
  290. Db::rollback();
  291. throw new \Exception($e->getMessage());
  292. }
  293. }
  294. public static function getByteAuthorization($order_number)
  295. {
  296. /*{
  297. "skuList": [{
  298. "skuId": "商品ID",
  299. "price": 100,//单价-分
  300. "quantity": 1,
  301. "title": "商品标题",
  302. "imageList": ["https://cdn.weixiu.kyjlkj.com/uploads/images/20240914/202409141528015aeaa2357.png"],
  303. "type": 701,
  304. "tagGroupId": "tag_group_7272625659887960076"
  305. }],
  306. "outOrderNo": "202411121413333930",
  307. "totalAmount": 100,//分
  308. "orderEntrySchema": {
  309. "path": "page/path/index",
  310. "params": '{"id":1234, "name":"hello"}'
  311. },
  312. "payNotifyUrl": "https://weixiudev.kyjlkj.com/api/dou_yin/payNotify"
  313. }*/
  314. try {
  315. $douyinOrder = DouyinOrder::where('order_number',$order_number)->findOrEmpty();
  316. if($douyinOrder->isEmpty()){
  317. throw new \Exception('订单不存在!');
  318. }
  319. $order = $douyinOrder->toArray();
  320. $goods_image = Goods::where('id',$order['goods_id'])->value('goods_image')??'';
  321. $data = [
  322. "skuList" => [
  323. [
  324. "skuId" => (string)$order['goods_id'],
  325. "price" => $order['unit_price'] * 100,
  326. "quantity" => $order['quantity'],
  327. "title" => $order['title'],
  328. "imageList" => [$goods_image],
  329. "type" => 701,
  330. "tagGroupId" => "tag_group_7272625659887960076"
  331. ]
  332. ],
  333. "outOrderNo" => $order['order_number'],
  334. "totalAmount" => $order['total_amount'] * 100,
  335. "orderEntrySchema" => [
  336. "path" => "page/index/index",
  337. "params" => json_encode(['order_number' => $order['order_number']])
  338. ],
  339. "payNotifyUrl" => config('douyin.payNotifyUrl'),
  340. ];
  341. $byteAuthorization = self::byteAuthorization(config('douyin.privateKeyStr'), json_encode($data), config('douyin.appId'), self::randStr(10), time(), 1);
  342. return ['byteAuthorization'=>$byteAuthorization,'data'=>json_encode($data)];
  343. } catch (\Exception $e) {
  344. throw new \Exception($e->getMessage());
  345. }
  346. }
  347. public static function cancelOrder($params)
  348. {
  349. // $params['order_number']
  350. Db::startTrans();
  351. try {
  352. $order = DouyinOrder::where('order_number', $params['order_number'])->findOrEmpty();
  353. if(!$order->isEmpty()){
  354. if($order->order_status == 1 && $order->pay_status == 0){
  355. $order->order_status = 4;
  356. $order->save();
  357. }else{
  358. throw new \Exception('订单状态不可取消!');
  359. }
  360. }
  361. Db::commit();
  362. return $order['id'];
  363. } catch (\Exception $e) {
  364. Db::rollback();
  365. throw new \Exception($e->getMessage());
  366. }
  367. }
  368. public static function payNotify($params)
  369. {
  370. Log::write(json_encode($params));
  371. // 查询抖音订单是否完成支付
  372. if ($params['status'] === 'SUCCESS') {
  373. $transaction_id = $params['order_id']??'';
  374. $paid_amount = bcdiv(bcsub($params['total_amount'] ,$params['discount_amount']), '100', 2)??0;
  375. $out_order_no = $params['out_order_no'];
  376. $pay_time = $params['event_time']??time();
  377. $order = DouyinOrder::where('order_number', $out_order_no)->findOrEmpty();
  378. if(!$order->isEmpty()){
  379. // 更新充值订单状态
  380. $order->transaction_id = $transaction_id;
  381. $order->order_status = 2;
  382. $order->pay_time = $pay_time;
  383. $order->paid_amount = $paid_amount;
  384. $user = User::where('id',$order->user_id)->findOrEmpty()->toArray();
  385. $form_detail = [
  386. 'user_name' => $user['real_name']??'',
  387. 'mobile' => $user['mobile'],
  388. 'transaction_id' => $transaction_id,
  389. 'out_trade_no' => $out_order_no,
  390. 'paid_amount' => $paid_amount,
  391. 'params' => $params,
  392. ];
  393. $consultation = ExternalConsultation::create([
  394. 'external_platform_id' => self::$external_platform_id,
  395. 'form_detail' => json_encode($form_detail),
  396. 'user_name' => $user['real_name']??'',
  397. 'mobile' => $user['mobile'],
  398. 'goods_id' => $order->goods_id,
  399. 'amount' => $paid_amount
  400. ]);
  401. $order->consultation_id = $consultation->id;
  402. $order->save();
  403. return true;
  404. }
  405. }
  406. return false;
  407. }
  408. public static function reservation($params)
  409. {
  410. /*$lon_lat = get_address_lat_lng($params['user_address']);
  411. $params['lon'] = $lon_lat['lon'];
  412. $params['lat'] = $lon_lat['lat'];*/
  413. // $params['order_number']
  414. Db::startTrans();
  415. try {
  416. $order = DouyinOrder::where('order_number', $params['order_number'])->findOrEmpty();
  417. if(!$order->isEmpty()){
  418. $consultation = ExternalConsultation::where('id', $order->consultation_id)->findOrEmpty()->toArray();
  419. $consultation['user_name'] = $params['user_name']??$consultation['user_name'];
  420. $consultation['mobile'] = $params['mobile']??$consultation['mobile'];
  421. $consultation['user_address'] = $params['user_address'];
  422. $consultation['lon'] = $params['lon'];
  423. $consultation['lat'] = $params['lat'];
  424. $consultation['appointment_time'] = $params['appointment_time'];
  425. $result = ExternalConsultationLogic::order($consultation);
  426. if (false === $result) {
  427. throw new \Exception('预约失败');
  428. }
  429. $consultationOrder = ExternalConsultationOrder::where('consultation_id', $order->consultation_id)->where('goods_id', $order->goods_id)->where('amount', $order->paid_amount)
  430. ->findOrEmpty()->toArray();
  431. $work_status = ServiceWork::where('id', $consultationOrder['work_id'])->value('work_status');
  432. $order->work_id = $consultationOrder['work_id'];
  433. $order->fulfillment_status = $work_status;
  434. $order->save();
  435. }
  436. Db::commit();
  437. return $order['id'];
  438. } catch (\Exception $e) {
  439. Db::rollback();
  440. throw new \Exception($e->getMessage());
  441. }
  442. }
  443. public static function upReservation($params)
  444. {
  445. // $params['order_number']
  446. Db::startTrans();
  447. try {
  448. $order = DouyinOrder::where('order_number', $params['order_number'])->findOrEmpty();
  449. if(!$order->isEmpty()){
  450. // sn appointment_time
  451. $result = ServiceOrderLogic::approvalChangeAppointment(['sn'=>RechargeOrder::where('work_id', $order->work_id)->value('sn'),'appointment_time'=>$params['appointment_time']]);
  452. if (false === $result) {
  453. throw new \Exception(ServiceOrderLogic::getError());
  454. }
  455. $order->fulfillment_status = ServiceWork::where('id', $order->work_id)->value('work_status');
  456. $order->save();
  457. }
  458. Db::commit();
  459. return $order['id'];
  460. } catch (\Exception $e) {
  461. Db::rollback();
  462. throw new \Exception($e->getMessage());
  463. }
  464. }
  465. public static function getOrderDetail($params)
  466. {
  467. //抖音订单信息/商品信息/预约信息(地址、时间、履约状态与信息)
  468. // $params['order_number'] user_id
  469. $order = DouyinOrder::with(['goods','serviceWork','douyinRefundOrder'])->where('order_number', $params['order_number'])->where('user_id', $params['user_id'])->findOrEmpty();
  470. if($order->isEmpty()){
  471. return [];
  472. }
  473. $orderInfo = $order->toArray();
  474. empty($orderInfo['goods']) && $orderInfo['goods'] = [];
  475. empty($orderInfo['serviceWork']) && $orderInfo['serviceWork'] = [];
  476. empty($orderInfo['douyinRefundOrder']) && $orderInfo['douyinRefundOrder'] = [];
  477. $work_status = $orderInfo['serviceWork']['work_status']??0;
  478. $performance = [];
  479. // tmp
  480. switch ($work_status){
  481. case 0:
  482. $performance[] = ['status' => '待派单','title' => '待派单','time' => date('Y-m-d H:i:s',time())];
  483. break;
  484. case 1:
  485. case 2:
  486. case 3:
  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 4:
  491. case 5:
  492. case 6:
  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. case 7:
  498. case 8:
  499. $performance[] = ['status' => '待派单','title' => '待派单','time' => date('Y-m-d H:i:s',time())];
  500. $performance[] = ['status' => '已派单','title' => '已派单','time' => date('Y-m-d H:i:s',time())];
  501. $performance[] = ['status' => '服务中','title' => '服务中','time' => date('Y-m-d H:i:s',time())];
  502. $performance[] = ['status' => '已完结','title' => '已完结','time' => date('Y-m-d H:i:s',time())];
  503. break;
  504. }
  505. $orderInfo['performance'] = $performance;
  506. return $orderInfo;
  507. }
  508. public static function refund($params)
  509. {
  510. Db::startTrans();
  511. try {
  512. // $params['order_number'] user_id
  513. $order = DouyinOrder::with(['goods','serviceWork'])->where('order_number', $params['order_number'])->where('user_id', $params['user_id'])->findOrEmpty();
  514. if($order->isEmpty()){
  515. throw new \Exception('订单不存在');
  516. }
  517. $orderInfo = $order->toArray();
  518. $work_status = $orderInfo['serviceWork']['work_status']??0;
  519. if(3 < $work_status){
  520. throw new \Exception('该订单禁止退款');
  521. }
  522. DouyinRefundOrder::create([
  523. 'refund_number' => generate_sn(DouyinRefundOrder::class, 'refund_number'),
  524. 'order_number' => $orderInfo['order_number'],
  525. 'transaction_id' => $orderInfo['transaction_id'],
  526. 'reason' => $params['reason']??'',
  527. 'refund_status' => 0,
  528. 'user_id' => $orderInfo['user_id'],
  529. 'refund_amount' => $orderInfo['paid_amount'],
  530. ]);
  531. Db::commit();
  532. return true;
  533. } catch (\Exception $e) {
  534. Db::rollback();
  535. throw new \Exception($e->getMessage());
  536. }
  537. }
  538. public static function refundExamine($params)
  539. {
  540. Db::startTrans();
  541. try {
  542. // $params['order_number']
  543. $order = DouyinOrder::with(['goods','serviceWork'])->where('order_number', $params['order_number'])->findOrEmpty();
  544. if($order->isEmpty()){
  545. throw new \Exception('订单不存在');
  546. }
  547. $orderInfo = $order->toArray();
  548. //$refund_number = $params['refund_number']??'';
  549. $douyinRefundOrder = DouyinRefundOrder::where('order_number', $params['order_number'])->order('id', 'desc')->findOrEmpty();
  550. if($params['is_examine_ok'] === 'pass'){
  551. $douyinRefundOrder->refund_status = 2;
  552. RechargeOrder::where('work_id', $orderInfo['work_id'])->update([
  553. 'pay_status' => 2,
  554. 'pay_time' => 0,
  555. 'paid_amount' => 0,
  556. ]);
  557. ServiceWork::where('id', $orderInfo['work_id'])->update([
  558. 'work_status' => 0,
  559. 'user_confirm_status' => 0,
  560. 'service_status' => 4,
  561. 'work_pay_status' => 0
  562. ]);
  563. }else{
  564. $douyinRefundOrder->refund_status = 1;
  565. }
  566. $douyinRefundOrder->save();
  567. Db::commit();
  568. if($params['is_examine_ok'] === 'pass'){
  569. //通过后向抖音申请退款
  570. self::sendRefundCreate($params['order_number']);
  571. }
  572. return true;
  573. } catch (\Exception $e) {
  574. Db::rollback();
  575. throw new \Exception($e->getMessage());
  576. }
  577. }
  578. public static function sendRefundCreate($order_number)
  579. {
  580. try {
  581. // $params['order_number']
  582. $order = DouyinOrder::with(['goods','serviceWork'])->where('order_number', $order_number)->findOrEmpty();
  583. if($order->isEmpty()){
  584. throw new \Exception('订单不存在');
  585. }
  586. $orderInfo = $order->toArray();
  587. $douyinRefundOrder = DouyinRefundOrder::where('order_number', $order_number)->order('id', 'desc')->findOrEmpty();
  588. //通过后向抖音申请退款
  589. //getClientToken()
  590. $url = config('douyin.host').'api/trade_basic/v1/developer/refund_create/';
  591. $data = [
  592. "order_id" => $orderInfo['transaction_id'],
  593. "out_refund_no" => $douyinRefundOrder->refund_number,
  594. "cp_extra" => $orderInfo['id'].'|'.$douyinRefundOrder->id,
  595. "order_entry_schema" => [
  596. "path" => "page/index/index",
  597. "params" => json_encode(['refund_number'=>$douyinRefundOrder->refund_number])
  598. ],
  599. "refund_total_amount " => $douyinRefundOrder->refund_amount * 100,
  600. "notify_url" => config('douyin.refundNotifyUrl'),
  601. "refund_reason" => [
  602. [
  603. "code" => 101,
  604. "text" => "不想要了"
  605. ]
  606. ]
  607. ];
  608. $res = http_request($url,$data,['Content-Type' => 'application/json;charset=utf-8','access_token' => self::getClientToken()]);
  609. if(isset($res['err_msg']) && $res['err_msg'] === 'success'){
  610. $douyinRefundOrder->transaction_id = $res['data']['refund_id'];
  611. $douyinRefundOrder->save();
  612. }
  613. return true;
  614. } catch (\Exception $e) {
  615. Log::info($e->getMessage());
  616. return false;
  617. }
  618. }
  619. public static function refundNotify($params)
  620. {
  621. Db::startTrans();
  622. try {
  623. $douyinRefundOrder = DouyinRefundOrder::where('refund_number', $params['out_refund_no'])->findOrEmpty();
  624. if($douyinRefundOrder->isEmpty()){
  625. throw new \Exception('退款订单不存在');
  626. }
  627. if($douyinRefundOrder->refund_status == 0){
  628. if($params['status'] === 'SUCCESS'){
  629. $douyinRefundOrder->refund_status = 3;
  630. DouyinOrder::where('order_number', $douyinRefundOrder->order_number)->update([
  631. 'order_status' => 4,
  632. 'pay_status' => 3,
  633. ]);
  634. }elseif($params['status'] === 'FAIL'){
  635. $douyinRefundOrder->refund_status = 4;
  636. }else{
  637. throw new \Exception('退款状态未知');
  638. }
  639. $douyinRefundOrder->save();
  640. }
  641. Db::commit();
  642. return true;
  643. } catch (\Exception $e) {
  644. Db::rollback();
  645. throw new \Exception($e->getMessage());
  646. }
  647. }
  648. public static function byteAuthorization($privateKeyStr, $data, $appId, $nonceStr, $timestamp, $keyVersion) {
  649. $byteAuthorization = '';
  650. // 读取私钥
  651. $privateKey = openssl_pkey_get_private($privateKeyStr);
  652. if (!$privateKey) {
  653. throw new \Exception("Invalid private key");
  654. }
  655. // 生成签名
  656. $signature = self::getSignature("POST", "/requestOrder", $timestamp, $nonceStr, $data, $privateKey);
  657. if ($signature === false) {
  658. return null;
  659. }
  660. // 构造 byteAuthorization
  661. $byteAuthorization = sprintf("SHA256-RSA2048 appid=%s,nonce_str=%s,timestamp=%s,key_version=%s,signature=%s", $appId, $nonceStr, $timestamp, $keyVersion, $signature);
  662. return $byteAuthorization;
  663. }
  664. public static function getSignature($method, $url, $timestamp, $nonce, $data, $privateKey) {
  665. Log::info("method:{$method}\n url:{$url}\n timestamp:{$timestamp}\n nonce:{$nonce}\n data:{$data}");
  666. $targetStr = $method. "\n" . $url. "\n" . $timestamp. "\n" . $nonce. "\n" . $data. "\n";
  667. openssl_sign($targetStr, $sign, $privateKey, OPENSSL_ALGO_SHA256);
  668. $sign = base64_encode($sign);
  669. return $sign;
  670. }
  671. public static function randStr($length = 8) {
  672. $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  673. $str = '';
  674. for ($i = 0; $i < $length; $i++) {
  675. $str .= $chars[mt_rand(0, strlen($chars) - 1)];
  676. }
  677. return $str;
  678. }
  679. public static function getClientToken($isRefresh = false) {
  680. $url = config('douyin.host').'oauth/client_token/';
  681. $cache_name = 'dy_client_token';
  682. $cache_data = cache($cache_name);
  683. if(empty($cache_data) || $cache_data == null || $isRefresh){
  684. $data = [
  685. 'client_key'=> config('douyin.appId'),
  686. 'client_secret'=> config('douyin.appSecret'),
  687. 'grant_type'=> "client_credential"
  688. ];
  689. $res = http_request($url,$data,['Content-Type' => 'application/json;charset=utf-8']);
  690. Log::info(json_encode($res));
  691. if($res['message'] === 'success'){
  692. cache($cache_name, json_encode($res['data']), (time()+$res['data']['expires_in']-1));
  693. $cache_data = $res['data'];
  694. }
  695. }
  696. return $cache_data['access_token'];
  697. }
  698. }