目的:实现消息摸版的下发。
结果:测试成功
步骤:
1.小程序不校验域名请求OpenId(个人开发者不行)
2.界面弄个表单
3.点击事件(真机点击得到form_id: e.detail.formId,表单id只有真机才会有):
orderSign:function(e)
{
console.log(e.detail.formId),
wx.request({
url: 'http://localhost:9561/api/values',
data: {
Openid: "oBU4-5beiAsSLu40efAxL0", //事先获取的OpenId不会过期而唯一
form_id: e.detail.formId,
},
method: "POST",
dataType: JSON,
success: function (res) {
console.log(res.data);
},
fail: function (e) {
wx.showToast({
title: '网络请求错误!',
icon: 'loading',
duration: 1500
})
},
})
},
4.获取OpenId方法:
//app.js
App({
globalData: {
appid: 'wx62a1178cfc2',//appid需自己提供,此处的appid我随机编写 企业的
secret: '8990bf0889db3d01a951a1',//secret需自己提供,此处的secret我随机编写 企业的
},
onLaunch: function () {
var that = this
var user = wx.getStorageSync('user') || {};
var userInfo = wx.getStorageSync('userInfo') || {};
if ((!user.openid || (user.expires_in || Date.now()) < (Date.now() + 600)) && (!userInfo.nickName)) {
wx.login({
success: function (res) {
if (res.code) {
wx.getUserInfo({
success: function (res) {
var objz = {};
objz.avatarUrl = res.userInfo.avatarUrl;
objz.nickName = res.userInfo.nickName;
console.log(objz);
wx.setStorageSync('userInfo', objz);//存储userInfo
}
});
var d = that.globalData;//这里存储了appid、secret、token串
var l = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + d.appid + '&secret=' + d.secret + '&js_code=' + res.code + '&grant_type=authorization_code';
wx.request({
url: l,
data: {},
method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
// header: {}, // 设置请求的 header
success: function (res) {
var obj = {};
obj.openid = res.data.openid;
obj.expires_in = Date.now() + res.data.expires_in;
console.log(obj);
wx.setStorageSync('user', obj);//存储openid
}
});
} else {
console.log('获取用户登录态失败!' + res.errMsg)
}
}
});
}
},
})
5.在后台写入form_id(本机测试没有,所以写入),然后获取签名,然后调用消息摸版接口,传入post数据:
// POST api/values
public HttpResponseMessage Post([FromBody]JObject value)
{
string Js = value.ToString();
JObject jo = (JObject)JsonConvert.DeserializeObject(Js); // 反序列化对象
string form_id =jo["form_id"].ToString();
string Openid = jo["Openid"].ToString();
//获取微信签名
string GetACCESS_TOKEN = GetHtml("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx62a178cft=8990bf0889db3d9ce6a3c951a1");
JObject JsonACCESS_TOKEN = (JObject)JsonConvert.DeserializeObject(GetACCESS_TOKEN);
string ACCESS_TOKEN = JsonACCESS_TOKEN["access_token"].ToString();
//消息摸版需要的数据
string Json = "{\"touser\":\"" + Openid + "\",\"template_id\":\"-leLgZp24rY5br09axjHGIZbn8cFBMqdyV2uNr27THo\",\"page\":\"\",\"form_id\":\"1542952684504\",\"data\":{\"keyword1\":{\"value\":\"339208499\"},\"keyword2\":{\"value\":\"2015年01月05日 12:30\"}},\"emphasis_keyword\":\"keyword1.DATA\"}";
//接口访问
string message = PostHttpUrl("https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + ACCESS_TOKEN, Json);
return new HttpResponseMessage { Content = new StringContent(message, System.Text.Encoding.UTF8, "application/json") };
}
6.上面的两个方法分别Get和Post的方法
最后测试成功:
源码QQ联系:1174787689