1.将你要部署的程序的域名加入微信公众号后台域名授权,将授权文件放到程序部署网站的根目录下,以及IP地址加入IP白名单
2.微信公众号后台搜索合适的模板并将模板id记录下来
3.新建模板类
public class BaseMessage
{
///
/// openid
///
public string openid
{
get;
set;
}
///
/// 点击跳转url
///
public string url
{
get;
set;
}
///
/// 标题
///
public string first
{
get;
set;
}
///
/// 模板内容1
///
public string keyword1
{
get;
set;
}
///
/// 模板内容2
///
public string keyword2
{
get;
set;
}
///
/// 模板内容3
///
public string keyword3
{
get;
set;
}
///
/// 模板内容4
///
public string keyword4
{
get;
set;
}
///
/// 模板内容5
///
public string keyword5
{
get;
set;
}
///
/// 模板结尾
///
public string remark
{
get;
set;
}
///
/// 选用的模板
///
public string templateType;
}
public class MessageModel
{
[DataMember(Order = 0)]
public string touser
{
get;
set;
}
[DataMember(Order = 1)]
public string template_id
{
get;
set;
}
[DataMember(Order = 2)]
public string url
{
get;
set;
}
[DataMember(Order = 3)]
public BaseData data
{
get;
set;
}
}
public class BaseData
{
[DataMember(Order = 0)]
public font first
{
get;
set;
}
[DataMember(Order = 1)]
public font keyword1
{
get;
set;
}
[DataMember(Order = 2)]
public font keyword2
{
get;
set;
}
[DataMember(Order = 3)]
public font keyword3
{
get;
set;
}
[DataMember(Order = 4)]
public font keyword4
{
get;
set;
}
[DataMember(Order = 5)]
public font keyword5
{
get;
set;
}
[DataMember(Order = 6)]
public font remark
{
get;
set;
}
}
///
/// 字体
///
public class font
{
public string value
{
get;
set;
}
public string color
{
get;
set;
}
}
4.首先进入页面时先获取openid并存session(微信公众号用户唯一标识),回调地址得到返回值
//采用排序的Dictionary的好处是方便对数据包进行签名,不用再签名之前再做一次排序
private SortedDictionary m_values = new SortedDictionary();
/**
* 设置某个字段的值
* @param key 字段名
* @param value 字段值
*/
public void SetValue(string key, object value)
{
m_values[key] = value;
}
/**
* 根据字段名获取某个字段的值
* @param key 字段名
* @return key对应的字段值
*/
public object GetValue(string key)
{
object o = null;
m_values.TryGetValue(key, out o);
return o;
}
public static string GetOpenidAndAccessToken()
{
string redirect_uri = HttpUtility.UrlEncode(System.Configuration.ConfigurationManager.AppSettings["WechatAPIUrl"]);
WxPayDataParamIn data = new WxPayDataParamIn();
data.SetValue("appid", System.Configuration.ConfigurationManager.AppSettings["WeixinAppId"]);
data.SetValue("redirect_uri", redirect_uri);
data.SetValue("response_type", "code");
data.SetValue("scope", "snsapi_base");
data.SetValue("state", "STATE" + "#wechat_redirect");
string url = "https://open.weixin.qq.com/connect/oauth2/authorize?" + data.ToUrl();
try
{
//触发微信返回code码
return url;//Redirect函数会抛出ThreadAbortException异常,不用处理这个异常
}
catch (System.Threading.ThreadAbortException ex)
{
return "";
}
}
redirect_uri(回调地址)获取到openid和accesstoken
public ActionResult ResponseCode()
{
string url = "";
string code = "";
string openid = "";
string access_token = "";
string ret = CookieHelper.ReadCookies("RedirectUrlRe");
try
{
Log.WriteLog("ResponseCode2:" + SessionHelper.RedirectUrl);
if (Request.QueryString["code"] != null)
{
code = Request.QueryString["code"];
AccesstokenTemplate model = new TjjgService().GetTemp(SessionHelper.YYBH, "1");
WxPayDataParamIn wechatOpration = new WxPayDataParamIn();
wechatOpration.GetOpenidAndAccessTokenFromCode(code, model);
openid = wechatOpration.Openid;
access_token = wechatOpration.Access_token;
url = VerfityRedirectUrl(ret) + "code=" + code + "&openid=" + openid + "&access_token=" + access_token;
Response.Redirect(url);
}
else
{
url = VerfityRedirectUrl(ret) + "errorCode=06&errorMessage=code为空";
Response.Redirect(url);
}
}
catch (Exception ex)
{
Log.WriteLog(ex.ToString());
url = VerfityRedirectUrl(ret) + "errorCode=05&errorMessage=获取openid时报错";
Response.Redirect(url);
}
return null;
}
5.用户授权登录之后,触发事件,将openid等要发送的内容赋值给一个实体,
//发微信模版消息
WeiXinService.BaseMessage bm = new WeiXinService.BaseMessage();
bm.openid = SessionHelper.OpenId;
bm.first = "您好,恭喜您预约成功!";
bm.keyword1 = "";
bm.keyword2 = "";
bm.keyword3 = "";
bm.keyword4 = "";
bm.keyword5 = "";
bm.remark = "具体注意事项,请点击下方的链接查看!联系电话:";
bm.url = null;
bool s= WeiXinService.SendMessage(bm);
6.给赋值的内容增加字体颜色以及改造成另一个符合微信接口要求的入参格式MessageModel
///
/// 给用户推送消息(基础)
///
/// 发送内容
///
public static bool SendMessage(BaseMessage Message)
{
bool result = false;
MessageModel Model = new MessageModel();
Model.touser = Message.openid;//用户openid
Model.url = Message.url;//跳转链接
if (string.IsNullOrWhiteSpace(Message.templateType) || Message.templateType == "0")
{
Model.template_id = WebConfigurationManager.AppSettings["Base_template_id"];//模板id
}
else
{
Model.template_id = WebConfigurationManager.AppSettings["Base_template_id_" + Message.templateType];//模板id
}
Log.WriteLog("常规" + Model.template_id);
BaseData baseDate = new BaseData();
font first = new font();
first.value = Message.first;
first.color = "#3998fc";
font keyword1 = new font();
keyword1.value = Message.keyword1;
keyword1.color = "";
font keyword2 = new font();
keyword2.value = Message.keyword2;
keyword2.color = "";
font keyword3 = new font();
keyword3.value = Message.keyword3;
keyword3.color = "";
font keyword4 = new font();
keyword4.value = Message.keyword4;
keyword4.color = "";
font keyword5 = new font();
keyword5.value = Message.keyword5;
keyword5.color = "";
font remark = new font();
remark.value = Message.remark;
remark.color = "";
baseDate.first = first;
baseDate.keyword1 = keyword1;
baseDate.keyword2 = keyword2;
baseDate.keyword3 = keyword3;
baseDate.keyword4 = keyword4;
baseDate.keyword5 = keyword5;
baseDate.remark = remark;
Model.data = baseDate;
result = SendMessage(Model);
return result;
}
7.首先检查accesstoken是否过期,若无过期则调用接口传参,过期则重新调用微信调用accesstoken接口获取
///
/// 检查基础token是否过期并刷新
///
///
public static bool Check_token()
{
bool result = false;
var timespan = (DateTime.Now - access_token_Date);//获取时间差(秒)
if (timespan.TotalSeconds < expires_in && !string.IsNullOrEmpty(access_token))
{
result = true;
return result;
}
else
{
result = Base_token();
}
return result;
}
///
/// 获取基础token
///
///
private static bool Base_token()
{
bool result = false;
string Str = GetJson("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret);
OAuth_Token2 Oauth_Token_Model = Common.JsonHelper.ParseFromJson(Str);
if (!string.IsNullOrEmpty(Oauth_Token_Model.access_token))
{
access_token = Oauth_Token_Model.access_token;
access_token_Date = DateTime.Now;
result = true;
}
return result;
}
8.最后一步调用发送模板消息接口发送数据
///
/// 给用户推送消息
///
///
///
public static bool SendMessage(MessageModel Model)
{
bool result = false;
if (Check_token())
{
string Url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;
Log.WriteLog("url:" + Url);
string JsonParam = JsonHelper.GetJson(Model);
string Str = PostJson(Url, JsonParam);
retMess retmess = Common.JsonHelper.ParseFromJson(Str);
Log.WriteLog(retmess.errcode + "|" + retmess.errmsg);
if (retmess != null)
{
if (retmess.errcode == "0")
{
result = true;
}
}
}
return result;
}
这样,关注了公众号的用户操作时就可以接受到模板信息啦,实际效果如下: