后端对接小程序订阅消息

	//发送订阅消息
  public ResultMessage SendSubscribeMsg(SendSubscribeMsgRequestDto request)
        {
            ResultMessage resultMessage = new ResultMessage();

            string token = GetAccessToken();
            if (token.Length < 20)
            {
                resultMessage.Message = "token错误";
                return resultMessage;
            }

            string url = string.Format("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={0}", token);
            string resultdata = HttpServiceHelper.PostJson(url, JsonHelper.GetJsonString(request));

            var result = JsonHelper.JsonDeserialize<SendSubscribeMsgResponseDto>(resultdata);

            if (result.errcode == 0)
            {
                resultMessage.IsSuccess = true;
                resultMessage.Message = "发送成功";
                return resultMessage;
            }
            else
            {
                resultMessage.Message = result.errmsg;
            }
            return resultMessage;
        }
发送请求
private string GetRequestPost(string url, string param)
        {
            HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);

            Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
            byte[] arrB = encode.GetBytes(param.ToString());

            webrequest.Method = "POST";
            webrequest.ContentType = "application/x-www-form-urlencoded";
            webrequest.ContentLength = arrB.Length;
  
            Stream outStream = webrequest.GetRequestStream();
            outStream.Write(arrB, 0, arrB.Length);
            outStream.Close();

            //接收HTTP做出的响应
            WebResponse myResp = webrequest.GetResponse();
            Stream ReceiveStream = myResp.GetResponseStream();
            StreamReader readStream = new StreamReader(ReceiveStream, encode);

            Char[] read = new Char[256];
            int count = readStream.Read(read, 0, 256);
            string strs = "";
            while (count > 0)
            {
                strs += new String(read, 0, count);
                count = readStream.Read(read, 0, 256);
            }
            readStream.Close();
            myResp.Close();
            return strs;
        }
获取accesstoken
 private string GetAccessToken()
        {
            lock (SyncLock)
            {
                var token = "";

                if (CacheHelper.Exists(CacheKey))
                {
                    CacheHelper.Get(CacheKey, out token);
                }
                else
                {
                    var accessTokenUrl = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", AppId, AppSecret);
                    var tokenResult = GetRequestPost(accessTokenUrl, "");
                    var _result = JsonHelper.JsonDeserialize<AccessTokenResponseDto>(tokenResult);
                    if (_result != null)
                    {
                        token = _result.access_token;
                        CacheHelper.Add(token, CacheKey);
                    }
                }
                return token;
            }
        }
 public class SendSubscribeMsgRequestDto
        {
            /// <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>
            /// 跳转小程序类型:developer为开发版;trial为体验版;formal为正式版;默认为正式版
            /// </summary>
            public string miniprogram_state { get; set; }
            /// <summary>
            /// 进入小程序查看”的语言类型,支持zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文),默认为zh_CN
            /// </summary>
            public string lang { get; set; }
            /// <summary>
            /// 模板内容
            /// </summary>
            public Dictionary<string, DataValue> data { get; set; }
        }

        /// <summary>
        /// 发送小程序订阅消息响应Dto
        /// </summary>
        public class SendSubscribeMsgResponseDto : WechatResponseDto
        {

        }

        /// <summary>
        /// 模板内容关键字
        /// </summary>
        public class DataValue
        {
            /// <summary>
            /// 订阅消息参数值
            /// </summary>
            public string value { get; set; }
        }
封装调用
 public ResultMessage SendSubscribeMessage(string openId, string template_id, Dictionary<string, AppletAPI.DataValue> data, string pageUrl = "")
        {
            var sendMe = new AppletAPI.SendSubscribeMsgRequestDto()
            {
                page = pageUrl,
                template_id = template_id,
                data = data,
                touser = openId,
                miniprogram_state = "developer"//跳转小程序类型:developer为开发版;trial为体验版;formal为正式版;默认为正式版
            };

            AppletAPI appletAPI = new AppletAPI();
            ResultMessage sendResult = appletAPI.SendSubscribeMsg(sendMe);
            return sendResult;
        }
业务调用
string template_id = "123asd";
                Dictionary<string, AppletAPI.DataValue> data = new Dictionary<string, AppletAPI.DataValue>()
                        {
                            {"thing",new AppletAPI.DataValue{ value="测试" } },
                            {"date",new AppletAPI.DataValue{ value= DateTime.Now.ToString()} }
                        };
                        //点击消息卡片跳转的页面和参数
                string pageUrl = "/pages/index?param=myParam" ;

                SendSubscribeMessage(customer.FirstOpenId, template_id, data,pageUrl);

在这里插入图片描述

在这里插入图片描述

符号表示除中文、英文、数字外的常见符号,不能带有换行等控制字符。 时间格式支持HH:MM:SS或者HH:MM。 日期包含年月日,为y年m月d日,y年m月、m月d日格式,或者用‘-’、‘/’、‘.’符号连接,如2018-01-01,2018/01/01,2018.01.01,2018-01,01-01。

在这里插入图片描述

小程序的前端和后端可以通过HTTP请求进行通信。前端可以通过wx.request()函数向后端发送请求,后端可以处理请求并返回数据。通常情况下,前端发送请求时需要携带一些参数,例如请求的URL、请求的方法(GET/POST等)、请求的数据等。同时,后端也需要对请求进行验证,并根据请求的参数进行相应的处理。处理完请求后,后端需要将相应的数据返回给前端,前端再根据返回的数据进行相应的渲染。 具体的对接流程可以参考以下步骤: 1. 后端提供API接口。后端需要提供一些API接口,用于处理前端发送的请求,并返回相应的数据。通常情况下,API接口都是RESTful风格的,即每个API接口都对应一个特定的URL和请求方法。 2. 前端发送请求。前端需要通过wx.request()函数向后端发送请求。在发送请求时,需要指定请求的URL、请求的方法、请求的数据等。 3. 后端处理请求。后端接收到前端发送的请求后,需要对请求进行验证,并根据请求的参数进行相应的处理。处理完请求后,后端需要将相应的数据返回给前端。 4. 前端渲染数据。前端接收到后端返回的数据后,需要根据数据进行相应的渲染。通常情况下,使用setData()函数将数据绑定到前端的组件上。 5. 错误处理。在整个对接过程中,可能会出现各种各样的错误,例如网络错误、服务器错误等。因此,需要对这些错误进行处理,以保证应用的稳定性和可靠性。 总之,前端和后端对接是整个小程序开发中非常重要的一环,需要仔细设计和实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值