| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386 |
- <?php
- namespace app\controller\api;
- use app\common\enum\CommonEnum;
- use app\common\repositories\merchant\order\OrderMerchantRepository;
- use app\common\repositories\shared\SharedProsperityRecommendConfigRepository;
- use app\common\repositories\user\UserAddressRepository;
- use app\common\repositories\user\UserRepository;
- use app\services\ThirdParty\AlibabaAgent\OrderService;
- use app\services\ThirdParty\AlibabaAgent\ProductService;
- use applet\WXBizDataCrypt;
- use think\facade\Db;
- /**
- * 1688分销严选采购解决方案 - 接口调用示例
- *
- * 使用前请确保 config/third_party.php 中已配置 alibaba_agent 项:
- * 'alibaba_agent' => [
- * 'appKey' => '你的AppKey',
- * 'appSecret' => '你的AppSecret',
- * 'gatewayUrl' => 'https://gw.open.1688.com/openapi/',
- * ]
- *
- * access_token 通过 OAuth 2.0 授权获取,或由用户提供。
- */
- class Test
- {
- /**
- * 1688分销商品列表 - 调用示例
- *
- * API: com.alibaba.fenxiao:jxhy.product.getPageList-1
- * 文档: https://open.1688.com/api/apidocdetail.htm?id=com.alibaba.fenxiao%3Ajxhy.product.getPageList-1
- */
- public function test()
- {
- // ============================================================
- // 功能:从本地 store_product 表读取 is_alibaba=1 的商品
- // → 根据 spu_id(1688商品ID)查询1688商品详情
- // → 获取分类ID → 重复调用1688分类接口向上追溯
- // → 直到 parentIDs=[0](顶级分类)
- // → 将顶级分类保存到 store_category 表(按 alibaba_cate_id 去重)
- // → 更新商品的 cate_id
- // ============================================================
- try {
- /** @var ProductService $productService */
- $productService = app()->make(ProductService::class);
- $productService->setAccessToken('ce15fc70-b462-43bf-acc3-f87e43c858ba');
- // ============================================================
- // 第一步:从 store_product 表读取 is_alibaba=1 的商品
- // ============================================================
- echo "========== 第一步:读取本地1688商品列表 ==========\n";
- $productList = Db::name('store_product')
- ->where('is_alibaba', 1)
- ->where('cate_id', 0)
- ->where('is_del', 0)
- ->field('product_id, store_name, spu_id, image, price, is_alibaba')
- ->limit(50)
- ->select()
- ->toArray();
- if (empty($productList)) {
- echo "没有找到 is_alibaba=1 的商品\n";
- die;
- }
- echo "共找到 " . count($productList) . " 个1688商品\n\n";
- foreach ($productList as $i => $product) {
- echo ($i + 1) . ". {$product['store_name']}\n";
- echo " 本地商品ID: {$product['product_id']}\n";
- echo " 1688商品ID(spu_id): {$product['spu_id']}\n";
- echo " 价格: ¥{$product['price']}\n\n";
- }
- // ============================================================
- // 第二步+第三步+第四步:遍历商品,查询详情 → 追溯分类层级 → 保存顶级分类
- // ============================================================
- echo "========== 第二步:查询1688商品详情,获取分类ID ==========\n\n";
- foreach ($productList as $product) {
- $spuId = $product['spu_id'];
- $productId = $product['product_id'];
- $storeName = $product['store_name'];
- if (empty($spuId)) {
- echo "商品 {$productId} 的 spu_id 为空,跳过\n\n";
- continue;
- }
- echo "--- 查询商品: {$storeName} (spu_id: {$spuId}) ---\n";
- // ---- 第二步:获取商品详情,提取分类ID ----
- $detail = $productService->getProductDetail($spuId);
- if ($detail === false || empty($detail)) {
- echo " 获取1688商品详情失败\n\n";
- continue;
- }
- $categoryId = $detail['categoryId'] ?? 0;
- $categoryName = $detail['categoryName'] ?? '';
- echo " 商品标题: {$detail['title']}\n";
- echo " 分类ID: {$categoryId}\n";
- echo " 分类名称: {$categoryName}\n";
- echo " 价格区间: ¥{$detail['minPrice']} ~ ¥{$detail['maxPrice']}\n\n";
- // ---- 第三步:追溯完整分类层级(直到顶级分类) ----
- echo "========== 第三步:追溯完整分类层级(直到顶级分类) ==========\n";
- $categoryPath = []; // 从叶子到根的顺序存储
- $categoryPathReversed = []; // 从根到叶子的顺序
- if (!empty($categoryId)) {
- $currentCategoryId = $categoryId;
- $maxLevels = 10;
- $level = 0;
- while ($currentCategoryId > 0 && $level < $maxLevels) {
- $level++;
- echo " 第{$level}层: 查询分类ID [{$currentCategoryId}]...\n";
- $categoryInfoList = $productService->getCategories((string)$currentCategoryId);
- if ($categoryInfoList === false || empty($categoryInfoList)) {
- echo " 分类ID [{$currentCategoryId}] 查询失败或无数据,停止追溯\n";
- break;
- }
- // 查找与当前分类ID匹配的分类信息
- $currentCategoryInfo = null;
- foreach ($categoryInfoList as $cat) {
- if (($cat['categoryID'] ?? 0) == $currentCategoryId) {
- $currentCategoryInfo = $cat;
- break;
- }
- }
- if ($currentCategoryInfo === null) {
- $currentCategoryInfo = $categoryInfoList[0] ?? null;
- }
- if ($currentCategoryInfo === null) {
- echo " 无法获取分类信息,停止追溯\n";
- break;
- }
- $catId = $currentCategoryInfo['categoryID'] ?? 0;
- $catName = $currentCategoryInfo['name'] ?? '';
- $parentIDs = $currentCategoryInfo['parentIDs'] ?? [];
- $isLeaf = $currentCategoryInfo['isLeaf'] ?? false;
- $categoryPath[] = [
- 'category_id' => $catId,
- 'category_name' => $catName,
- 'is_leaf' => $isLeaf,
- 'parent_ids' => $parentIDs,
- ];
- echo " 当前分类: [{$catId}] {$catName}, parentIDs: [" . implode(',', $parentIDs) . "], isLeaf: " . ($isLeaf ? '是' : '否') . "\n";
- if (empty($parentIDs) || in_array(0, $parentIDs, true) || in_array('0', $parentIDs, true)) {
- echo " → 已到达顶级分类,追溯完成\n";
- break;
- }
- $currentCategoryId = (int)$parentIDs[0];
- }
- if ($level >= $maxLevels) {
- echo " 警告:达到最大追溯层数 {$maxLevels},可能存在循环\n";
- }
- // 输出完整分类层级(从顶级到叶子)
- $categoryPathReversed = array_reverse($categoryPath);
- $pathStr = '';
- foreach ($categoryPathReversed as $i => $cat) {
- if ($i > 0) $pathStr .= ' → ';
- $pathStr .= "[{$cat['category_id']}] {$cat['category_name']}";
- }
- echo "\n 完整分类层级: {$pathStr}\n\n";
- } else {
- echo " 分类ID为空,无法追溯分类层级\n\n";
- }
- // ---- 第四步:将顶级分类保存到 store_category 表,并更新商品 cate_id ----
- echo "========== 第四步:保存顶级分类到 store_category 表 ==========\n";
- if (!empty($categoryPathReversed)) {
- $topCategory = $categoryPathReversed[0];
- $alibabaCateId = $topCategory['category_id'];
- $alibabaCateName = $topCategory['category_name'];
- echo " 顶级分类: [{$alibabaCateId}] {$alibabaCateName}\n";
- // 按 alibaba_cate_id 查重
- $existingCategory = Db::name('store_category')
- ->where('alibaba_cate_id', $alibabaCateId)
- ->find();
- if ($existingCategory) {
- $storeCategoryId = $existingCategory['store_category_id'];
- echo " 分类已存在 (store_category_id: {$storeCategoryId}),跳过创建\n";
- } else {
- $insertData = [
- 'pid' => 564,
- 'cate_name' => $alibabaCateName,
- 'path' => '',
- 'sort' => 0,
- 'pic' => '',
- 'is_show' => 1,
- 'level' => 2,
- 'mer_id' => 0,
- 'create_time' => date('Y-m-d H:i:s'),
- 'alibaba_cate_id' => $alibabaCateId,
- ];
- $storeCategoryId = Db::name('store_category')->insertGetId($insertData);
- if ($storeCategoryId) {
- $path = '/563/564/';
- Db::name('store_category')
- ->where('store_category_id', $storeCategoryId)
- ->update(['path' => $path]);
- echo " 顶级分类创建成功! store_category_id: {$storeCategoryId}, path: {$path}\n";
- } else {
- echo " 顶级分类创建失败\n";
- }
- }
- // 更新商品 cate_id
- if (!empty($storeCategoryId)) {
- Db::name('store_product')
- ->where('product_id', $productId)
- ->update(['cate_id' => $storeCategoryId]);
- echo " 已更新商品(product_id: {$productId}) 的 cate_id 为 {$storeCategoryId}\n";
- }
- } else {
- echo " 未找到顶级分类数据\n";
- }
- echo "\n";
- }
- } catch (\Throwable $e) {
- echo "错误: " . $e->getMessage() . "\n";
- echo "文件: " . $e->getFile() . " (行 " . $e->getLine() . ")\n";
- }
- die;
- }
- public function posttest()
- {
- $sessionKey = request()->post(['sessionKey']);
- $encryptedData = request()->post(['encryptedData']);
- $iv = request()->post(['iv']);
- $appid = 'wx9082e5ac2fdb513f';
- $sessionKey =str_replace(' ','+', stripslashes($sessionKey['sessionKey']));
- $encryptedData=str_replace(' ','+',$encryptedData['encryptedData']);
- $iv =str_replace(' ','+', stripslashes($iv['iv']));
-
- // $sessionKey =str_replace(' ','+', $sessionKey['sessionKey']);
- // $encryptedData=str_replace(' ','+',$encryptedData['encryptedData']);
- // $iv =str_replace(' ','+', $iv['iv']);
- $pc = new WXBizDataCrypt($appid, $sessionKey);
- $errCode = $pc->decryptData($encryptedData, $iv, $data );
- dd($errCode);
- }
- /**
- * 直接调用示例(不通过ProductService,展示完整流程)
- */
- public function direct()
- {
- $host = 'https://gw.open.1688.com/openapi/';
- $appKey = '6512262';
- $appSecret = 'uNPRZE7895';
- $accessToken = 'dc8eab20-f10f-4688-9e45-9ebfa182c7c2';
- $version = 1;
- $namespace = 'com.alibaba.fenxiao';
- $apiName = 'jxhy.product.getPageList';
- // 1. 构建URL
- $param = "param2/{$version}/";
- $path = "{$namespace}/{$apiName}/{$appKey}";
- $url = $host . $param . $path;
- // 2. 请求参数
- $data = [
- 'access_token' => $accessToken,
- 'pageNo' => 1,
- 'pageSize' => 10,
- ];
- // 3. 生成签名
- $aliParams = [];
- foreach ($data as $key => $val) {
- $aliParams[] = $key . $val;
- }
- sort($aliParams);
- $signStr = $param . $path . join('', $aliParams);
- $data['_aop_signature'] = strtoupper(bin2hex(
- hash_hmac("sha1", $signStr, $appSecret, true)
- ));
- // 4. 发送POST请求
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_POST, true);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
- $response = curl_exec($ch);
- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- curl_close($ch);
- $result = json_decode($response, true);
- echo "HTTP状态码: {$httpCode}\n";
- dump($result);
- die;
- }
- /**
- * 1688分销商品详情 - 调用示例
- *
- * API: com.alibaba.fenxiao:alibaba.pifatuan.product.detail.list-2
- * 文档: https://open.1688.com/api/apidocdetail.htm?id=com.alibaba.fenxiao%3Aalibaba.pifatuan.product.detail.list-2
- */
- public function detail()
- {
- try {
- /** @var ProductService $productService */
- $productService = app()->make(ProductService::class);
- // 设置 access_token
- $productService->setAccessToken('dc8eab20-f10f-4688-9e45-9ebfa182c7c2');
- // 商品ID(从列表接口获取到的 itemId)
- $productId = 642639328505;
- echo "=== 获取商品详情 ===\n";
- echo "商品ID: {$productId}\n\n";
- $result = $productService->getProductDetail($productId);
- echo "=== 原始返回 ===\n";
- var_dump($result);
- echo "\n";
- if ($result === false) {
- echo "请求失败,请查看日志获取详细信息。\n";
- } else {
- echo "=== 商品详情结果 ===\n";
- echo "标题: " . ($result['title'] ?? 'N/A') . "\n";
- echo "商品ID: " . ($result['productId'] ?? 'N/A') . "\n";
- echo "价格: ¥" . ($result['minPrice'] ?? 0) . " ~ ¥" . ($result['maxPrice'] ?? 0) . "\n";
- echo "库存: " . ($result['stock'] ?? 0) . "\n";
- echo "主图: " . ($result['mainImage'] ?? 'N/A') . "\n";
- echo "SKU数: " . (isset($result['skuList']) ? count($result['skuList']) : 0) . "\n";
- echo "图片数: " . (isset($result['imageList']) ? count($result['imageList']) : 0) . "\n";
- }
- } catch (\Throwable $e) {
- echo "错误: " . $e->getMessage() . "\n";
- echo "文件: " . $e->getFile() . " (行 " . $e->getLine() . ")\n";
- }
- die;
- }
- }
|