.net 后台如何模擬http請求調用微信的消息模板發送消息接口


1、前提條件

1)公眾號是服務號,不是訂閱號

2)開通消息模板(功能-->添加功能插件-->消息模板)

3)打開消息模板,在模板庫添加模板到我的模板,也可以自定義模板(可支持3個)

 

 2、發送微信模板消息給用戶(用戶需關注公眾號)

2.1)http請求方法

/// <summary>
        /// 后台發送POST請求
        /// </summary>
        /// <param name="url">服務器地址</param>
        /// <param name="data">發送的數據</param>
        /// <returns></returns>
        public string HttpPost(string url, string data)
        {
            try
            {
                //創建post請求
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/json;charset=UTF-8";
                byte[] payload = Encoding.UTF8.GetBytes(data);
                request.ContentLength = payload.Length;

                //發送post的請求
                Stream writer = request.GetRequestStream();
                writer.Write(payload, 0, payload.Length);
                writer.Close();

                //接受返回來的數據
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream stream = response.GetResponseStream();
                StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                string value = reader.ReadToEnd();

                reader.Close();
                stream.Close();
                response.Close();

                return value;
            }
            catch (Exception)
            {
                return "";
            }
        }

        /// <summary>
        /// 后台發送GET請求
        /// </summary>
        /// <param name="url">服務器地址</param>
        /// <param name="data">發送的數據</param>
        /// <returns></returns>
        public string HttpGet(string url, string data)
        {
            try
            {
                //創建Get請求
                url = url + (data == "" ? "" : "?") + data;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";
                request.ContentType = "text/html;charset=UTF-8";

                //接受返回來的數據
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream stream = response.GetResponseStream();
                StreamReader streamReader = new StreamReader(stream, Encoding.GetEncoding("utf-8"));
                string retString = streamReader.ReadToEnd();

                streamReader.Close();
                stream.Close();
                response.Close();

                return retString;
            }
            catch (Exception)
            {
                return "";
            }
        }

2.2)微信接口方法

        /// <summary>
        /// 獲取基礎支持的accessToken
        /// </summary>
        /// <param name="appid">公眾號憑證ID</param>
        /// <param name="secret">公眾號憑證密碼</param>
        /// <returns></returns>
        public string GetBaseAcccessToken(string appid, string secret)
        {
            string accessToken = string.Empty;

            string reqUrl = string.Format(@"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, secret);
            string resultStr = HttpGet(reqUrl,"");
            dynamic data = JsonConvert.DeserializeObject(resultStr);
            if (data["access_token"] != null)
            {
                accessToken = data["access_token"].ToString();
            }
            else
            {
                accessToken = "";
            }
            return accessToken;
        }

  /// <summary>
        /// 發送微信的模板信息到用戶的Openid(用戶關注公眾號的唯一標識)
        /// </summary>
        /// <param name="msgTempId">消息模板Id</param>
        /// <param name="openId">微信OpenId</param>
        /// <param name="firstInfo">提示信息</param>
        /// <param name="keyword1">參數1信息</param>
        /// <param name="keyword2">參數2信息</param>
        /// <param name="keyword3">參數3信息</param>
        /// <param name="keyword4">參數4信息</param>
        /// <param name="keyword5">參數5信息</param>
        /// <param name="endInfo">備注信息</param>
        public bool SendWxMessageToUser(string msgTempId,string openId, string firstInfo,string keyword1, string keyword2, string keyword3, string keyword4, string keyword5, string endInfo) {

            bool IsSuccess = false;

            //獲取配置文件中參數(公眾號ID,密碼, 發送模板消息ID)
            var appid = ConfigurationManager.AppSettings["AppID"].ToString();
            var secret = ConfigurationManager.AppSettings["AppSecret"].ToString();
           // var msgTempId = ConfigurationManager.AppSettings["MsgTemplateId"].ToString();

            //獲取基礎支持的accessToken
            string reqAccessToken = GetBaseAcccessToken(appid,secret);
            //找不到aceessToken(調用失敗)
            if (string.IsNullOrEmpty(reqAccessToken))
            {
                IsSuccess = false;
                SynLog.Info(string.Format(ErrorLogMsg, "SendWxMessageToUser", "微信發送消息失敗,原因:未找到微信令牌accessToken!"));
            }
            else {
                //組成請求的json數據
                JObject reqObj = new JObject(
                    new JProperty("touser", openId),
                    new JProperty("template_id",msgTempId),
                    new JProperty("data",new JObject(
                            new JProperty("first",new JObject { new JProperty("value", firstInfo),new JProperty("color", "#173177") }),
                            new JProperty("keyword1", new JObject { new JProperty("value", keyword1), new JProperty("color", "#173177") }),
                            new JProperty("keyword2", new JObject { new JProperty("value", keyword2), new JProperty("color", "#173177") }),
                            new JProperty("keyword3", new JObject { new JProperty("value", keyword3), new JProperty("color", "#173177") }),
                            new JProperty("keyword4", new JObject { new JProperty("value", keyword4), new JProperty("color", "#173177") }),
                            new JProperty("keyword5", new JObject { new JProperty("value", keyword5), new JProperty("color", "#173177") }),
                            new JProperty("remark", new JObject { new JProperty("value", endInfo), new JProperty("color", "#173177") })
                        ))    
                );
                //序列化轉成json格式字符串
                var jsonStr = JsonConvert.SerializeObject(reqObj);
                //請求url
                string reqUrl = string.Format(@"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={0}", reqAccessToken);
                string resultStr = HttpPost(reqUrl,jsonStr);
                //反序列化成對象
                dynamic result = JsonConvert.DeserializeObject(resultStr);

                if (result["errmsg"].ToString() == "ok")
                {
                    IsSuccess = true;
                    SynLog.Info(string.Format(SuccessLogMsg, "SendWxMessageToUser", "微信發送消息成功!"));
                }
                else {
                    IsSuccess = false;
                    SynLog.Info(string.Format(ErrorLogMsg, "SendWxMessageToUser", "微信發送消息失敗!"));
                }
            }

            return IsSuccess;
        }

2.3)調用微信接口方法

 

 2.4)發送消息結果(在公眾號查看)

 

 注明:由於用模板庫中的模板,列的值可能對不上,因為申請自定義模板(未審批),先用有的模板測試。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM