编程语言
首页 > 编程语言> > Java API获取微盟商品信息详解

Java API获取微盟商品信息详解

作者:互联网

Java API获取微盟商品信息详解

1. 业务概述

1.1 微盟云简介

像淘宝,京东,苏宁等各式各样的电商平台或者其他平台,处理提供有pc,app,h5等可视化的交互方式,还会提供便于后台开发,集成扩展的rest api的交互方式,微盟也是如此,微盟云。

微盟云是基于微盟各大业务解决方案提供的一个全场景解决方案的开发平台,通过OpenAPI、消息推送服务、扩展点、自定义页面、页面组件等形式开放给开发者。它是微盟基础服务的重要开放途径,致力于通过高效低成本的开发方式帮助商家解决经营场景中的个性化需求,助力开发者共赢并赋能商家成功。
说的是挺好相信公司的初衷也是这样,这里不得不吐槽下微盟的运营不是很专业,不过态度还行,但是通过微盟云公众号技术支持态度真的很差,甩给你个文档链接,文档不是很详细,还有很多错误的数据类型,半天回一句,很多问题一句话的事,都要不停的试错,导致效率很低,沟通很重要,可是微盟对待付费账户不专业呀!

微盟云简介,https://cloud.weimob.com/saas/word/detail.html?tag=1079&menuId=2
在这里插入图片描述

1.2 业务需求

在业务开发中有些场景是需要同步微信小程序,或者是微盟等电商平台的商品,酒店,订单,库存等信息,用来集成到自有系统或者是第三方系统中。

需要注意的是,通过微盟开放平台提供的API实现商品或者酒店,订单等数据的同步,前提条件是已经获取有效的token信息,这个在上篇已经详细梳理,详见,Java API获取微盟token信息详解

2. 后台配置

2.1 普通API与消息API

微盟API文档:https://cloud.weimob.com/saas/word/list.html?tag=190&menuId=1

微商城-商品API
普通API:商品,库存,类目等API属于调用微盟接口。
消息API:属于微盟商品变更通知外部系统的机制,调用外部接口。

普通api调用不需要配置,有token即可调用,消息api需要配置接收地址与订阅。

2.1 消息API配置

对接消息API文档,开发指南-服务订购消息订阅。
https://cloud.weimob.com/saas/word/detail.html?tag=1102&menuId=2

配置消息API地址:开发者中心-应用列表-API权限
在这里插入图片描述
API消息订阅服务-开启订阅,订阅网址一定要可用才能保存,提供的订阅网址是POST请求,参数是linkedHashMap,不必传@RequestBody(required = false),要不然掉不通保存不了。
接口权限列表-消息订阅接口:选择对应类目进行测试与订阅。
在这里插入图片描述

3. 实现验证

对于微盟提供的API接口对接还好,解析不是很友好,如果能够提供完善的sdk与demo,将会给服务商及商户带来极大的便利与更加友好的体验。

只是为了获取数据解析验证,就不全贴了,按需索取,仅供参考。

3.1 普通接口实现

微盟同步商品接口:WeimobSynGoodsService


import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;

import java.net.URI;
import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * 微盟同步商品接口
 *
 * @author zrj
 * @since 2021/7/22
 **/
@Service("WeimobSynGoodsService")
@FeignClient(url = "https://dopen.weimob.com/api/1_0", name = "WeimobSynGoodsService")
public interface WeimobSynGoodsService {
    /**
     * 同步微盟商品信息(全量)
     */
    @PostMapping
    LinkedHashMap querySimpleGoodsListWithPage(URI uri, HashMap map);

    /**
     * 同步微盟商品信息(增量)
     * 本接口最多获取10000个商品
     */
    @PostMapping
    LinkedHashMap queryGoodsList(URI uri, HashMap map);

    /**
     * 获取商品详情
     */
    @PostMapping
    LinkedHashMap queryGoodsDetail(URI uri, HashMap map);

}

微盟同步酒店接口:WeimobSynStoreService

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;

import java.net.URI;
import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * 微盟同步酒店接口
 *
 * @author zrj
 * @since 2021/7/22
 **/
@Service("WeimobSynStoreService")
@FeignClient(url = "https://dopen.weimob.com/api/1_0", name = "WeimobSynStoreService")
public interface WeimobSynStoreService {
    /**
     * 同步微盟酒店信息
     */
    @PostMapping
    LinkedHashMap getStoreList(URI uri, HashMap map);
}

同步搜索数据接口:SearchDataSynService


import com.ennova.tour.search.core.service.bo.SearchDataSynBO;
import top.rdfa.framework.biz.ro.RdfaResult;

/**
 * 同步搜索数据接口
 *
 * @author zrj
 * @since 2021/7/21
 **/
public interface SearchDataSynService {

    /**
     * 微盟同步全量商品数据
     */
    RdfaResult weimobSynAllGoods();

    /**
     * 微盟同步增量商品数据
     */
    RdfaResult weimobSynIncGoods();

    /**
     * 微盟同步酒店数据
     */
    RdfaResult weimobSynStore();

    /**
     * 数据同步:直播,玩乐,游记,攻略
     */
    RdfaResult tourSynData(SearchDataSynBO searchDataSynBO);

}

同步搜索数据实现类:SearchDataSynServiceImpl


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ennova.tour.search.core.service.SearchDataSynService;
import com.ennova.tour.search.core.service.SearchPlantService;
import com.ennova.tour.search.core.service.bo.GoodsListInfo;
import com.ennova.tour.search.core.service.bo.SearchDataSynBO;
import com.ennova.tour.search.core.service.bo.QueryGoodsListRequestVo;
import com.ennova.tour.search.core.service.bo.StoreOut;
import com.ennova.tour.search.core.service.constants.CommonConstant;
import com.ennova.tour.search.core.service.enums.OperateEnum;
import com.ennova.tour.search.core.service.enums.TourSearchErrorCodeEnum;
import com.ennova.tour.search.core.service.utils.DateUtils;
import com.ennova.tour.search.dal.mapper.ext.SearchGoodsExtMapper;
import com.ennova.tour.search.dal.mapper.ext.SearchStoreExtMapper;
import com.ennova.tour.search.dal.mapper.ext.SearchStoreLogoExtMapper;
import com.ennova.tour.search.dal.mapper.ext.SearchStoreMatingExtMapper;
import com.ennova.tour.search.dal.mapper.mbg.*;
import com.ennova.tour.search.dal.po.mbg.SearchGoods;
import com.ennova.tour.search.dal.po.mbg.SearchStore;
import com.ennova.tour.search.dal.po.mbg.SearchStoreLogo;
import com.ennova.tour.search.integration.service.WeimobSynGoodsService;
import com.ennova.tour.search.integration.service.WeimobSynStoreService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import top.rdfa.framework.biz.ro.RdfaResult;

import javax.annotation.Resource;
import java.net.URI;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 同步搜索数据实现类
 *
 * @author zrj
 * @since 2021/7/21
 **/
@Slf4j
@Service
public class SearchDataSynServiceImpl implements SearchDataSynService {

    @Resource
    private SearchEsIndexMapper searchEsIndexMapper;
    @Resource
    private SearchGoodsMapper searchGoodsMapper;
    @Resource
    private SearchGoodsExtMapper searchGoodsExtMapper;
    @Resource
    private SearchStoreMapper searchStoreMapper;
    @Resource
    private SearchStoreLogoMapper searchStoreLogoMapper;
    @Resource
    private SearchStoreMatingMapper searchStoreMatingMapper;
    @Resource
    private SearchStoreExtMapper searchStoreExtMapper;
    @Resource
    private SearchStoreLogoExtMapper searchStoreLogoExtMapper;
    @Resource
    private SearchStoreMatingExtMapper searchStoreMatingExtMapper;
    @Resource
    private WeimobSynGoodsService weimobSynGoodsService;
    @Resource
    private WeimobSynStoreService weimobSynStoreService;

    @Resource(name = "redisTemplate")
    private RedisTemplate redisTemplate;

    @Resource
    private SearchPlantService searchPlantService;

    //@Resource
    //private GeneralSearchService generalSearchService;

    private String accessToken;
    private String goodsRedictUri;
    private String storeRedictUri;
    private URI goodsUri;
    private URI storeUri;

    /**
     * 初始化配置信息
     */
    public SearchDataSynServiceImpl() {
        log.info("数据同步初始化配置信息");
        goodsRedictUri = CommonConstant.goodsRedictUri;
        storeRedictUri = CommonConstant.storeRedictUri;
    }

    /**
     * 微盟同步全量商品数据
     */
    @Override
    public RdfaResult weimobSynAllGoods() {
        log.info("微盟同步全量商品数据");

        try {
            // 循环获取微盟商品信息
            for (int i = 1; ; i++) {
                HashMap map = Maps.newHashMap();
                map.put("pageSize", CommonConstant.GOODS_MAX_PAGE_SIZE);
                map.put("pageNum", i);

                // 缓存中获取token
                accessToken = (String) redisTemplate.opsForValue().get(CommonConstant.WEIMOB_GOODS_ACCESS_TOKEN_KEY);
                goodsUri = new URI(goodsRedictUri + accessToken);

                LinkedHashMap queryGoodsMap = weimobSynGoodsService.queryGoodsList(goodsUri, map);
                log.info("同步全量商品数据响应结果:" + JSON.toJSONString(queryGoodsMap));

                if (CollectionUtil.isEmpty(queryGoodsMap)) {
                    break;
                }

                // 解析转换
                JSONObject json = (JSONObject) JSON.toJSON(queryGoodsMap);
                JSONObject code = json.getJSONObject("code");
                String errcode = code.getString("errcode");
                if (!"0".equals(errcode)) {
                    log.warn("同步全量商品数据失败:" + JSON.toJSONString(code));
                    break;
                }

                // 获取商品数据
                JSONObject data = json.getJSONObject("data");
                int totalCount = data.getIntValue("totalCount");
                if (totalCount == 0) {
                    log.warn("同步全量商品数据为空:" + JSON.toJSONString(data));
                    break;
                }

                // 获取商品列表
                String pageList = data.getString("pageList");
                List<GoodsListInfo> goodsListInfoList = JSONArray.parseArray(pageList, GoodsListInfo.class);
                System.out.println(goodsListInfoList);

                if (CollectionUtil.isEmpty(goodsListInfoList)) {
                    break;
                }

                // 批量入库
                List<SearchGoods> searchGoodsList = getGoodsInfoList(goodsListInfoList);
                searchGoodsExtMapper.batchInsert(searchGoodsList);

            }
        } catch (Exception e) {
            log.error("微盟同步全量商品数据异常" + e);
            return RdfaResult.fail(CommonConstant.RDFA_RESULT_FAIL_CODE, CommonConstant.RDFA_RESULT_FAIL_MSG);
        }

        return RdfaResult.success(CommonConstant.RDFA_RESULT_SUCCESS_CODE, CommonConstant.RDFA_RESULT_SUCCESS_MSG, null);
    }

    /**
     * 微盟同步增量商品数据
     */
    @Override
    public RdfaResult weimobSynIncGoods() {
        log.info("微盟同步增量商品数据");

        try {
            // 查询昨天晚上12点到当前时间内更新的商品
            QueryGoodsListRequestVo goodsListRequestVo = new QueryGoodsListRequestVo();
            goodsListRequestVo.setUpdateStartTime(DateUtils.getZeroDate());
            goodsListRequestVo.setUpdateEndTime(DateUtils.getNowDate());

            // 循环获取微盟商品信息
            for (int i = 1; ; i++) {
                HashMap map = Maps.newHashMap();
                map.put("pageSize", CommonConstant.GOODS_MAX_PAGE_SIZE);
                map.put("pageNum", i);
                map.put("queryParameter", goodsListRequestVo);

                // 缓存中获取token
                accessToken = (String) redisTemplate.opsForValue().get(CommonConstant.WEIMOB_GOODS_ACCESS_TOKEN_KEY);
                goodsUri = new URI(goodsRedictUri + accessToken);

                LinkedHashMap queryGoodsMap = weimobSynGoodsService.queryGoodsList(goodsUri, map);
                if (CollectionUtil.isEmpty(queryGoodsMap)) {
                    break;
                }
                // 解析转换
                JSONObject json = (JSONObject) JSON.toJSON(queryGoodsMap);
                JSONObject code = json.getJSONObject("code");
                String errcode = code.getString("errcode");
                if (!"0".equals(errcode)) {
                    log.warn("同步全量商品数据失败:" + JSON.toJSONString(code));
                    break;
                }

                // 获取商品数据
                JSONObject data = json.getJSONObject("data");
                int totalCount = data.getIntValue("totalCount");
                if (totalCount == 0) {
                    log.warn("同步全量商品数据为空:" + JSON.toJSONString(data));
                    break;
                }

                // 获取商品列表
                String pageList = data.getString("pageList");
                List<GoodsListInfo> goodsListInfoList = JSONArray.parseArray(pageList, GoodsListInfo.class);
                System.out.println(goodsListInfoList);

                if (CollectionUtil.isEmpty(goodsListInfoList)) {
                    break;
                }

                // 批量更新
                List<SearchGoods> searchGoodsList = getGoodsInfoList(goodsListInfoList);
                searchGoodsExtMapper.batchReplace(searchGoodsList);

            }
        } catch (Exception e) {
            log.error("微盟同步增量商品数据异常" + e);
            return RdfaResult.fail(CommonConstant.RDFA_RESULT_FAIL_CODE, CommonConstant.RDFA_RESULT_FAIL_MSG);
        }

        return RdfaResult.success(CommonConstant.RDFA_RESULT_SUCCESS_CODE, CommonConstant.RDFA_RESULT_SUCCESS_MSG, null);
    }

    /**
     * 微盟同步酒店数据
     */
    @Override
    public RdfaResult weimobSynStore() {
        log.info("微盟同步酒店数据");

        try {
            // 循环更新商品信息
            for (int i = 1; ; i++) {
                HashMap map = Maps.newHashMap();
                map.put("pageSize", CommonConstant.STORE_MAX_PAGE_SIZE);
                map.put("pageIndex", i);

                // 缓存中获取token
                accessToken = (String) redisTemplate.opsForValue().get(CommonConstant.WEIMOB_STORE_ACCESS_TOKEN_KEY);
                storeUri = new URI(storeRedictUri + accessToken);

                LinkedHashMap storeMap = weimobSynStoreService.getStoreList(storeUri, map);
                if (CollectionUtil.isEmpty(storeMap)) {
                    break;
                }

                // 解析转换
                JSONObject json = (JSONObject) JSON.toJSON(storeMap);
                JSONObject code = json.getJSONObject("code");
                String errcode = code.getString("errcode");
                if (!"0".equals(errcode)) {
                    log.warn("同步全量酒店数据失败:" + JSON.toJSONString(code));
                    break;
                }

                // 获取商品数据
                JSONObject data = json.getJSONObject("data");
                int totalCount = data.getIntValue("totalCount");
                if (totalCount == 0) {
                    log.warn("同步全量酒店数据为空:" + JSON.toJSONString(data));
                    break;
                }
                // 获取wid
                Long wid = data.getLong("wid");

                // 获取商品列表
                String pageList = data.getString("items");
                List<StoreOut> storeOutList = JSONArray.parseArray(pageList, StoreOut.class);
                System.out.println(storeOutList);

                if (CollectionUtil.isEmpty(storeOutList)) {
                    break;
                }

                // 酒店集合
                List<SearchStore> searchStores = Lists.newArrayList();
                // 酒店图片url集合
                List<SearchStoreLogo> searchStoreLogos = Lists.newArrayList();

                storeOutList.forEach(storeOutResp -> {
                    // 酒店列表
                    SearchStore searchStore = BeanUtil.copyProperties(storeOutResp, SearchStore.class);
                    searchStore.setWid(wid);
                    searchStore.setCreateUid("weimob-store");
                    searchStore.setCreateName("微盟酒店");
                    searchStore.setCreateTime(DateUtil.date());
                    searchStore.setUpdateUid("weimob-store");
                    searchStore.setUpdateName("微盟酒店");
                    searchStore.setUpdateTime(DateUtil.date());

                    searchStores.add(searchStore);

                    // 门店图片列表
                    List<String> logoList = storeOutResp.getLogoList();
                    SearchStoreLogo searchStoreLogo = new SearchStoreLogo();
                    searchStoreLogo.setStoreId(storeOutResp.getStoreId());
                    logoList.forEach(log -> {
                        searchStoreLogo.setStoreLogo(log);
                        searchStoreLogos.add(searchStoreLogo);
                    });
                });
                // 批量入库门店信息
                searchStoreExtMapper.batchInsert(searchStores);
                log.info("酒店入库成功");

                // 批量入库门店图片列表
                searchStoreLogoExtMapper.batchInsert(searchStoreLogos);
                log.info("酒店图片入库成功");

            }
        } catch (Exception e) {
            log.error("微盟同步酒店数据异常" + e);
            return RdfaResult.fail(CommonConstant.RDFA_RESULT_FAIL_CODE, CommonConstant.RDFA_RESULT_FAIL_MSG);
        }

        return RdfaResult.success(CommonConstant.RDFA_RESULT_SUCCESS_CODE, CommonConstant.RDFA_RESULT_SUCCESS_MSG, null);
    }


    /**
     * 数据同步:直播,玩乐,游记,攻略
     */
    @Override
    public RdfaResult tourSynData(SearchDataSynBO searchDataSynBO) {
        log.info("数据同步:直播,玩乐,游记,攻略:" + searchDataSynBO);

        if (searchDataSynBO == null) {
            return RdfaResult.success(TourSearchErrorCodeEnum.DATA_SYN_NULL.getCode(), TourSearchErrorCodeEnum.DATA_SYN_NULL.getMessage(), null);
        }

        try {
            // 同步搜索平台
            log.info("正在同步" + searchDataSynBO.getSearchType() + "信息,执行" + OperateEnum.getMsgByCode(searchDataSynBO.getOperateType()));
            RdfaResult rdfaResult = searchPlantService.insertDoc(searchDataSynBO);
            if (!rdfaResult.isSuccess()) {
                return RdfaResult.fail(TourSearchErrorCodeEnum.DATA_SYN_FAILED.getCode(), TourSearchErrorCodeEnum.DATA_SYN_FAILED.getMessage());
            }

        } catch (Exception e) {
            log.error("同步直播,玩乐,游记,攻略数据异常" + e);
            return RdfaResult.fail(TourSearchErrorCodeEnum.DATA_SYN_FAILED.getCode(), TourSearchErrorCodeEnum.DATA_SYN_FAILED.getMessage());
        }

        return RdfaResult.success(CommonConstant.RDFA_RESULT_SUCCESS_CODE, CommonConstant.RDFA_RESULT_SUCCESS_MSG, null);
    }

    /**
     * 设置默认值
     *
     * @param goodsListInfoList
     * @return java.util.List<com.ennova.tour.search.dal.po.mbg.SearchGoods>
     */
    public List<SearchGoods> getGoodsInfoList(List<GoodsListInfo> goodsListInfoList) {
        List<SearchGoods> searchGoodsList = goodsListInfoList.stream().map(goodsListInfoResp ->
        {
            SearchGoods goods = BeanUtil.copyProperties(goodsListInfoResp, SearchGoods.class);
            goods.setCreateUid("weimobGoods");
            goods.setCreateName("微盟商城");
            goods.setCreateTime(DateUtil.date());
            goods.setUpdateUid("weimobGoods");
            goods.setUpdateName("微盟商城");
            goods.setUpdateTime(DateUtil.date());

            return goods;
        }).collect(Collectors.toList());

        return searchGoodsList;
    }
}

3.2 消息API实现

微盟消息接口:WeimobMessageService

import com.ennova.tour.search.client.dto.resp.CodeResp;

import java.util.LinkedHashMap;

/**
 * 微盟消息接口
 *
 * @author zrj
 * @since 2021/8/5
 **/
public interface WeimobMessageService {
    /**
     * 微盟消息API
     */
    CodeResp weimobMessage(LinkedHashMap linkedHashMap);
}

微盟消息实现类:WeimobMessageServiceImpl


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ennova.tour.search.client.dto.resp.CodeResp;
import com.ennova.tour.search.core.service.WeimobMessageService;
import com.ennova.tour.search.core.service.bo.GoodsListInfo;
import com.ennova.tour.search.core.service.constants.CommonConstant;
import com.ennova.tour.search.dal.mapper.ext.SearchGoodsExtMapper;
import com.ennova.tour.search.dal.po.mbg.SearchGoods;
import com.ennova.tour.search.integration.service.WeimobSynGoodsService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.net.URI;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 微盟消息实现类
 *
 * @author zrj
 * @since 2021/8/6
 **/
@Slf4j
@Service
public class WeimobMessageServiceImpl implements WeimobMessageService {

    @Resource
    private SearchGoodsExtMapper searchGoodsExtMapper;
    @Resource
    private WeimobSynGoodsService weimobSynGoodsService;
    @Resource(name = "redisTemplate")
    private RedisTemplate redisTemplate;

    /**
     * 微盟消息API
     */
    @Override
    public CodeResp weimobMessage(LinkedHashMap linkedHashMap) {
        log.info("微盟消息API请求对象:linkedHashMap=" + linkedHashMap);

        if (CollectionUtil.isEmpty(linkedHashMap)) {
            log.info("微盟消息API请求对象为空,暂不处理!");
            return CodeResp.codeRespFaile();
        }

        String id = String.valueOf(linkedHashMap.get("id"));
        String model = String.valueOf(linkedHashMap.get("model"));
        String topic = String.valueOf(linkedHashMap.get("topic"));
        String event = String.valueOf(linkedHashMap.get("event"));
        String msgBody = String.valueOf(linkedHashMap.get("msg_body"));
        String businessId = String.valueOf(linkedHashMap.get("business_id"));
        String publicAccountId = String.valueOf(linkedHashMap.get("public_account_id"));

        // 目前只处理商品信息
        if ("ec_goods".equals(topic)) {
            return goodsMessageHandler(event, msgBody);
        }

        log.info("微盟消息类型不支持,暂不处理!");
        return CodeResp.codeRespSuccess();
    }

    /**
     * 微盟消息商品信息处理
     * {"model":1,"id":"test_id","topic":"ec_goods","event":"goodsDelete","test":true,"business_id":"4464",
     * "public_account_id":"371629","msg_body":"{\"goodsIdList\":[27721798271]}"}
     * <p>
     * 品消息订阅网址2:
     * {"model":1,"id":"test_id","topic":"ec_goods","event":"goodsUpdate","test":true,
     * "business_id":"4464","public_account_id":"371629","msg_body":"{\"goodsIdList\":[89330122]}"}
     * <p>
     * 微盟消息API请求对象:
     * linkedHashMap={model=1, id=test_id, topic=KLD_MemberCard, event=salePriceChanged, test=true,
     * business_id=4464, public_account_id=371629, msg_body=message test to check callbackUrl!}
     */
    public CodeResp goodsMessageHandler(String event, String msgBody) {
        log.info("微盟消息商品信息处理请求参数:event=" + event + ",msgBody = " + msgBody);

        if (StrUtil.isEmpty(event) || StrUtil.isEmpty(msgBody)) {
            log.info("微盟消息商品信息处理请求参数为空,暂不处理!");
            return CodeResp.codeRespSuccess();
        }
        JSONObject jsonObject = (JSONObject) JSONObject.parse(msgBody);
        List goodsIdList = jsonObject.getJSONArray("goodsIdList");
        if (CollectionUtil.isEmpty(goodsIdList)) {
            log.info("微盟消息商品信息处理GoodsId为空,暂不处理!goodsIdList=" + goodsIdList);
            return CodeResp.codeRespSuccess();
        }

        List<SearchGoods> searchGoodsList = Lists.newArrayList();

        /**
         * 微盟消息新增商品
         */
        if ("salePriceChanged".equals(event)) {
            log.info("微盟消息新增商品,消息体为空,暂时无法处理");
            return CodeResp.codeRespSuccess();
        }

        /**
         * 删除商品信息处理
         */
        if ("goodsDelete".equals(event)) {
            goodsIdList.forEach(goodsId -> {
                SearchGoods searchGoods = new SearchGoods();
                searchGoods.setGoodsId(Long.valueOf(String.valueOf(goodsId)));
                searchGoods.setDeleted(true);

                searchGoodsList.add(searchGoods);
            });
        }

        /**
         * 微盟消息修改商品信息处理
         *触发条件:修改商家编码,批量更新sku相关信息,修改分销商品,修改商品
         * ps:新增商品不会触发该消息
         */
        if ("goodsUpdate".equals(event)) {
            goodsIdList.forEach(goodsId -> {
                SearchGoods searchGoods = getSearchGoods(String.valueOf(goodsId));
                searchGoodsList.add(searchGoods);
            });
        }

        // 微盟消息获取商品列表
        if (CollectionUtil.isEmpty(searchGoodsList)) {
            log.info("微盟消息获取商品列表为空:" + JSON.toJSONString(searchGoodsList));
            return CodeResp.codeRespSuccess();
        }

        // 微盟消息批量更新
        searchGoodsExtMapper.batchReplace(searchGoodsList);

        return CodeResp.codeRespFaile();
    }

    /**
     * 微盟消息查询商品详情
     */
    public SearchGoods getSearchGoods(String goodsIdReq) {
        log.info("微盟消息查询商品详情:goodsIdReq=" + goodsIdReq);

        // 封装结果集
        SearchGoods searchGoods = new SearchGoods();

        if (StrUtil.isEmpty(goodsIdReq)) {
            log.info("微盟消息查询商品详情请求参数为空:goodsIdReq=" + goodsIdReq);
            return searchGoods;
        }

        // 缓存中获取token,拼接URL
        String accessToken = (String) redisTemplate.opsForValue().get(CommonConstant.WEIMOB_GOODS_ACCESS_TOKEN_KEY);
        String redirectUrl = CommonConstant.GOODS_DETAIL_REDIRECT_URL + accessToken;

        try {
            // 参数构建
            Long goodsId = Long.valueOf(goodsIdReq);
            HashMap map = Maps.newHashMap();
            map.put("goodsId", goodsId);
            URI uri = new URI(redirectUrl);

            // 查询详情
            LinkedHashMap queryGoodsMap = weimobSynGoodsService.queryGoodsDetail(uri, map);
            log.info("微盟消息查询商品详情结果集:queryGoodsMap = " + queryGoodsMap);
            if (CollectionUtil.isEmpty(queryGoodsMap)) {
                log.info("微盟消息查询商品详情结果集为空:" + JSON.toJSONString(queryGoodsMap));
                return searchGoods;
            }

            // 对象解析
            JSONObject json = (JSONObject) JSON.toJSON(queryGoodsMap);
            JSONObject code = json.getJSONObject("code");
            String errcode = code.getString("errcode");
            if (!"0".equals(errcode)) {
                log.info("微盟消息查询商品详情失败:" + JSON.toJSONString(code));
                return searchGoods;
            }

            JSONObject data = json.getJSONObject("data");
            JSONObject goods = data.getJSONObject("goods");

            //Long goodsId = goods.getLong("goodsId");
            String title = goods.getString("title");
            List goodsImageUrlList = goods.getJSONArray("goodsImageUrl");
            String goodsImageUrl = "";
            if (CollectionUtil.isNotEmpty(goodsImageUrlList)) {
                goodsImageUrl = (String) goodsImageUrlList.get(0);
            }
            Integer isPutAway = goods.getInteger("isPutAway");
            Integer isMultiSku = goods.getInteger("isMultiSku");
            Integer isCanSell = goods.getInteger("isCanSell");
            Integer sellModelType = goods.getInteger("sellModelType");
            Integer isPreSell = goods.getInteger("isPreSell");

            // 类型转换
            GoodsListInfo goodsListInfo = new GoodsListInfo();
            goodsListInfo.setGoodsId(goodsId);
            goodsListInfo.setTitle(title);
            goodsListInfo.setDefaultImageUrl(goodsImageUrl);
            goodsListInfo.setIsPutAway(isPutAway);
            goodsListInfo.setIsMultiSku(isMultiSku);
            goodsListInfo.setCanSell(isCanSell == 0 ? false : true);
            goodsListInfo.setSellModelType(sellModelType);
            goodsListInfo.setIsPreSell(isPreSell);

            // 详情中不存在数据
            //goodsListInfo.setMaxPrice();
            //goodsListInfo.setMinPrice();
            //goodsListInfo.setAvaliableStockNum();
            //goodsListInfo.setSalesNum();
            //goodsListInfo.setPutAwayDate();
            //goodsListInfo.setSortNum();
            //goodsListInfo.setIsExistEmptyStock();
            //goodsListInfo.setIsAllStockEmpty();

            BeanUtil.copyProperties(goodsListInfo, SearchGoods.class);
            return searchGoods;
        } catch (Exception e) {
            log.info("微盟消息查询商品详情异常:" + e);
        }
        return searchGoods;
    }
}

微盟消息API:WeimobMessageController

import com.ennova.tour.search.client.dto.resp.CodeResp;
import com.ennova.tour.search.client.service.WeimobMessageRpcService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedHashMap;

/**
 * 微盟消息API
 *
 * @author zrj
 * @since 2021/8/6
 **/
@Api(tags = "微盟消息API")
@RestController
@RequestMapping("/app/search")
public class WeimobMessageController {
    @Resource
    private WeimobMessageService weimobMessageService;
    
    @ApiOperation(value = "微盟消息")
    @PostMapping("/message")
    public CodeResp weimobMessage(@RequestBody(required = false) LinkedHashMap linkedHashMap) {
        return weimobMessageService.weimobMessage(linkedHashMap);
    }
}

标签:search,商品信息,Java,String,API,微盟,import,com,log
来源: https://blog.csdn.net/m0_37583655/article/details/119475982