Test.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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\UserAddressRepository;
  7. use app\common\repositories\user\UserRepository;
  8. use app\services\ThirdParty\AlibabaAgent\OrderService;
  9. use app\services\ThirdParty\AlibabaAgent\ProductService;
  10. use applet\WXBizDataCrypt;
  11. use think\facade\Db;
  12. /**
  13. * 1688分销严选采购解决方案 - 接口调用示例
  14. *
  15. * 使用前请确保 config/third_party.php 中已配置 alibaba_agent 项:
  16. * 'alibaba_agent' => [
  17. * 'appKey' => '你的AppKey',
  18. * 'appSecret' => '你的AppSecret',
  19. * 'gatewayUrl' => 'https://gw.open.1688.com/openapi/',
  20. * ]
  21. *
  22. * access_token 通过 OAuth 2.0 授权获取,或由用户提供。
  23. */
  24. class Test
  25. {
  26. /**
  27. * 1688分销商品列表 - 调用示例
  28. *
  29. * API: com.alibaba.fenxiao:jxhy.product.getPageList-1
  30. * 文档: https://open.1688.com/api/apidocdetail.htm?id=com.alibaba.fenxiao%3Ajxhy.product.getPageList-1
  31. */
  32. public function test()
  33. {
  34. // ============================================================
  35. // 功能:从本地 store_product 表读取 is_alibaba=1 的商品
  36. // → 根据 spu_id(1688商品ID)查询1688商品详情
  37. // → 获取分类ID → 重复调用1688分类接口向上追溯
  38. // → 直到 parentIDs=[0](顶级分类)
  39. // → 将顶级分类保存到 store_category 表(按 alibaba_cate_id 去重)
  40. // → 更新商品的 cate_id
  41. // ============================================================
  42. try {
  43. /** @var ProductService $productService */
  44. $productService = app()->make(ProductService::class);
  45. $productService->setAccessToken('ce15fc70-b462-43bf-acc3-f87e43c858ba');
  46. // ============================================================
  47. // 第一步:从 store_product 表读取 is_alibaba=1 的商品
  48. // ============================================================
  49. echo "========== 第一步:读取本地1688商品列表 ==========\n";
  50. $productList = Db::name('store_product')
  51. ->where('is_alibaba', 1)
  52. ->where('cate_id', 0)
  53. ->where('is_del', 0)
  54. ->field('product_id, store_name, spu_id, image, price, is_alibaba')
  55. ->limit(50)
  56. ->select()
  57. ->toArray();
  58. if (empty($productList)) {
  59. echo "没有找到 is_alibaba=1 的商品\n";
  60. die;
  61. }
  62. echo "共找到 " . count($productList) . " 个1688商品\n\n";
  63. foreach ($productList as $i => $product) {
  64. echo ($i + 1) . ". {$product['store_name']}\n";
  65. echo " 本地商品ID: {$product['product_id']}\n";
  66. echo " 1688商品ID(spu_id): {$product['spu_id']}\n";
  67. echo " 价格: ¥{$product['price']}\n\n";
  68. }
  69. // ============================================================
  70. // 第二步+第三步+第四步:遍历商品,查询详情 → 追溯分类层级 → 保存顶级分类
  71. // ============================================================
  72. echo "========== 第二步:查询1688商品详情,获取分类ID ==========\n\n";
  73. foreach ($productList as $product) {
  74. $spuId = $product['spu_id'];
  75. $productId = $product['product_id'];
  76. $storeName = $product['store_name'];
  77. if (empty($spuId)) {
  78. echo "商品 {$productId} 的 spu_id 为空,跳过\n\n";
  79. continue;
  80. }
  81. echo "--- 查询商品: {$storeName} (spu_id: {$spuId}) ---\n";
  82. // ---- 第二步:获取商品详情,提取分类ID ----
  83. $detail = $productService->getProductDetail($spuId);
  84. if ($detail === false || empty($detail)) {
  85. echo " 获取1688商品详情失败\n\n";
  86. continue;
  87. }
  88. $categoryId = $detail['categoryId'] ?? 0;
  89. $categoryName = $detail['categoryName'] ?? '';
  90. echo " 商品标题: {$detail['title']}\n";
  91. echo " 分类ID: {$categoryId}\n";
  92. echo " 分类名称: {$categoryName}\n";
  93. echo " 价格区间: ¥{$detail['minPrice']} ~ ¥{$detail['maxPrice']}\n\n";
  94. // ---- 第三步:追溯完整分类层级(直到顶级分类) ----
  95. echo "========== 第三步:追溯完整分类层级(直到顶级分类) ==========\n";
  96. $categoryPath = []; // 从叶子到根的顺序存储
  97. $categoryPathReversed = []; // 从根到叶子的顺序
  98. if (!empty($categoryId)) {
  99. $currentCategoryId = $categoryId;
  100. $maxLevels = 10;
  101. $level = 0;
  102. while ($currentCategoryId > 0 && $level < $maxLevels) {
  103. $level++;
  104. echo " 第{$level}层: 查询分类ID [{$currentCategoryId}]...\n";
  105. $categoryInfoList = $productService->getCategories((string)$currentCategoryId);
  106. if ($categoryInfoList === false || empty($categoryInfoList)) {
  107. echo " 分类ID [{$currentCategoryId}] 查询失败或无数据,停止追溯\n";
  108. break;
  109. }
  110. // 查找与当前分类ID匹配的分类信息
  111. $currentCategoryInfo = null;
  112. foreach ($categoryInfoList as $cat) {
  113. if (($cat['categoryID'] ?? 0) == $currentCategoryId) {
  114. $currentCategoryInfo = $cat;
  115. break;
  116. }
  117. }
  118. if ($currentCategoryInfo === null) {
  119. $currentCategoryInfo = $categoryInfoList[0] ?? null;
  120. }
  121. if ($currentCategoryInfo === null) {
  122. echo " 无法获取分类信息,停止追溯\n";
  123. break;
  124. }
  125. $catId = $currentCategoryInfo['categoryID'] ?? 0;
  126. $catName = $currentCategoryInfo['name'] ?? '';
  127. $parentIDs = $currentCategoryInfo['parentIDs'] ?? [];
  128. $isLeaf = $currentCategoryInfo['isLeaf'] ?? false;
  129. $categoryPath[] = [
  130. 'category_id' => $catId,
  131. 'category_name' => $catName,
  132. 'is_leaf' => $isLeaf,
  133. 'parent_ids' => $parentIDs,
  134. ];
  135. echo " 当前分类: [{$catId}] {$catName}, parentIDs: [" . implode(',', $parentIDs) . "], isLeaf: " . ($isLeaf ? '是' : '否') . "\n";
  136. if (empty($parentIDs) || in_array(0, $parentIDs, true) || in_array('0', $parentIDs, true)) {
  137. echo " → 已到达顶级分类,追溯完成\n";
  138. break;
  139. }
  140. $currentCategoryId = (int)$parentIDs[0];
  141. }
  142. if ($level >= $maxLevels) {
  143. echo " 警告:达到最大追溯层数 {$maxLevels},可能存在循环\n";
  144. }
  145. // 输出完整分类层级(从顶级到叶子)
  146. $categoryPathReversed = array_reverse($categoryPath);
  147. $pathStr = '';
  148. foreach ($categoryPathReversed as $i => $cat) {
  149. if ($i > 0) $pathStr .= ' → ';
  150. $pathStr .= "[{$cat['category_id']}] {$cat['category_name']}";
  151. }
  152. echo "\n 完整分类层级: {$pathStr}\n\n";
  153. } else {
  154. echo " 分类ID为空,无法追溯分类层级\n\n";
  155. }
  156. // ---- 第四步:将顶级分类保存到 store_category 表,并更新商品 cate_id ----
  157. echo "========== 第四步:保存顶级分类到 store_category 表 ==========\n";
  158. if (!empty($categoryPathReversed)) {
  159. $topCategory = $categoryPathReversed[0];
  160. $alibabaCateId = $topCategory['category_id'];
  161. $alibabaCateName = $topCategory['category_name'];
  162. echo " 顶级分类: [{$alibabaCateId}] {$alibabaCateName}\n";
  163. // 按 alibaba_cate_id 查重
  164. $existingCategory = Db::name('store_category')
  165. ->where('alibaba_cate_id', $alibabaCateId)
  166. ->find();
  167. if ($existingCategory) {
  168. $storeCategoryId = $existingCategory['store_category_id'];
  169. echo " 分类已存在 (store_category_id: {$storeCategoryId}),跳过创建\n";
  170. } else {
  171. $insertData = [
  172. 'pid' => 564,
  173. 'cate_name' => $alibabaCateName,
  174. 'path' => '',
  175. 'sort' => 0,
  176. 'pic' => '',
  177. 'is_show' => 1,
  178. 'level' => 2,
  179. 'mer_id' => 0,
  180. 'create_time' => date('Y-m-d H:i:s'),
  181. 'alibaba_cate_id' => $alibabaCateId,
  182. ];
  183. $storeCategoryId = Db::name('store_category')->insertGetId($insertData);
  184. if ($storeCategoryId) {
  185. $path = '/563/564/';
  186. Db::name('store_category')
  187. ->where('store_category_id', $storeCategoryId)
  188. ->update(['path' => $path]);
  189. echo " 顶级分类创建成功! store_category_id: {$storeCategoryId}, path: {$path}\n";
  190. } else {
  191. echo " 顶级分类创建失败\n";
  192. }
  193. }
  194. // 更新商品 cate_id
  195. if (!empty($storeCategoryId)) {
  196. Db::name('store_product')
  197. ->where('product_id', $productId)
  198. ->update(['cate_id' => $storeCategoryId]);
  199. echo " 已更新商品(product_id: {$productId}) 的 cate_id 为 {$storeCategoryId}\n";
  200. }
  201. } else {
  202. echo " 未找到顶级分类数据\n";
  203. }
  204. echo "\n";
  205. }
  206. } catch (\Throwable $e) {
  207. echo "错误: " . $e->getMessage() . "\n";
  208. echo "文件: " . $e->getFile() . " (行 " . $e->getLine() . ")\n";
  209. }
  210. die;
  211. }
  212. public function posttest()
  213. {
  214. $sessionKey = request()->post(['sessionKey']);
  215. $encryptedData = request()->post(['encryptedData']);
  216. $iv = request()->post(['iv']);
  217. $appid = 'wx9082e5ac2fdb513f';
  218. $sessionKey =str_replace(' ','+', stripslashes($sessionKey['sessionKey']));
  219. $encryptedData=str_replace(' ','+',$encryptedData['encryptedData']);
  220. $iv =str_replace(' ','+', stripslashes($iv['iv']));
  221. // $sessionKey =str_replace(' ','+', $sessionKey['sessionKey']);
  222. // $encryptedData=str_replace(' ','+',$encryptedData['encryptedData']);
  223. // $iv =str_replace(' ','+', $iv['iv']);
  224. $pc = new WXBizDataCrypt($appid, $sessionKey);
  225. $errCode = $pc->decryptData($encryptedData, $iv, $data );
  226. dd($errCode);
  227. }
  228. /**
  229. * 直接调用示例(不通过ProductService,展示完整流程)
  230. */
  231. public function direct()
  232. {
  233. $host = 'https://gw.open.1688.com/openapi/';
  234. $appKey = '6512262';
  235. $appSecret = 'uNPRZE7895';
  236. $accessToken = 'dc8eab20-f10f-4688-9e45-9ebfa182c7c2';
  237. $version = 1;
  238. $namespace = 'com.alibaba.fenxiao';
  239. $apiName = 'jxhy.product.getPageList';
  240. // 1. 构建URL
  241. $param = "param2/{$version}/";
  242. $path = "{$namespace}/{$apiName}/{$appKey}";
  243. $url = $host . $param . $path;
  244. // 2. 请求参数
  245. $data = [
  246. 'access_token' => $accessToken,
  247. 'pageNo' => 1,
  248. 'pageSize' => 10,
  249. ];
  250. // 3. 生成签名
  251. $aliParams = [];
  252. foreach ($data as $key => $val) {
  253. $aliParams[] = $key . $val;
  254. }
  255. sort($aliParams);
  256. $signStr = $param . $path . join('', $aliParams);
  257. $data['_aop_signature'] = strtoupper(bin2hex(
  258. hash_hmac("sha1", $signStr, $appSecret, true)
  259. ));
  260. // 4. 发送POST请求
  261. $ch = curl_init();
  262. curl_setopt($ch, CURLOPT_URL, $url);
  263. curl_setopt($ch, CURLOPT_POST, true);
  264. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  265. curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
  266. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  267. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  268. $response = curl_exec($ch);
  269. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  270. curl_close($ch);
  271. $result = json_decode($response, true);
  272. echo "HTTP状态码: {$httpCode}\n";
  273. dump($result);
  274. die;
  275. }
  276. /**
  277. * 1688分销商品详情 - 调用示例
  278. *
  279. * API: com.alibaba.fenxiao:alibaba.pifatuan.product.detail.list-2
  280. * 文档: https://open.1688.com/api/apidocdetail.htm?id=com.alibaba.fenxiao%3Aalibaba.pifatuan.product.detail.list-2
  281. */
  282. public function detail()
  283. {
  284. try {
  285. /** @var ProductService $productService */
  286. $productService = app()->make(ProductService::class);
  287. // 设置 access_token
  288. $productService->setAccessToken('dc8eab20-f10f-4688-9e45-9ebfa182c7c2');
  289. // 商品ID(从列表接口获取到的 itemId)
  290. $productId = 642639328505;
  291. echo "=== 获取商品详情 ===\n";
  292. echo "商品ID: {$productId}\n\n";
  293. $result = $productService->getProductDetail($productId);
  294. echo "=== 原始返回 ===\n";
  295. var_dump($result);
  296. echo "\n";
  297. if ($result === false) {
  298. echo "请求失败,请查看日志获取详细信息。\n";
  299. } else {
  300. echo "=== 商品详情结果 ===\n";
  301. echo "标题: " . ($result['title'] ?? 'N/A') . "\n";
  302. echo "商品ID: " . ($result['productId'] ?? 'N/A') . "\n";
  303. echo "价格: ¥" . ($result['minPrice'] ?? 0) . " ~ ¥" . ($result['maxPrice'] ?? 0) . "\n";
  304. echo "库存: " . ($result['stock'] ?? 0) . "\n";
  305. echo "主图: " . ($result['mainImage'] ?? 'N/A') . "\n";
  306. echo "SKU数: " . (isset($result['skuList']) ? count($result['skuList']) : 0) . "\n";
  307. echo "图片数: " . (isset($result['imageList']) ? count($result['imageList']) : 0) . "\n";
  308. }
  309. } catch (\Throwable $e) {
  310. echo "错误: " . $e->getMessage() . "\n";
  311. echo "文件: " . $e->getFile() . " (行 " . $e->getLine() . ")\n";
  312. }
  313. die;
  314. }
  315. }