微信小程序模板消息发送

最近根据公司需要,转行做微信小程序。再次过程中发现net 后台资源的资料甚少。在网上看了半天基本都是前台搞定。后台找了好久一个都没找到,可能自己不擅长找东西。现在讲自己整理的微信小程序发送模板消息的代码公布如下,希望能帮到一些初学的道友,大神请无视。。。。。。

第一中:这种基本可以算前台完全搞定,之所以有一个后台的回调,主要是为了不把appid和秘钥在小程序前台公布出来。算是出于安全考虑吧。

SendNoticeInfo:function(e) {

    var _this = this;

    var sData = {

      url: 'test',

      where: 'test'//

    };

    wx.request({

      url:'http://localhost:50672/V1/WxInterfaceInfo.ashx',

      data: { 'sData':JSON.stringify(sData)

        },

      method: 'POST',

      success: function (res) {

        var rrdata = {

          "touser":_this.data.noticeInfo[0].OpenId,

          "template_id": "221sg0iLOsZXl4pazr3zK********",

        'page': "pages/index/index",

          "form_id":_this.data.noticeInfo[0].PayId,

          "data": {

            "keyword1": {

              "value": "SDHF",

              "color": "#173177"

            },

            "keyword2": {

              "value": "2015年01月05日 12:30",

              "color": "#173177"

            },

            "keyword3": {

              "value": "粤海喜来登酒店",

              "color": "#173177"

            },

            "keyword4": {

              "value": "123456789123456",

              "color": "#173177"

            },

            "keyword5": {

              "value": "208号",

              "color": "#173177"

            },

            "keyword6": {

              "value": "O123456789012634567",

              "color": "#173177"

            },

            "keyword7": {

              "value": "张小姐",

              "color": "#173177"

            },

            "keyword8": {

              "value": "100元",

              "color": "#173177"

            },

            "keyword9": {

              "value": "合软餐饮连锁",

              "color": "#173177"

            }

          },

          "emphasis_keyword": "keyword5.DATA"

        }

        wx.request({

          url: 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + res.data.access_token,

          data: JSON.stringify(rrdata),

          method: 'POST',

          header: {

            'content-type': 'application/x-www-form-urlencoded'

          },

          success: function (res) {

            console.log(res);

          }

        });

       

      }

    });

  }

 

后台:'http://localhost:50672/V1/WxInterfaceInfo.ashx'内容

publicvoid ProcessRequest(HttpContext context)

        {

            context.Response.ContentType = "application/json";

            context.Response.AddHeader("Access-Control-Allow-Origin","*");

            context.Response.AddHeader("Access-Control-Allow-Methods","POST");

            //// 响应头设置 

            context.Response.AddHeader("Access-Control-Allow-Headers:x-requested-with","content-type");

 

            string reqJson =context.Request.Params["sData"];//传入过来的数据

//下面两个是在腾讯小程序网站申请的,在配置文件写死的

            string appid = ConfigurationManager.AppSettings["appid"];//appid

            string secret = ConfigurationManager.AppSettings["secret"];//小程序秘钥

 

            string strUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&";

            strUrl += "appid="+appid+"&secret="+secret;

            string sendTxt = Comm.GetHttpsInfo(strUrl);

            context.Response.Write(sendTxt);

        }

第二种:这种基本所有的操作都在后台完成,前台只提供几个相关的参数

前端如下:

  SendNoticeInfo: function (e) {

    var _this = this;

    wx.request({

      url: 'http://localhost:50672/V1/WxMessageInfo.ashx',

      data: {

        'openid':_this.data.noticeInfo[0].OpenId,

        'formid':_this.data.noticeInfo[0].PayId

      },

      method: 'POST',

      header: {

        'content-type': 'application/x-www-form-urlencoded'

      },

      success: function (res) {

        console.log(res);

      }

    });

  }

 

 

后台如下:

publicvoid ProcessRequest(HttpContext context)

        {

            context.Response.ContentType = "application/json";

            context.Response.AddHeader("Access-Control-Allow-Origin","*");

            context.Response.AddHeader("Access-Control-Allow-Methods","POST");

            //// 响应头设置 

            context.Response.AddHeader("Access-Control-Allow-Headers:x-requested-with","content-type");

 

            string appid = ConfigurationManager.AppSettings["appid"];//appid

            string secret = ConfigurationManager.AppSettings["secret"];//小程序秘钥

 

            string strUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&";

            strUrl += "appid=" +appid + "&secret=" + secret;

            string sendTxt = Comm.GetHttpsInfo(strUrl);

            JObject sdata = Json.ToJObject(sendTxt);

            string acToken = sdata["access_token"].ToString();

            //=========================================

            string openid =context.Request.Params["openid"];//openid

            string formid =context.Request.Params["formid"];// formid

             JObject oReturn = new JObject();

             oReturn["touser"] =openid;

             oReturn["template_id"] ="221sg0iLOsZXl4pazr3zKlLV7X5e91GGAu6zl8bU0rA";

             oReturn["form_id"] =formid;

             oReturn["data"] = new JObject();

             oReturn["data"]["keyword1"]= getNewJsonObject("SDHF", "#173177");

 

             oReturn["data"]["keyword2"]= getNewJsonObject(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "#173177");

 

             oReturn["data"]["keyword3"]= getNewJsonObject("粤海喜来登酒店", "#173177");

 

             oReturn["data"]["keyword4"]= getNewJsonObject("123456789123456", "#173177");

 

             oReturn["data"]["keyword5"]= getNewJsonObject("208号", "#173177");

 

             oReturn["data"]["keyword6"]= getNewJsonObject("O123456789012634567", "#173177");

 

             oReturn["data"]["keyword7"]= getNewJsonObject("张小姐", "#173177");

 

             oReturn["data"]["keyword8"]= getNewJsonObject("100元", "#173177");

 

             oReturn["data"]["keyword9"]= getNewJsonObject("合软餐饮连锁", "#173177");

 

             oReturn["emphasis_keyword"]= "keyword5.DATA";

 

            string sendJson=oReturn.ToString();

           

                Encoding en = Encoding.GetEncoding("UTF-8");

                string strMsgUrl = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="+ acToken;

              

                string html =PostWebReq(strMsgUrl, sendJson, en);

               

                context.Response.Write(html);

           

        }

     //发送Post请求

        public static string PostWebReq(stringPostUrl, string ParamData, Encoding DataEncode)

        {

            string ret = string.Empty;

            try

            {

                byte[] byteArray =DataEncode.GetBytes(ParamData);

                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(newUri(PostUrl));

                webReq.Method = "POST";

                webReq.ContentType = "application/x-www-form-urlencoded";

                webReq.ContentLength =byteArray.Length;

 

                Stream newStream =webReq.GetRequestStream();

                newStream.Write(byteArray, 0,byteArray.Length);

                newStream.Close();

 

                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();

                StreamReader sr = new StreamReader(response.GetResponseStream(),DataEncode);

                ret = sr.ReadToEnd();

 

                sr.Close();

                response.Close();

                newStream.Close();

            }

            catch (WebException ex)

            {

                Log.WriteLog("错误:" ,ex.Message);

            }

            return ret;

        }

 /// <summary>
        /// 获取新的Json对象
        /// </summary>
        /// <param name="value"></param>
        /// <param name="color"></param>
        /// <returns></returns>
        private JObject getNewJsonObject(string value, string color)
        {
            JObject oReturn = new JObject();
            oReturn["value"] = value;
            oReturn["color"] = color;
            return oReturn;
        }

好了,这就是所有的代码。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值