Home  >  Article  >  WeChat Applet  >  C# development of WeChat portal and application-encapsulation and testing of WeChat store product management interface

C# development of WeChat portal and application-encapsulation and testing of WeChat store product management interface

高洛峰
高洛峰Original
2017-02-18 09:53:491448browse

In the previous article "Developing WeChat Portals and Applications in C# (22) - Development and Use of WeChat Stores", some basic knowledge of WeChat stores and the corresponding object model were introduced. This article continues the theme of WeChat stores. , introducing the encapsulation and testing use of the API interface. The relevant object models of WeChat stores basically include regular products, product groupings, shelves, inventory, and order models, as well as product classification, product classification attributes, product classification SKU, express mailing templates, image management and other functions. The interface encapsulation introduced in this article is based on these contents, and is tested and used for the implementation of the interface.

1. Definition of product management interface

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

C#开发微信门户及应用-微信小店商品管理接口的封装和测试

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#开发微信门户及应用-微信小店商品管理接口的封装和测试

#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 name="accessToken">调用接口凭证</param>
        /// <param name="merchantJson">商品对象</param>
        /// <returns></returns>
        AddMerchantResult AddMerchant(string accessToken, MerchantJson merchantJson);        /// <summary>
        /// 删除商品        /// </summary>
        /// <param name="accessToken">调用接口凭证</param>
        /// <param name="productId">商品ID</param>
        /// <returns></returns>
        CommonResult DeleteMerchant(string accessToken, string productId);        /// <summary>
        /// 修改商品        /// product_id表示要更新的商品的ID,其他字段说明请参考增加商品接口。        /// 从未上架的商品所有信息均可修改,否则商品的名称(name)、商品分类(category)、商品属性(property)这三个字段不可修改。        /// </summary>
        /// <param name="accessToken">调用接口凭证</param>
        /// <param name="merchantJson">修改商品的信息</param>
        /// <returns></returns>
        CommonResult UpdateMerchant(string accessToken, MerchantJson merchantJson);        /// <summary>
        /// 根据ID查询商品信息,如果成功返回MerchantJson信息,否则返回null        /// </summary>
        /// <param name="accessToken">调用接口凭证</param>
        /// <param name="productId">商品的Id</param>
        /// <returns></returns>
        MerchantJson GetMerchant(string accessToken, string productId);        /// <summary>
        /// 获取指定状态的所有商品        /// </summary>
        /// <param name="accessToken">调用接口凭证</param>
        /// <param name="status">商品状态(0-全部, 1-上架, 2-下架)</param>
        /// <returns></returns>
        List<MerchantJson> GetMerchantByStatus(string accessToken, int status);        /// <summary>
        /// 商品上下架        /// </summary>
        /// <param name="accessToken">调用接口凭证</param>
        /// <param name="status">商品上下架标识(0-下架, 1-上架)</param>
        /// <returns></returns>
        CommonResult UpdateMerchantStatus(string accessToken, string productId, int status); 

        #endregion

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#开发微信门户及应用-微信小店商品管理接口的封装和测试

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 name="accessToken">调用接口凭证</param>
        /// <param name="cateId">大分类ID(根节点分类id为1)</param>
        /// <returns></returns>
        List<SubCategory> GetSub(string accessToken, int cate_id);        /// <summary>
        /// 获取指定子分类的所有SKU        /// </summary>
        /// <param name="accessToken">调用接口凭证</param>
        /// <param name="cateId">商品子分类ID</param>
        /// <returns></returns>
        List<SubCategorySku> GetSku(string accessToken, int cate_id);        /// <summary>
        /// 获取指定分类的所有属性        /// </summary>
        /// <param name="accessToken">调用接口凭证</param>
        /// <param name="cateId">分类ID</param>
        /// <returns></returns>
        List<SubCategoryProperty> GetProperty(string accessToken, int cate_id); 

        #endregion

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 name="accessToken">调用接口凭证</param>
        /// <param name="merchantJson">商品对象</param>
        /// <returns></returns>
        public AddMerchantResult AddMerchant(string accessToken, MerchantJson merchantJson)
        {            var url = string.Format("http://www.php.cn/{0}", accessToken);            string postData = merchantJson.ToJson();            return JsonHelper<AddMerchantResult>.ConvertJson(url, postData);
        }

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

    /// <summary>
    /// 创建商品信息的返回结果    /// </summary>
    public class AddMerchantResult : ErrorJsonResult
    {        /// <summary>
        /// 商品ID        /// </summary>
        public string product_id { get; set; }
    }

And the base class is the regular response content

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

Through these objects Definition, after adding a 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 modification, deletion and other operations.

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 name="accessToken">调用接口凭证</param>
        /// <param name="productId">商品ID</param>
        /// <returns></returns>
        public CommonResult DeleteMerchant(string accessToken, string productId)
        {            var url = string.Format("http://www.php.cn/{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 name="accessToken">调用接口凭证</param>
        /// <param name="merchantJson">修改商品的信息</param>
        /// <returns></returns>
        public CommonResult UpdateMerchant(string accessToken, MerchantJson merchantJson)
        {            var url = string.Format("http://www.php.cn/{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.

C#开发微信门户及应用-微信小店商品管理接口的封装和测试

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

The implementation code for obtaining product details is as follows.

        /// <summary>
        /// 根据ID查询商品信息,如果成功返回MerchantJson信息,否则返回null        /// </summary>
        /// <param name="accessToken">调用接口凭证</param>
        /// <param name="productId">商品的Id</param>
        /// <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;
        }

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 name="accessToken">调用接口凭证</param>
        /// <param name="status">商品状态(0-全部, 1-上架, 2-下架)</param>
        /// <returns></returns>
        public List<MerchantJson> GetMerchantByStatus(string accessToken, int status)
        {            var url = string.Format("http://www.php.cn/{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;
        }

我们添加商品的时候,商品的分类信息、分类属性、分类SKU信息也都是很重要的内容,我们需要指定对应商品分类才能添加到微信小店里面。

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

        /// <summary>
        /// 获取指定分类的所有子分类        /// </summary>
        /// <param name="accessToken">调用接口凭证</param>
        /// <param name="cateId">大分类ID(根节点分类id为1)</param>
        /// <returns></returns>
        public List<SubCategory> GetSub(string accessToken, int cate_id)
        {            var url = string.Format("http://www.php.cn/{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;
        }

 

3、商品管理接口的测试

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

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

C#开发微信门户及应用-微信小店商品管理接口的封装和测试

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

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

        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);
                }
            }
        }

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

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

{  "product_id": "pSiLnt6FYDuFtrRRPMlkdKbye-rE",  "product_base": {    "category_id": [      "537103312"
    ],    "property": [
      {        "id": "类型",        "vid": "软件产品设计"
      }
    ],    "name": "代码生成工具Database2Sharp",    "sku_info": [],    "main_img": "http://www.php.cn/",    "img": [      "http://www.php.cn/"
    ],    "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}

View Code

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

C#开发微信门户及应用-微信小店商品管理接口的封装和测试

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

        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/0n/";            
            string img3 = "http://mmbiz.qpic.cn/mmbiz/4whpV1VZl28bJj62XgfHPibY3ORKicN1oJ4CcoIr4BMbfA8LqyyjzOZzqrOGz3f5KWq1QGP3fo6TOTSYD3TBQjuw/0n/";            
            //商品增删改处理
            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 = "<p class=\"item_pic_wrp\" style=\"margin-bottom:8px;font-size:0;\"><img class=\"item_pic\" style=\"width:100%;\" alt=\"\" src=\"http://www.php.cn/\" ></p><p style=\"margin-bottom:11px;margin-top:11px;\">test</p><p class=\"item_pic_wrp\" style=\"margin-bottom:8px;font-size:0;\"><img class=\"item_pic\" style=\"width:100%;\" alt=\"\" src=\"http://www.php.cn/\" ></p><p style=\"margin-bottom:11px;margin-top:11px;\">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 ? "成功" : "失败");
            }
        }

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

C#开发微信门户及应用-微信小店商品管理接口的封装和测试

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

 更多C#开发微信门户及应用-微信小店商品管理接口的封装和测试 相关文章请关注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