一、配置信息
1、微信公众平台:mp.weixin.qq.com
2、登录小程序=》 开发 -> 开发管理 -> 开发设置-> 拿到小程序专属的 AppId, Secret
3、登录公众号=》 模板Id: 广告与服务=>模板消息=>操作记录=>模板Id
4、绑定微信公众号与小程序: 广告与服务=>小程序管理=>添加关联小程序
二、实现思路
1、前端去获取到在公众号的 code
2、后端通过这个 code、appid、secret 去微信获取用户在公众号的 openId
3、后端通过 appid、secret 去微信获取 access_token
3、后端通过 access_token、templateid、openid、消息内容 给用户发送公众号模板消息
三、代码实现
1、获取用户的openId
static string UserOpenIdUrl="https://api.weixin.qq.com/sns/oauth2/access_token";
/// <summary>
/// 获取微信公众号用户openId
/// </summary>
/// <returns></returns>
public static async Task<string> GetOpenId(string pAppId, string pSecret, string pCode)
{
try
{
Dictionary<string, string> pairs = new Dictionary<string, string>()
{
{"appid", pAppId },
{"secret", pSecret },
{"code", pCode },
{"grant_type", "authorization_code" },
};
//获取微信公众号用户信息
string jsonResult = null;
using (HttpClient client = new HttpClient())
{
//配置请求数据
var queryString = new FormUrlEncodedContent(pairs).ReadAsStringAsync().Result;
//拼接url参数
string url = UserOpenIdUrl + "?" + queryString;
//发送http请求
HttpResponseMessage response = await client.GetAsync(url);
//校验请求状态是否成功
if (response.IsSuccessStatusCode)
jsonResult = await response.Content.ReadAsStringAsync();
else
jsonResult = $"Error: {response.StatusCode}";
}
if (string.IsNullOrEmpty(jsonResult))
return null;
return JObject.Parse(jsonResult)["openid"].ToString();
}
catch (Exception ex)
{
await Console.Out.WriteLineAsync(ex.Message);
return null;
}
}
2、获取access_token
static string GetTokenUrl="https://api.weixin.qq.com/cgi-bin/token";
/// <summary>
/// 获取微信公众号Token
/// </summary>
/// <returns></returns>
public static async Task<string> GetToken(string appId, string secret)
{
Dictionary<string, string> pairs = new Dictionary<string, string>()
{
{"appid", appId },
{"secret", secret },
{"grant_type", "client_credential" },
};
string jsonResult = null;
using (HttpClient client = new HttpClient())
{
//配置请求数据
var queryString = new FormUrlEncodedContent(pairs).ReadAsStringAsync().Result;
//拼接url参数
string url = GetTokenUrl + "?" + queryString;
//发送http请求
HttpResponseMessage response = await client.GetAsync(url);
//校验请求状态是否成功
if (response.IsSuccessStatusCode)
jsonResult = await response.Content.ReadAsStringAsync();
else
jsonResult = $"Error: {response.StatusCode}";
}
if (string.IsNullOrEmpty(jsonResult))
return null;
return JObject.Parse(jsonResult)["access_token"].ToString();
}
3、发送模板消息
static string sednUrl="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={0}";
//发送指定人消息
public static async Task<bool> SendWeChat(string access_token, string templateId, List<string> openIds)
{
try
{
// 准备发送模板消息需要的信息
foreach (var openId in openIds)
{
dynamic content = new
{
touser = openId,
template_id = templateId,
data = new
{
phrase11 = new
{
value = "测试数据",
color = "#173177"
},
thing5 = new
{
value = "测试过数据2222",
color = "#173177"
}
}
};
string dataJson = JsonConvert.SerializeObject(content);
string url = string.Format(sednUrl, access_token);
string responseContent = null;
// 使用Wechat.SDK发送模板消息
using (HttpClient client = new HttpClient())
{
//配置请求数据
StringContent requestContent = new StringContent(dataJson, Encoding.UTF8, "application/json");
//发送http请求
HttpResponseMessage response = await client.PostAsync(url, requestContent);
//校验请求状态是否成功
if (response.IsSuccessStatusCode)
responseContent = await response.Content.ReadAsStringAsync();
else
responseContent = $"Error: {response.StatusCode}";
}
return true;
}
catch (Exception ex)
{
await Console.Out.WriteLineAsync(ex.Message);
return false;
}
}
以上就是c#实现的给指定用户发送公众号模板消息功能全部流程!!!