Test.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. <?php
  2. namespace app\controller\api;
  3. use app\common\enum\CommonEnum;
  4. use app\common\repositories\merchant\order\OrderMerchantRepository;
  5. use app\common\repositories\shared\SharedProsperityRecommendConfigRepository;
  6. use app\common\repositories\user\UserRepository;
  7. use app\services\ThirdParty\AlibabaAgent\OrderService;
  8. use app\services\ThirdParty\AlibabaAgent\ProductService;
  9. use applet\WXBizDataCrypt;
  10. use think\facade\Db;
  11. /**
  12. * 1688分销严选采购解决方案 - 接口调用示例
  13. *
  14. * 使用前请确保 config/third_party.php 中已配置 alibaba_agent 项:
  15. * 'alibaba_agent' => [
  16. * 'appKey' => '你的AppKey',
  17. * 'appSecret' => '你的AppSecret',
  18. * 'gatewayUrl' => 'https://gw.open.1688.com/openapi/',
  19. * ]
  20. *
  21. * access_token 通过 OAuth 2.0 授权获取,或由用户提供。
  22. */
  23. class Test
  24. {
  25. /**
  26. * 1688分销商品列表 - 调用示例
  27. *
  28. * API: com.alibaba.fenxiao:jxhy.product.getPageList-1
  29. * 文档: https://open.1688.com/api/apidocdetail.htm?id=com.alibaba.fenxiao%3Ajxhy.product.getPageList-1
  30. */
  31. public function test()
  32. {
  33. $json = [
  34. 'created_time' => '1775884033',
  35. 'data' => [
  36. 'app_id' => 'app_44108546-d27a-48ee-88c1-84b45b75114f',
  37. 'business_mode' => '00',
  38. 'created_time' => '20260411130713',
  39. 'description' => '',
  40. 'end_time' => '20260411130724',
  41. 'expend' => [
  42. 'buyer_logon_id' => '131****9459',
  43. 'cashPayAmt' => '298.00',
  44. 'open_id' => '2088702188085230',
  45. 'sub_open_id' => '2088702188085230',
  46. ],
  47. 'fee_amt' => '1.13',
  48. 'id' => '002212026041113071210888906215589441536',
  49. 'order_no' => 'ALI177588403255323243_466',
  50. 'out_trans_id' => '2026041123001485231459472633',
  51. 'party_order_id' => '02232604114723298914940',
  52. 'pay_amt' => '298.00',
  53. 'pay_channel' => 'alipay_pub',
  54. 'real_amt' => '298.00',
  55. 'status' => 'succeeded',
  56. 'trans_response_add_info' => [
  57. 'fund_bill_list' => [
  58. [
  59. 'amount' => '298.00',
  60. 'fund_channel' => 'ALIPAYACCOUNT',
  61. ],
  62. ],
  63. ],
  64. ],
  65. 'prod_mode' => 'true',
  66. 'sign' => 'fgbSc95NQDor1/jH3/L0G55l3XB7wl+sDt45Mtig/8eSvLIVo0uoyyD+jWaLkXV5xY2iAV3w8W4tiyVUcMQwVvwDIt9zQ44HTo05ng0e6CHCXLxFQbg/SHsjmK/3hin/2t6HkEjlitJYVikcPxMA0vnlR+lL/xMOYqNMDuq9oQQ=',
  67. 'id' => '002210888906265044500480',
  68. 'type' => 'HF',
  69. 'app_id' => 'app_44108546-d27a-48ee-88c1-84b45b75114f',
  70. 'object' => 'payment',
  71. ];
  72. /** @var OrderMerchantRepository $orderMerchantRepository */
  73. $orderMerchantRepository = app()->make(OrderMerchantRepository::class);
  74. $res = $orderMerchantRepository->doNotifyHF($json['data']);
  75. dd($res);
  76. die;
  77. $orderService = new OrderService();
  78. //
  79. //
  80. // $orderId = '3298535043727138963';
  81. // $payRes = $orderService->prepareProtocolPay(['orderId'=>$orderId]);
  82. // dd($payRes);
  83. $cargoParamList = '{"offerId":"1045816431082","specId":"2fc39c573acfab640d10bcb1b533f041","quantity":1}';
  84. $addressParam = '{"fullName":"测试","mobile":"17756507016","provinceText":"河北省","cityText":"廊坊市","areaText":"三河市","address":"兴远高科产业园23号楼2层210"}';
  85. $cargoParamList = json_decode($cargoParamList,true);
  86. $addressParam = json_decode($addressParam,true);
  87. $flow = 'general';
  88. $res = $orderService->previewOrder(['cargoParamList' => $cargoParamList, 'addressParam' => $addressParam,'flow'=>$flow]);
  89. dd($res);
  90. /** @var SharedProsperityRecommendConfigRepository $sharedProsperityRecommendConfigRepository */
  91. $sharedProsperityRecommendConfigRepository = app()->make(SharedProsperityRecommendConfigRepository::class);
  92. // 共富配置--获取最大的直推奖比例
  93. $sharedProsperityRecommendConfigEntityByMaxRewardRatio = $sharedProsperityRecommendConfigRepository->getSharedProsperityRecommendConfigEntityByMaxRewardRatio();
  94. // 共富配置--获取最大的分享奖比例
  95. $sharedProsperityRecommendConfigEntityByMaxShareRewardRatio = $sharedProsperityRecommendConfigRepository->getSharedProsperityRecommendConfigEntityByMaxShareRatio();
  96. // 利润 减去 顶格的直推奖,剩下的是PV值
  97. $sharPveRate = bcadd($sharedProsperityRecommendConfigEntityByMaxRewardRatio->getRewardRatio(),$sharedProsperityRecommendConfigEntityByMaxShareRewardRatio->getShareRatio(), CommonEnum::DECIMAL_PLACES_OF_THE_AMOUNT);
  98. $pvProportion = bcsub('1', bcdiv($sharPveRate, '100', 4), 2);
  99. dd($pvProportion);
  100. $orderShareUid = 6;
  101. $ShareUser = Db::name('shared_prosperity_user')->where(["user_id" => $orderShareUid])->find();
  102. if ($ShareUser) {
  103. $rate = Db::name('shared_prosperity_recommend_config')->where(["level" => $ShareUser['partner_level']])->value("share_ratio");
  104. $rate = $rate / 100;
  105. }else{
  106. // 计算 佣金
  107. $user_group_share_rate = Db::name("system_config_value")->where(["config_key" => "user_group_share_rate"])->value("value");
  108. $user_group_share_rate = json_decode($user_group_share_rate, true);
  109. $user_group_share_rate = array_column($user_group_share_rate, 'rate', 'user_groub');
  110. /** @var UserRepository $userRepository */
  111. $userRepository = app()->make(UserRepository::class);
  112. $userEntityByShareUserEntity = $userRepository->getUserEntityByUid($orderShareUid);
  113. $userGroup = $userEntityByShareUserEntity->getUserGroup();
  114. $rate = ($user_group_share_rate[$userGroup] ?? 0) / 100;
  115. }
  116. dd($rate);
  117. die;
  118. $data = [
  119. 'orderId' => '123', // 1688订单号,接口里
  120. 'orderEntryIds' => '123',// 1688子订单号,接口里
  121. 'disputeRequest' => 'refund', // 单选
  122. 'description' => '不想要了', // 填写的
  123. 'applyPayment' => '4.82', // 退款金额,接口里
  124. 'applyCarriage' => '0', // 运费金额,接口里
  125. 'applyReasonId' => '20006', // 退款原因,选的
  126. 'goodsStatus' => 'refundWaitBuyerReceive', // 货物状态,接口里
  127. 'refund_order_id' => 33 // 列表的refund_order_id
  128. ];
  129. $orderService = new OrderService();
  130. // 构建1688接口参数(前端 disputeRequest 映射为 1688 接口的 disputeReasonId)
  131. $params = [
  132. 'orderId' => (string)$data['orderId'],
  133. 'orderEntryIds' => $data['orderEntryIds'],
  134. 'disputeReasonId' => (string)$data['disputeRequest'],
  135. 'description' => (string)$data['description'],
  136. 'applyPayment' => (string)$data['applyPayment'] * 100,
  137. 'applyCarriage' => (string)$data['applyCarriage'] * 100,
  138. 'applyReasonId' => (string)$data['applyReasonId'],
  139. 'goodsStatus' => (string)$data['goodsStatus'],
  140. ];
  141. // 调用1688 API提交售后申请
  142. $result = $orderService->createRefund($params);
  143. // 记录到 store_refund_alibaba 表(不管成功与否都保存原始数据)
  144. $insertData = [
  145. 'refund_order_id' => (int)($data['refund_order_id'] ?? 0),
  146. 'alibaba_order_id' => (string)$data['orderId'],
  147. 'order_entry_ids' => $data['orderEntryIds'],
  148. 'dispute_reason_id' => (string)$data['disputeRequest'],
  149. 'description' => (string)$data['description'],
  150. 'goods_status' => (string)$data['goodsStatus'],
  151. 'apply_payment' => (string)$data['applyPayment'],
  152. 'apply_carriage' => (string)$data['applyCarriage'],
  153. 'result_data' => json_encode($result['rawData'] ?? [], JSON_UNESCAPED_UNICODE),
  154. ];
  155. if ($result['success']) {
  156. // 提交成功
  157. $insertData['status'] = 1;
  158. $insertData['alibaba_refund_id'] = $result['refundId'] ?? '';
  159. $insertData['alibaba_status'] = $result['status'] ?? '';
  160. Db::name('store_refund_alibaba')->insert($insertData);
  161. // 更新退款单的 after_sn 字段为1688售后单ID
  162. if (!empty($data['refund_order_id']) && !empty($result['refundId'])) {
  163. Db::name('store_refund_order')
  164. ->where('refund_order_id', (int)$data['refund_order_id'])
  165. ->update(['after_sn' => $result['refundId']]);
  166. }
  167. return app('json')->success([
  168. 'alibaba_refund_id' => $result['refundId'] ?? '',
  169. 'alibaba_status' => $result['status'] ?? '',
  170. ], '提交1688售后申请成功');
  171. } else {
  172. // 提交失败
  173. $insertData['status'] = 2;
  174. $insertData['fail_message'] = $result['status'] ?? '1688接口调用失败';
  175. Db::name('store_refund_alibaba')->insert($insertData);
  176. return app('json')->fail($result['status'] ?? '提交1688售后申请失败');
  177. }
  178. // $alibabaOrderId = '3300284931845138963';
  179. // $orderService = new OrderService();
  180. // $result = $orderService->getRefundReasonList(['orderId' => $alibabaOrderId]);
  181. // dd($result);
  182. die;
  183. // $id = $this->request->params(['pid'])['pid'];
  184. $id = request()->params(['pid'])['pid'];
  185. if (!$id) {
  186. return app('json')->fail('参数不正确');
  187. }
  188. dd(request());
  189. $appid = 'wx9082e5ac2fdb513f';
  190. $sessionKey =str_replace(' ','+', 'AIXeWyu4hRRg0EkD8Z23JA==');
  191. $encryptedData=str_replace(' ','+','7OCmD5\/4xylVdxYswuTrA6TKzmXNkDymIpdyx9GZIBS+qCIcsBpUnJ5U5GXOTn0JvfQYic9e+0idCTP7QJyJkjjlGWNwwiE0\/WnhBvhAWYlo+Hkh+v3ioiSvqJ7zC4bEJ3GWDNyts5fEX\/u+tL25DySDuUoDoCJs6k+ThlVO5NiecPIcgnmfrLG6nV4Xh3y9H6p\/loj71LRJ47hywX9OQg==');
  192. $iv =str_replace(' ','+', 'NbjIV0k1DyDWxU7JSSF44w==');
  193. $pc = new WXBizDataCrypt($appid, $sessionKey);
  194. $errCode = $pc->decryptData($encryptedData, $iv, $data );
  195. dd($errCode);
  196. die;
  197. die;
  198. // ============================================================
  199. // 通过 ProductService 调用 1688 分销商品列表
  200. // ============================================================
  201. try {
  202. /** @var ProductService $productService */
  203. $productService = app()->make(ProductService::class);
  204. // 设置 access_token(由用户提供或通过OAuth获取)
  205. $productService->setAccessToken('dc8eab20-f10f-4688-9e45-9ebfa182c7c2');
  206. // 搜索参数
  207. $params = [
  208. 'page' => 1, // 页码
  209. 'limit' => 50, // 每页条数(最大50)
  210. ];
  211. $result = $productService->searchProducts($params);
  212. if ($result === false) {
  213. echo "请求失败,请查看日志获取详细信息。\n";
  214. } else {
  215. echo "=== 1688分销商品列表 ===\n";
  216. echo "总数: {$result['total']}\n";
  217. echo "页码: {$result['page']}\n";
  218. echo "每页: {$result['pageSize']}\n";
  219. echo "商品数: " . count($result['list']) . "\n\n";
  220. foreach ($result['list'] as $i => $product) {
  221. echo ($i + 1) . ". {$product['title']}\n";
  222. echo " 商品ID: {$product['productId']}\n";
  223. echo " 价格: ¥{$product['minPrice']} ~ ¥{$product['maxPrice']}\n";
  224. echo " 月销: {$product['monthSales']}\n";
  225. echo " 主图: {$product['mainImage']}\n\n";
  226. }
  227. }
  228. } catch (\Throwable $e) {
  229. echo "错误: " . $e->getMessage() . "\n";
  230. echo "文件: " . $e->getFile() . " (行 " . $e->getLine() . ")\n";
  231. }
  232. die;
  233. }
  234. public function posttest()
  235. {
  236. $sessionKey = request()->post(['sessionKey']);
  237. $encryptedData = request()->post(['encryptedData']);
  238. $iv = request()->post(['iv']);
  239. $appid = 'wx9082e5ac2fdb513f';
  240. $sessionKey =str_replace(' ','+', stripslashes($sessionKey['sessionKey']));
  241. $encryptedData=str_replace(' ','+',$encryptedData['encryptedData']);
  242. $iv =str_replace(' ','+', stripslashes($iv['iv']));
  243. // $sessionKey =str_replace(' ','+', $sessionKey['sessionKey']);
  244. // $encryptedData=str_replace(' ','+',$encryptedData['encryptedData']);
  245. // $iv =str_replace(' ','+', $iv['iv']);
  246. $pc = new WXBizDataCrypt($appid, $sessionKey);
  247. $errCode = $pc->decryptData($encryptedData, $iv, $data );
  248. dd($errCode);
  249. }
  250. /**
  251. * 直接调用示例(不通过ProductService,展示完整流程)
  252. */
  253. public function direct()
  254. {
  255. $host = 'https://gw.open.1688.com/openapi/';
  256. $appKey = '6512262';
  257. $appSecret = 'uNPRZE7895';
  258. $accessToken = 'dc8eab20-f10f-4688-9e45-9ebfa182c7c2';
  259. $version = 1;
  260. $namespace = 'com.alibaba.fenxiao';
  261. $apiName = 'jxhy.product.getPageList';
  262. // 1. 构建URL
  263. $param = "param2/{$version}/";
  264. $path = "{$namespace}/{$apiName}/{$appKey}";
  265. $url = $host . $param . $path;
  266. // 2. 请求参数
  267. $data = [
  268. 'access_token' => $accessToken,
  269. 'pageNo' => 1,
  270. 'pageSize' => 10,
  271. ];
  272. // 3. 生成签名
  273. $aliParams = [];
  274. foreach ($data as $key => $val) {
  275. $aliParams[] = $key . $val;
  276. }
  277. sort($aliParams);
  278. $signStr = $param . $path . join('', $aliParams);
  279. $data['_aop_signature'] = strtoupper(bin2hex(
  280. hash_hmac("sha1", $signStr, $appSecret, true)
  281. ));
  282. // 4. 发送POST请求
  283. $ch = curl_init();
  284. curl_setopt($ch, CURLOPT_URL, $url);
  285. curl_setopt($ch, CURLOPT_POST, true);
  286. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  287. curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
  288. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  289. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  290. $response = curl_exec($ch);
  291. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  292. curl_close($ch);
  293. $result = json_decode($response, true);
  294. echo "HTTP状态码: {$httpCode}\n";
  295. dump($result);
  296. die;
  297. }
  298. /**
  299. * 1688分销商品详情 - 调用示例
  300. *
  301. * API: com.alibaba.fenxiao:alibaba.pifatuan.product.detail.list-2
  302. * 文档: https://open.1688.com/api/apidocdetail.htm?id=com.alibaba.fenxiao%3Aalibaba.pifatuan.product.detail.list-2
  303. */
  304. public function detail()
  305. {
  306. try {
  307. /** @var ProductService $productService */
  308. $productService = app()->make(ProductService::class);
  309. // 设置 access_token
  310. $productService->setAccessToken('dc8eab20-f10f-4688-9e45-9ebfa182c7c2');
  311. // 商品ID(从列表接口获取到的 itemId)
  312. $productId = 642639328505;
  313. echo "=== 获取商品详情 ===\n";
  314. echo "商品ID: {$productId}\n\n";
  315. $result = $productService->getProductDetail($productId);
  316. echo "=== 原始返回 ===\n";
  317. var_dump($result);
  318. echo "\n";
  319. if ($result === false) {
  320. echo "请求失败,请查看日志获取详细信息。\n";
  321. } else {
  322. echo "=== 商品详情结果 ===\n";
  323. echo "标题: " . ($result['title'] ?? 'N/A') . "\n";
  324. echo "商品ID: " . ($result['productId'] ?? 'N/A') . "\n";
  325. echo "价格: ¥" . ($result['minPrice'] ?? 0) . " ~ ¥" . ($result['maxPrice'] ?? 0) . "\n";
  326. echo "库存: " . ($result['stock'] ?? 0) . "\n";
  327. echo "主图: " . ($result['mainImage'] ?? 'N/A') . "\n";
  328. echo "SKU数: " . (isset($result['skuList']) ? count($result['skuList']) : 0) . "\n";
  329. echo "图片数: " . (isset($result['imageList']) ? count($result['imageList']) : 0) . "\n";
  330. }
  331. } catch (\Throwable $e) {
  332. echo "错误: " . $e->getMessage() . "\n";
  333. echo "文件: " . $e->getFile() . " (行 " . $e->getLine() . ")\n";
  334. }
  335. die;
  336. }
  337. }