不多说,直接上代码:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace wechat
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
String message= Form1.SendTempletMessge();
MessageBox.Show(message);
}
public static 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=wx22f7b957cbfe6393&secret=42acf0bc57b3113ca60889a91a7db77a";
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.com/cgi-bin/message/template/send?access_token=" + token;
string temp = "{\"touser\": \"olqDqwbz-vSAaK6MoLJZQ2fDXkNo\"," +
"\"template_id\": \"t2_292xC7yNQAv-M1JcUVfRzHCFWYxLL5pTxFIUl2O0\", " +
"\"topcolor\": \"#FF0000\", " +
"\"data\": " +
"{\"first\": {\"value\": \"你好,你申请参加活动报名成功\"}," +
"\"keyword1\": { \"value\": \"邓杰\"}," +
"\"keyword2\": { \"value\": \"13333333333\"}," +
"\"keyword3\": { \"value\": \"2019-09-25 10:54:10\"}," +
"\"keyword4\": { \"value\": \"你选择的是足球队员\"}," +
"\"remark\": {\"value\": \"感谢您的使用,祝你生活愉快!\" }}}";
#endregion
//核心代码
Form1.GetResponseData(temp,@url);
strReturn = "推送成功";
}
catch (Exception ex)
{
strReturn = ex.Message;
}
return strReturn;
}
/// <summary>
/// 返回JSon数据
/// </summary>
/// <param name="JSONData">要处理的JSON数据</param>
/// <param name="Url">要提交的URL</param>
/// <returns>返回的JSON处理字符串</returns>
public static 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; }
}
}
}
注意:模板消息需要在微信公众号后台添加!