C# 微信接口之推送模版消息

 public string SendTempletMessge()
    {
      string strReturn = string.Empty;
      try
      {
          #region 获取access_token
          string apiurl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=你的appid&secret=你的secret";
          WebRequest request = WebRequest.Create(@apiurl);
          request.Method = "POST";
          WebResponse response = request.GetResponse();
          Stream stream = response.GetResponseStream();
          Encoding encode = Encoding.UTF8;
          StreamReader reader = new StreamReader(stream, encode);
          string detail = reader.ReadToEnd();
          var jd = JsonConvert.DeserializeObject(detail);
          string token = (String)jd.access_token;
          #endregion

          #region 组装信息推送,并返回结果(其它模版消息于此类似)
          string url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;
          string temp = "{\"touser\": \"" + UserInfo.OpenID + "\"," +
                        "\"template_id\": \"f3kRRjJeyLDf4tndtg-OJeRvgEdgjjDxCy4T9kuwM70\", " +
                        "\"topcolor\": \"#FF0000\", " +
                        "\"data\": " +
                        "{\"first\": {\"value\": \"您好,您有一条回款通知信息\"}," +
                        "\"keyword1\": { \"value\": \"单位名称\"}," +
                        "\"keyword2\": { \"value\": \"日期\"}," +
                        "\"keyword3\": { \"value\": \"金额\"}," +
                        "\"keyword4\": { \"value\": \"业务员\"}," +
                        "\"remark\": {\"value\": \"\" }}}";

          #endregion

	  //核心代码
	  GetResponseData(temp, @url);
          strReturn = "推送成功";
      }
      catch (Exception ex)
      {
        strReturn = ex.Message;
      }
      return strReturn;
    }

    ///   
    /// 返回JSon数据  
    ///   
    /// 要处理的JSON数据  
    /// 要提交的URL  
    /// 返回的JSON处理字符串  
    public string GetResponseData(string JSONData, string Url)
    {
      byte[] bytes = Encoding.UTF8.GetBytes(JSONData);
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
      request.Method = "POST";
      request.ContentLength = bytes.Length;
      request.ContentType = "json";
      Stream reqstream = request.GetRequestStream();
      reqstream.Write(bytes, 0, bytes.Length);

      //声明一个HttpWebRequest请求  
      request.Timeout = 90000;
      //设置连接超时时间  
      request.Headers.Set("Pragma", "no-cache");
      HttpWebResponse response = (HttpWebResponse)request.GetResponse();
      Stream streamReceive = response.GetResponseStream();
      Encoding encoding = Encoding.UTF8;

      StreamReader streamReader = new StreamReader(streamReceive, encoding);
      string strResult = streamReader.ReadToEnd();
      streamReceive.Dispose();
      streamReader.Dispose();
      return strResult;
    }
==================================================================================
涉及到的实体:
public class WXApi
  {
    public string access_token { set; get; }
  }

你可能感兴趣的:(微信开发笔记)