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<WXApi>(detail);
          string token = (String)jd.access_token;
          #endregion

          #region 组装信息推送,并返回结果(其它模版消息于此类似)
          string url = "https://api.weixin.qq.co
### C# 实现微信服务消息推送 API 示例 #### 准备工作 为了通过C#实现向微信服务号发送消息的功能,需先完成以下准备工作: - 注册并认证微信公众平台的服务号; - 获取`AppID`和`AppSecret`用于后续接口调用的身份验证。 #### 获取 Access Token 由于每次请求都需要有效的`access_token`作为凭证,在发起任何业务逻辑之前应确保拥有最新有效期内的令牌。考虑到该令牌的有效期为7200秒(即两小时),因此建议设置定时器定期刷新此值以避免过期失效问题[^4]。 ```csharp public class AccessTokenManager { private static string _accessToken; private static DateTime _expireTime; public async Task<string> EnsureValidTokenAsync(string appId, string appSecret) { var now = DateTime.UtcNow; // 如果当前时间距离上次更新已超过7200秒,则重新获取新的access_token if (_expireTime <= now || string.IsNullOrEmpty(_accessToken)) { using HttpClient client = new(); HttpResponseMessage response = await client.GetAsync($"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appId}&secret={appSecret}"); string jsonResponse = await response.Content.ReadAsStringAsync(); dynamic jsonResult = JsonConvert.DeserializeObject(jsonResponse); int expiresIn = Convert.ToInt32(jsonResult.expires_in); _accessToken = jsonResult.access_token; _expireTime = now.AddSeconds(expiresIn - 60); // 提前一分钟再次获取新token Console.WriteLine($"Access token updated at {now}, expires in {_expireTime}."); } return _accessToken; } } ``` #### 构建并发送模板消息 当拥有了合法可用的`access_token`后,就可以构建想要推送给用户的模板消息对象,并将其序列化成JSON字符串形式提交至官方API端点进行处理了[^2]。 ```csharp using System.Net.Http.Headers; // 定义一个表示单条消息的数据传输类 public class TemplateMessageRequest { [JsonProperty("touser")] public string ToUser { get; set; } [JsonProperty("template_id")] public string TemplateId { get; set; } [JsonProperty("url")] public string Url { get; set; } [JsonProperty("topcolor")] public string TopColor { get; set; } [JsonProperty("data")] public Dictionary<string, DataItem> DataItems { get; set; } } public class DataItem { [JsonProperty("value")] public string Value { get; set; } [JsonProperty("color")] public string Color { get; set; } } /// <summary> /// 发送一条模板消息给指定用户 /// </summary> private async void SendTemplateMessage() { try { string accessToken = await new AccessTokenManager().EnsureValidTokenAsync(appid, secret); string url = $"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={accessToken}"; TemplateMessageRequest requestPayload = new TemplateMessageRequest{ ToUser = "OPENID", TemplateId = "TEMPLATE_ID", Url = "http://weixin.qq.com/download", // 可选参数 TopColor = "#FF0000", // 可选参数 DataItems = new Dictionary<string, DataItem>() { {"first", new DataItem{Value="您好,恭喜您预约成功!", Color="#173177"}}, {"keyword1", new DataItem{Value="【关键词】", Color="#173177"}}, {"keyword2", new DataItem{Value="【更多详情...】", Color="#173177"}}, {"remark", new DataItem{Value="具体注意事项,请点击下方链接查看详情...", Color="#173177"}} } }; using(var httpClient = new HttpClient()) { HttpContent content = new StringContent(JsonConvert.SerializeObject(requestPayload), Encoding.UTF8, "application/json"); HttpResponseMessage responeMsg = await httpClient.PostAsync(url,content ); if (!responeMsg.IsSuccessStatusCode){ throw new Exception(await responeMsg.Content.ReadAsStringAsync()); } string responseBody = await responeMsg.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } catch(Exception ex) { Console.WriteLine($"Error occurred while sending message:{ex.Message}"); } } ```
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值