小程序模板消息--发送模板消息

接口地址:https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=ACCESS_TOKEN

HTTP请求方式:post


POST参数说明

参数必填说明
touser 接收者(用户)的 openid
template_id 所需下发的模板消息的id
page 点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例index?foo=bar)。该字段不填则模板无跳转。
form_id 表单提交场景下,为 submit 事件带上的 formId;支付场景下,为本次支付的 prepay_id
data 模板内容,不填则下发空模板
color 模板内容字体的颜色,不填默认黑色
emphasis_keyword 模板需要放大的关键词,不填则默认无放大

 

 

 

本实例的form_id参数为支付场景下的prepay_id

自己封装的模板消息发送接口:(C# WebApi)

自己封装的post的接口参数:

#region 发送模板消息
    public class PostSendTemplete
    {
        /// <summary>
        /// 加密的
        /// </summary>
        public string shopid { get; set; }

        /// <summary>
        /// 付款成功通知  AT0005 
        /// 付款失败通知  AT0006
        /// 待付款提醒    AT0008
        /// 退款通知      AT0036
        /// </summary>
        public string temptype { get; set; }

        /// <summary>
        /// 接收者(用户)的 openid
        /// </summary>
        public string openid { get; set; }


        /// <summary>
        /// 点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例index?foo=bar)。该字段不填则模板无跳转。
        /// </summary>
        public string page { get; set; }

        /// <summary>
        /// 表单提交场景下,为 submit 事件带上的 formId;支付场景下,为本次支付的 prepay_id
        /// </summary>
        public string form_id { get; set; }

        /// <summary>
        /// 内容
        /// </summary>
        public string content { get; set; }

        /// <summary>
        /// 模板需要放大的关键词,不填则默认无放大
        /// </summary>
        public string emphasis_keyword { get; set; }

    }


    #endregion

  封装的post的小程序接口参数

/// <summary>
    /// 小程序模板消息模板
    /// </summary>
    public class WxaTempleteModel
    {
        /// <summary>
        /// 是	接收者(用户)的 openid
        /// </summary>
        public string touser { get; set; }

        /// <summary>
        /// 是	所需下发的模板消息的id
        /// </summary>
        public string template_id { get; set; }

        /// <summary>
        /// 否	点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例index?foo=bar)。该字段不填则模板无跳转。
        /// </summary>
        public string page { get; set; }

        /// <summary>
        /// 是	表单提交场景下,为 submit 事件带上的 formId;支付场景下,为本次支付的 prepay_id
        /// </summary>
        public string form_id { get; set; }

        /// <summary>
        /// 是	模板内容,不填则下发空模板
        /// </summary>
        public object data { get; set; }

        /// <summary>
        /// 否	模板内容字体的颜色,不填默认黑色
        /// </summary>
        public string color { get; set; }

        /// <summary>
        /// 否	模板需要放大的关键词,不填则默认无放大
        /// </summary>
        public string emphasis_keyword { get; set; }
    }

    #region  付款成功通知  AT0005
    /// <summary>
    ///  //付款成功通知
    //{"keyword_id":13,"name":"商家名称","example":"早安豆浆店"}{"keyword_id":16,"name":"门店","example":"汽车4s店"} {"keyword_id":22,"name":"订单编号","example":"123658635455"}  {"keyword_id":27,"name":"商品信息","example":"鱼香肉丝"},  {"keyword_id":3,"name":"付款金额","example":"8元"}
    /// </summary>
    public class PaySuccessTemplete
    {
        /// <summary>
        /// {"keyword_id":13,"name":"商家名称","example":"早安豆浆店"}
        /// </summary>
        public TempleteItemData keyword1 { get; set; }

        /// <summary>
        /// {"keyword_id":16,"name":"门店","example":"汽车4s店"}
        /// </summary>
        public TempleteItemData keyword2 { get; set; }

        /// <summary>
        /// {"keyword_id":22,"name":"订单编号","example":"123658635455"} 
        /// </summary>
        public TempleteItemData keyword3 { get; set; }

        /// <summary>
        /// {"keyword_id":27,"name":"商品信息","example":"鱼香肉丝"}
        /// </summary>
        public TempleteItemData keyword4 { get; set; }

        /// <summary>
        /// {"keyword_id":3,"name":"付款金额","example":"8元"}
        /// </summary>
        public TempleteItemData keyword5 { get; set; }
    }
    #endregion

  

后台接口代码

#region 发送模板消息
        [HttpPost]
        public Result SendTemplete(PostSendTemplete model)
        {
            Logger.Debug("发送模板接口:3" + JsonConvert.SerializeObject(model));
            if (string.IsNullOrWhiteSpace(model.shopid))
            {
                _result.success = false;
                _result.message = "商户号为空";
                return _result;
            }

            if (string.IsNullOrWhiteSpace(model.form_id))
            {
                _result.success = false;
                _result.message = "form_id为空";
                return _result;
            }

            if (string.IsNullOrWhiteSpace(model.openid))
            {
                _result.success = false;
                _result.message = "微信ID为空";
                return _result;
            }

            if (string.IsNullOrWhiteSpace(model.temptype))
            {
                _result.success = false;
                _result.message = "模板类别为空";
                return _result;
            }

            try
            {
                var shopid = DESEncrypt.Decrypt(model.shopid);
                var wxAppSet = _wxAppSetService.GetFromCache(shopid);
                var wxaTemplete = new t_wxa_templete();
                if (_wxaTempleteService.Exists(a => a.shopid == shopid && a.templete_type == model.temptype))
                {
                    wxaTemplete = _wxaTempleteService.Get(a => a.shopid == shopid && a.templete_type == model.temptype);
                }
                else
                {
                    var componentToken2 = Senparc.Weixin.MP.Sample.CommonService.Custom.TokenHelper.GetComponentAccessToken(component_AppId, component_Secret).component_access_token;
                    var authToken2 = Senparc.Weixin.MP.Sample.CommonService.Custom.TokenHelper.GetAuthorizerAccessToken(component_AppId, componentToken2, wxAppSet.appid, wxAppSet.authorizer_refresh_token).authorizer_access_token;
                    // var data = Senparc.Weixin.WxOpen.AdvancedAPIs.Template.TemplateApi.Add(authToken, temptype, intKws);
                    var url2 = "https://api.weixin.qq.com/cgi-bin/wxopen/template/add?access_token=" + authToken2;
                    var obj2 = new PostAddTemplete();
                    obj2.id = model.temptype;
                    switch (model.temptype)
                    {
                        case "AT0005"://付款成功通知

                            obj2.keyword_id_list = new int[5] { 13, 16, 22, 27, 3 };
                            break;
                        case "AT0006"://付款失败通知
                            obj2.keyword_id_list = new int[4] { 10, 11, 20, 2 };
                            break;
                        case "AT0008"://待付款提醒
                            obj2.keyword_id_list = new int[5] { 8, 33, 6, 9, 4 };
                            break;
                        case "AT0036"://退款通知
                            obj2.keyword_id_list = new int[5] { 14, 65, 4, 35, 5 };
                            break;
                        default:
                            _result.success = false;
                            _result.message = "未知模板类型";
                            return _result;
                            break;
                    }

                    var data2 = JsonConvert.DeserializeObject<AddTempleteResult>(SissO2O.Framework.Common.NetHelper.WxAppHttpPost(url2, obj2, SerializationType.Json));
                    Logger.Debug("data=" + JsonConvert.SerializeObject(data2));
                    if (data2.errcode == 0)
                    {
                        var templete = new t_wxa_templete();
                        templete = new t_wxa_templete();
                        templete.operdate = DateTime.Now;
                        templete.shopid = shopid;
                        templete.templete_id = data2.template_id;
                        templete.templete_type = model.temptype;
                        templete.keyword_id_list = obj2.keyword_id_list.ToList().ToString();
                        _wxaTempleteService.Add(templete);
                        _wxaTempleteService.Commit();
                    }
                    else
                    {
                        _result.message = "错误代码:" + data2.errcode + "  " + data2.errmsg;
                        _result.success = false;
                    }
                }
                Logger.Debug("wxaTemplete=" + JsonConvert.SerializeObject(wxaTemplete));

                var temppleteModel = new WxaTempleteModel();
                temppleteModel.template_id = wxaTemplete.templete_id;
                temppleteModel.page = model.page;
                temppleteModel.color = "#173177";
                temppleteModel.emphasis_keyword = model.emphasis_keyword;
                temppleteModel.form_id = model.form_id;
                temppleteModel.touser = model.openid;

                switch (model.temptype)
                {
                    case "AT0005"://付款成功通知
                        temppleteModel.data = JsonConvert.DeserializeObject<PaySuccessTemplete>(model.content);
                        break;
                    case "AT0006"://付款失败通知
                        temppleteModel.data = JsonConvert.DeserializeObject<PayFailTemplete>(model.content);
                        break;
                    case "AT0008"://待付款提醒
                        temppleteModel.data = JsonConvert.DeserializeObject<PayWaitTemplete>(model.content);
                        break;
                    case "AT0036"://退款通知
                        temppleteModel.data = JsonConvert.DeserializeObject<PayRefundTemplete>(model.content);
                        break;
                    default:
                        _result.success = false;
                        _result.message = "未知模板类型";
                        return _result;
                        break;
                }
                Logger.Debug("temppleteModel=" + JsonConvert.SerializeObject(temppleteModel));
                var componentToken = Senparc.Weixin.MP.Sample.CommonService.Custom.TokenHelper.GetComponentAccessToken(component_AppId, component_Secret).component_access_token;
                Logger.Debug("componentToken=" + componentToken);
                var authToken = Senparc.Weixin.MP.Sample.CommonService.Custom.TokenHelper.GetAuthorizerAccessToken(component_AppId, componentToken, wxAppSet.appid, wxAppSet.authorizer_refresh_token).authorizer_access_token;
                Logger.Debug("authToken=" + authToken);
                var url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + authToken;
                Logger.Debug("url2333=" + url);
                var result = Senparc.Weixin.CommonAPIs.CommonJsonSend.Send<BaseWxResult>(authToken, url, temppleteModel);
                //   var strResult = SissO2O.Framework.Common.NetHelper.WxAppHttpPost(url, temppleteModel, SerializationType.Json);
                // var strResult = SissO2O.Framework.Common.PostDataToUrl.PostData(url, JsonConvert.SerializeObject(temppleteModel));

                Logger.Debug("strResult=" + JsonConvert.SerializeObject(result));

                // var result = JsonConvert.DeserializeObject<BaseWxResult>(strResult);
                if (result.errcode != 0)
                {
                    _result.message = "错误代码:" + result.errcode + " " + result.errmsg;
                    _result.success = false;
                    Logger.Error("商户:" + shopid + "小程序发布模板消息出错" + "错误代码:" + result.errcode + " " + result.errmsg);
                }
            }
            catch (Exception ex)
            {
                _result.message = ex.Message;
                _result.success = false;
                Logger.Error("商户:" + JsonConvert.SerializeObject(model) + "小程序发布模板消息出错,因为:" + ex.Message + "错误代码:" + ex.StackTrace);
            }
            return _result;
        }
        #endregion

  

后台调用接口的代码

 //测试发送模板消息
            var postSendTemplete = new PostSendTemplete();
            postSendTemplete.form_id = order.form_id;
            postSendTemplete.openid = order.openid;
            postSendTemplete.page = "";
            postSendTemplete.shopid = model.shopid;
            postSendTemplete.temptype = "AT0005";
            postSendTemplete.content = Common.Common.PaySuccessTempleteContentToString(shopInfoModel.shopname, order.branchname, model.orderno, order.orderdesc, order.amt);
            Logger.Debug("发送模板消息接口1:" + JsonConvert.SerializeObject(postSendTemplete));
            var tempUrl = "http://wxapp.sissyun.com.cn/api/WxAppApi/SendTemplete";
            var tempResult = SissO2O.Framework.Common.NetHelper.WxAppHttpPost(tempUrl, postSendTemplete, SerializationType.Json);

  此处的keyword关键字,命名从1开始,

/// <summary>
        /// 获取支付成功的模板消息内容
        /// </summary>
        /// <param name="shopname">商家名称</param>
        /// <param name="branchname">门店名称</param>
        /// <param name="orderno">订单编号</param>
        /// <param name="productinfo">商品信息</param>
        /// <param name="amt">付款金额 </param>
        /// <returns></returns>
        public static string PaySuccessTempleteContentToString(string shopname, string branchname, string orderno, string productinfo, decimal amt)
        {
            var model = new PaySuccessTemplete()
            {
                keyword1 = new TempleteItemData()
                {
                    value = shopname,
                },
                keyword2 = new TempleteItemData()
                {
                    value = branchname,
                },
                keyword3 = new TempleteItemData()
                {
                    value = orderno,
                },
                keyword4 = new TempleteItemData()
                {
                    value = productinfo,
                },
                keyword5 = new TempleteItemData()
                {
                    value = amt.ToString("0.00") + "元"
                }
            };
            return JsonConvert.SerializeObject(model);
        }
效果
 

效果 第一条的关键字排列错误,第二条为正确的关键字组合  ,关键字组合有数量限制

 

posted @ 2018-04-26 12:32  w1433189426  阅读(2593)  评论(1编辑  收藏  举报