Home >WeChat Applet >WeChat Development >C# develops WeChat portal and applies encapsulation and testing of WeChat store product management interface

C# develops WeChat portal and applies encapsulation and testing of WeChat store product management interface

高洛峰
高洛峰Original
2017-03-01 10:51:061502browse

1. Definition of product management interface

The previous article introduced the object model of WeChat store, as shown below.

C# develops WeChat portal and applies encapsulation and testing of WeChat store product management interface

This graphic basically covers the related objects of the WeChat store and introduces the relationship between them.

We start with basic product information management. We know that the product interface includes interfaces for adding, modifying, querying, deleting, etc., as shown below.

C# develops WeChat portal and applies encapsulation and testing of WeChat store product management interface

Product information is the foundation of all micro-stores, so we need to be clearer and more complete in its management operations.

To sum up the functions mentioned above, we can define the interface of WeChat products as follows.

#region 商品信息
        /// <summary>
        /// 创建商品
        /// </summary>
        /// <param>调用接口凭证
        /// <param>商品对象
        /// <returns></returns>
        AddMerchantResult AddMerchant(string accessToken, MerchantJson merchantJson);

        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param>调用接口凭证
        /// <param>商品ID
        /// <returns></returns>
        CommonResult DeleteMerchant(string accessToken, string productId);

        /// <summary>
        /// 修改商品
        /// product_id表示要更新的商品的ID,其他字段说明请参考增加商品接口。
        /// 从未上架的商品所有信息均可修改,否则商品的名称(name)、商品分类(category)、商品属性(property)这三个字段不可修改。
        /// </summary>
        /// <param>调用接口凭证
        /// <param>修改商品的信息
        /// <returns></returns>
        CommonResult UpdateMerchant(string accessToken, MerchantJson merchantJson);

        /// <summary>
        /// 根据ID查询商品信息,如果成功返回MerchantJson信息,否则返回null
        /// </summary>
        /// <param>调用接口凭证
        /// <param>商品的Id
        /// <returns></returns>
        MerchantJson GetMerchant(string accessToken, string productId);

        /// <summary>
        /// 获取指定状态的所有商品
        /// </summary>
        /// <param>调用接口凭证
        /// <param>商品状态(0-全部, 1-上架, 2-下架)
        /// <returns></returns>
        List<merchantjson> GetMerchantByStatus(string accessToken, int status);

        /// <summary>
        /// 商品上下架
        /// </summary>
        /// <param>调用接口凭证
        /// <param>商品上下架标识(0-下架, 1-上架)
        /// <returns></returns>
        CommonResult UpdateMerchantStatus(string accessToken, string productId, int status); 

        #endregion</merchantjson>

Of course, WeChat products also include basic management of categories, category attributes, and category SKUs, so product management also needs to add this content

C# develops WeChat portal and applies encapsulation and testing of WeChat store product management interface

Their functional interface definitions are as follows. Through the following interface, we can easily obtain information such as product classification (not product grouping), SKU information, and classification attributes.

#region 商品分类及属性
        /// <summary>
        /// 获取指定分类的所有子分类
        /// </summary>
        /// <param>调用接口凭证
        /// <param>大分类ID(根节点分类id为1)
        /// <returns></returns>
        List<subcategory> GetSub(string accessToken, int cate_id);

        /// <summary>
        /// 获取指定子分类的所有SKU
        /// </summary>
        /// <param>调用接口凭证
        /// <param>商品子分类ID
        /// <returns></returns>
        List<subcategorysku> GetSku(string accessToken, int cate_id);

        /// <summary>
        /// 获取指定分类的所有属性
        /// </summary>
        /// <param>调用接口凭证
        /// <param>分类ID
        /// <returns></returns>
        List<subcategoryproperty> GetProperty(string accessToken, int cate_id); 

        #endregion</subcategoryproperty></subcategorysku></subcategory>

2. Implementation of product management interface

The above interface defines the interface of the corresponding product.

For the implementation of the interface, we generally submit it to the URL according to the interface description of the official website, and POST the data, and then organize it into a regular processing method, obtain the result and convert it into the corresponding object That’s it. For example, the implementation code of adding product operation is as follows.

/// <summary>
        /// 创建商品
        /// </summary>
        /// <param>调用接口凭证
        /// <param>商品对象
        /// <returns></returns>
        public AddMerchantResult AddMerchant(string accessToken, MerchantJson merchantJson)
        {
            var url = string.Format("https://api.weixin.qq.com/merchant/create?access_token={0}", accessToken);
            string postData = merchantJson.ToJson();

            return JsonHelper<addmerchantresult>.ConvertJson(url, postData);
        }</addmerchantresult>

To return the result, this is to define an object to obtain the ID of the added product and other contents, as shown below.

/// 
/// Return result of creating product information
///

public class AddMerchantResult: ErrorJsonResult
{
                                                                                                                                                            ​ 


/// <summary>
    /// 微信返回Json结果的错误数据
    /// </summary>
    public class ErrorJsonResult 
    {
        /// <summary>
        /// 返回代码
        /// </summary>
        public ReturnCode errcode { get; set; }

        /// <summary>
        /// 错误消息
        /// </summary>
        public string errmsg { get; set; }
    }

Through the definition of these objects, after adding the product, we will know whether the operation is successful. If the addition is successful, a newly created ID will be returned for us to use. , we can query specific product information or perform operations such as modification and deletion.

The modification or deletion of product information only needs to return a record of success, so we define a unified response object CommonResult. The interface implementation code for product modification and deletion is as follows.

Since I have highly improved and organized the code, it is relatively easy to understand the various processing codes.

/// <summary>
        /// 删除商品
        /// </summary>
        /// <param>调用接口凭证
        /// <param>商品ID
        /// <returns></returns>
        public CommonResult DeleteMerchant(string accessToken, string productId)
        {
            var url = string.Format("https://api.weixin.qq.com/merchant/del?access_token={0}", accessToken);
            var data = new
            {
                product_id = productId
            };
            string postData = data.ToJson();

            return Helper.GetExecuteResult(url, postData);
        }

        /// <summary>
        /// 修改商品
        /// product_id表示要更新的商品的ID,其他字段说明请参考增加商品接口。
        /// 从未上架的商品所有信息均可修改,否则商品的名称(name)、商品分类(category)、商品属性(property)这三个字段不可修改。
        /// </summary>
        /// <param>调用接口凭证
        /// <param>修改商品的信息
        /// <returns></returns>
        public CommonResult UpdateMerchant(string accessToken, MerchantJson merchantJson)
        {
            var url = string.Format("https://api.weixin.qq.com/merchant/update?access_token={0}", accessToken);
            string postData = merchantJson.ToJson();

            return Helper.GetExecuteResult(url, postData);
        }

In order to obtain the detailed information of the product, we need to define an entity object of the product so that we can convert the obtained information into entity class information for easy use. and processing.

The product information includes many small defined classes, which constitute the content of each part of the product. The main entity class information is as follows.

After defining the relatively complex product information entity, we can process it through objects.

The implementation code for obtaining product details is as follows. C# develops WeChat portal and applies encapsulation and testing of WeChat store product management interface

        /// <summary>
        /// 根据ID查询商品信息,如果成功返回MerchantJson信息,否则返回null        /// </summary>
        /// <param>调用接口凭证
        /// <param>商品的Id
        /// <returns></returns>
        public MerchantJson GetMerchant(string accessToken, string productId)
        {            var url = string.Format("http://www.php.cn/{0}", accessToken);            var data = new
            {
                product_id = productId
            };            string postData = data.ToJson();

            MerchantJson merchant = null;
            GetMerchantResult result = JsonHelper<getmerchantresult>.ConvertJson(url, postData);            if (result != null)
            {
                merchant = result.product_info;
            }            return merchant;
        }</getmerchantresult>

Although the entity information of the product is very complex, once we define it, it is easy for us to convert and process the results. The above code is not It's hard to understand. The main thing is to convert the data after submitting it.

Of course, we can also get the product list content in different states, as shown in the following code.

/// <summary>
        /// 获取指定状态的所有商品
        /// </summary>
        /// <param>调用接口凭证
        /// <param>商品状态(0-全部, 1-上架, 2-下架)
        /// <returns></returns>
        public List<merchantjson> GetMerchantByStatus(string accessToken, int status)
        {
            var url = string.Format("https://api.weixin.qq.com/merchant/getbystatus?access_token={0}", accessToken);
            var data = new
            {
                status = status
            };
            string postData = data.ToJson();

            List<merchantjson> list = new List<merchantjson>();
            GetMerchantByStatus result = JsonHelper<getmerchantbystatus>.ConvertJson(url, postData);
            if (result != null)
            {
                list = result.products_info;
            }
            return list;
        }</getmerchantbystatus></merchantjson></merchantjson></merchantjson>

When we add products, the product classification information, classification attributes, and classification SKU information are also very important. We need to specify the corresponding product classification. Only then can it be added to the WeChat store.

获取商品分类的操作实现代码如下所示。

/// <summary>
        /// 获取指定分类的所有子分类
        /// </summary>
        /// <param>调用接口凭证
        /// <param>大分类ID(根节点分类id为1)
        /// <returns></returns>
        public List<subcategory> GetSub(string accessToken, int cate_id)
        {
            var url = string.Format("https://api.weixin.qq.com/merchant/category/getsub?access_token={0}", accessToken);
            var data = new
            {
                cate_id = cate_id
            };
            string postData = data.ToJson();

            List<subcategory> list = new List<subcategory>();
            GetSubResult result = JsonHelper<getsubresult>.ConvertJson(url, postData);
            if(result != null)
            {
                list = result.cate_list;
            }
            return list;
        }</getsubresult></subcategory></subcategory></subcategory>

 

3、商品管理接口的测试

为了验证我们开发的接口,我们需要增加一个测试项目,方便对我们编写的API进行测试,测试完全成功后,我们才能正式在项目中使用。

我为了方便,创建了一个Winform项目,分别对各个接口进行测试。

C# develops WeChat portal and applies encapsulation and testing of WeChat store product management interface

本篇主要介绍商品管理方面的接口,因此下面主要介绍其中商品管理部分的接口测试代码,以及对应的结果。

其中商品常规管理的接口测试代码如下所示。

private void btnMerchant_Click(object sender, EventArgs e)
        {
            //商品管理
            IMerchantApi api = new MerchantApi();

            //获取所有商品信息
            Console.WriteLine("获取所有商品信息");
            List<merchantjson> list = api.GetMerchantByStatus(token, 0);
            foreach(MerchantJson json in list)
            {
                Console.WriteLine(json.ToJson());
                Console.WriteLine();
            }

            //更新商品状态
            Console.WriteLine("更新商品状态");
            foreach (MerchantJson json in list)
            {
                CommonResult result = api.UpdateMerchantStatus(token, json.product_id, 1);
                Console.WriteLine("商品ID:{0},商品名称:{1}, 操作:{2}", 
                    json.product_id, json.product_base.name, result.Success ? "成功" : "失败");
            }

            Thread.Sleep(1000);
            //根据商品ID获取商品信息
            Console.WriteLine("根据商品ID获取商品信息");
            foreach (MerchantJson json in list)
            {
                MerchantJson getJson = api.GetMerchant(token, json.product_id);
                if(json != null)
                {
                    Console.WriteLine("商品ID:{0},商品名称:{1}", getJson.product_id, getJson.product_base.name);
                }
            }
        }</merchantjson>

测试后结果如下所示(就是返回我微店铺里面的商品信息),一切正常。

返回的商品Json数据如下所示:

{
  "product_id": "pSiLnt6FYDuFtrRRPMlkdKbye-rE",
  "product_base": {
    "category_id": [
      "537103312"
    ],
    "property": [
      {
        "id": "类型",
        "vid": "软件产品设计"
      }
    ],
    "name": "代码生成工具Database2Sharp",
    "sku_info": [],
    "main_img": "http://mmbiz.qpic.cn/mmbiz/mLqH9gr11Gyb2sgiaelcsxYtQENGePp0Rb3AZKbjkicnKTUNBrEdo7Dyic97ar46SoAfKRB5x2R94bDUdNpgqiaZzA/0",
    "img": [
      "http://mmbiz.qpic.cn/mmbiz/mLqH9gr11Gyb2sgiaelcsxYtQENGePp0RiaheJmVXm7tbvTYUQV7OF3DgfGiaQVMh3WbeEcGDOQQiajQXGKK9tfoeA/0"
    ],
    "detail": [],
    "buy_limit": 0,
    "detail_html": ""
  },
  "sku_list": [
    {
      "sku_id": "",
      "ori_price": 100000,
      "price": 50000,
      "icon_url": "",
      "quantity": 1100,
      "product_code": ""
    }
  ],
  "attrext": {
    "location": {
      "country": "中国",
      "province": "广东",
      "city": "广州",
      "address": ""
    },
    "isPostFree": 1,
    "isHasReceipt": 0,
    "isUnderGuaranty": 0,
    "isSupportReplace": 0
  },
  "delivery_info": {
    "delivery_type": 0,
    "template_id": 175807970,
    "express": [
      {
        "id": 10000027,
        "price": 0
      },
      {
        "id": 10000028,
        "price": 0
      },
      {
        "id": 10000029,
        "price": 0
      }
    ]
  },
  "status": 1
}

测试的部分结果输出如下所示。

C# develops WeChat portal and applies encapsulation and testing of WeChat store product management interface

另外,“商品维护管理”的功能测试主要就是测试商品的增加、修改、删除操作,具体代码如下所示。

private void btnMerchantEdit_Click(object sender, EventArgs e)
        {
            IMerchantApi api = new MerchantApi();
            string img1 = "http://mmbiz.qpic.cn/mmbiz/4whpV1VZl2iccsvYbHvnphkyGtnvjD3ulEKogfsiaua49pvLfUS8Ym0GSYjViaLic0FD3vN0V8PILcibEGb2fPfEOmw/0";
            string img2 = "http://mmbiz.qpic.cn/mmbiz/4whpV1VZl2iccsvYbHvnphkyGtnvjD3ul1UcLcwxrFdwTKYhH9Q5YZoCfX4Ncx655ZK6ibnlibCCErbKQtReySaVA/0";
            string img3 = "http://mmbiz.qpic.cn/mmbiz/4whpV1VZl28bJj62XgfHPibY3ORKicN1oJ4CcoIr4BMbfA8LqyyjzOZzqrOGz3f5KWq1QGP3fo6TOTSYD3TBQjuw/0";

            //商品增删改处理
            MerchantJson merchant = new MerchantJson();
            merchant.product_base = new Merchant_base();
            merchant.product_base.name = "测试产品";
            merchant.product_base.category_id.Add("537074298");
            merchant.product_base.img = new List<string>() { img1, img2, img3 };
            merchant.product_base.main_img = img1;
            merchant.product_base.detail.AddRange(new List<merchantdetail>() {
                    new MerchantDetail()
                    {
                        text = "test first"
                    },
                    new MerchantDetail()
                    {
                        img = img2
                    }, new MerchantDetail()
                    {
                        text = "test again"
                    }
            });
            merchant.product_base.property.AddRange(new List<merchantproperty>(){
                new MerchantProperty
                {
                    id= "1075741879",
                    vid="1079749967"
                },
                new MerchantProperty{
                    id= "1075754127",
                    vid= "1079795198"
                },
                new MerchantProperty(){
                    id= "1075777334",
                    vid= "1079837440"
                }
            });
            merchant.product_base.sku_info.AddRange(new List<merchantsku>(){
                new MerchantSku{
                    id=  "1075741873",
                    vid = new List<string>() {
                        "1079742386",
                        "1079742363"
                    }
                }
            });
            merchant.product_base.buy_limit = 10;
            //merchant.product_base.detail_html = "<div><img  alt="C# develops WeChat portal and applies encapsulation and testing of WeChat store product management interface" ></div>
<p>test</p>
<div><img  alt="C# develops WeChat portal and applies encapsulation and testing of WeChat store product management interface" ></div>
<p>test again</p>";
            merchant.sku_list.AddRange(new List<merchantsku_list>()
            {
                new MerchantSku_list(){
                sku_id="1075741873:1079742386",
                price=30,
                icon_url="http://mmbiz.qpic.cn/mmbiz/4whpV1VZl2iccsvYbHvnphkyGtnvjD3ulEKogfsiaua49pvLfUS8Ym0GSYjViaLic0FD3vN0V8PILcibEGb2fPfEOmw/0",
                quantity=800,
                product_code="testing",
                ori_price=9000000
                },
                new MerchantSku_list(){
                    sku_id="1075741873:1079742363",
                    price=30,
                    icon_url="http://mmbiz.qpic.cn/mmbiz/4whpV1VZl28bJj62XgfHPibY3ORKicN1oJ4CcoIr4BMbfA8LqyyjzOZzqrOGz3f5KWq1QGP3fo6TOTSYD3TBQjuw/0",
                    quantity=800,
                    product_code="testingtesting",
                    ori_price=9000000
                }
            });
            merchant.attrext = new MerchantAttrext()
            {
                location = new MerchantLocation()
                {
                    country = "中国",
                    province = "广东省",
                    city = "广州市",
                    address = "T.I.T创意园"
                },
                isPostFree = 0,
                isHasReceipt = 1,
                isUnderGuaranty = 0,
                isSupportReplace = 0
            };
            merchant.delivery_info = new MerchantDelivery()
            {
                delivery_type = 0,
                template_id = 0,
                express = new List<merchantexpress>(){
                new MerchantExpress() {
                    id=10000027, 
                    price=100
                }, 
                new MerchantExpress(){
                    id=10000028, 
                    price=100
                }, 
                new MerchantExpress(){
                    id=10000029, 
                    price=100
                }}
            };

            Console.WriteLine(merchant.ToJson());

            AddMerchantResult result = api.AddMerchant(token, merchant);
            Console.WriteLine("添加商品:{0}", result.product_id);
            if (!string.IsNullOrEmpty(result.product_id))
            {
                //更新商品
                merchant.product_id = result.product_id;
                merchant.product_base.name = "测试产品22";
                CommonResult updateResult = api.UpdateMerchant(token, merchant);
                Console.WriteLine("更新商品:{0}", updateResult.Success ? "成功" : "失败");


                CommonResult deleteResult = api.DeleteMerchant(token, merchant.product_id);
                Console.WriteLine("删除商品:{0}", deleteResult.Success ? "成功" : "失败");
            }
        }</merchantexpress></merchantsku_list></string></merchantsku></merchantproperty></merchantdetail></string>

测试的输出结果如下所示(一切成功)。

C# develops WeChat portal and applies encapsulation and testing of WeChat store product management interface

以上就是我对商品管理接口的API定义和实现,以及对接口进行测试的阐述,基本上把所有相关的内容都贴出来了,希望大家能够对微店开发部分,有更深入的了解和认识。

 更多C# develops WeChat portal and applies encapsulation and testing of WeChat store product management interface相关文章请关注PHP中文网!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn