【微信小程序】模板消息推送(测试成功)。

note:
这几天想做微信小程序消息推送的功能,然后在网上找了好多教程,都没解决问题,官方文档写的教程由不够详细,所以走了好多弯路。
现在问题解决了,记录一下。
我在网上找的好多教程都不详细,虽然是贴代码出来了,但是好多都不说清楚是哪个文件的代码,真的很无语。

实现消息推送,需要先配置服务器域名、消息服务器推送配置。
请看我上一篇博客。
【微信小程序】消息推送服务器配置及服务器域名配置(记录坑)
https://blog.csdn.net/qq1445654576/article/details/89296942

配置好服务器域名后在开发工具中把 不校验合法域名、web-view(业务域名)、TLS 版本以及 HTTPS 证书选项勾上
【微信小程序】模板消息推送(测试成功)。_第1张图片

今天上午参考了这篇文章,终于实现了模板消息推送的功能。开心。
https://www.cnblogs.com/Smiled/p/8204467.html

下面是我写的:
首先看效果吧
【微信小程序】模板消息推送(测试成功)。_第2张图片

首先的要添加消息模板,这里我随便选一个为例
【微信小程序】模板消息推送(测试成功)。_第3张图片
【微信小程序】模板消息推送(测试成功)。_第4张图片
【微信小程序】模板消息推送(测试成功)。_第5张图片
【微信小程序】模板消息推送(测试成功)。_第6张图片
这样就选好消息模板了。

这里贴代码:
【微信小程序】模板消息推送(测试成功)。_第7张图片
template-message.wxml

<form name='pushMsgFm' report-submit="true" bindsubmit='template_Msg'>  
    <button form-type="submit" type='primary'>发送模板消息button>  
form>

template-message.js

Page({

  /**
   * 页面的初始数据
   */
  data: {
    openid: "", //(这个不要改)这里为空值,待获取到openid时,会给它重新赋值.openid在app.js中获取
    token: "",

    //要推送的内容
    push_content_data: [
      //keyword1
      {
        value: "17软件工程A班",
        color: "#4a4a4a"
      },
      //keyword2
      {
        "value": "软件工程导论",
        "color": "#9b9b9b"
      },
      //keyword3
      {
        "value": "P48 第5题",
        "color": "#9b9b9b"
      },
      //keyword4
      {
        "value": "2019-04-17 10:00:00",
        "color": "#9b9b9b"
      },
      //keyword5
      {
        "value": "今天你交作业了吗? 别忘了,当初为何出发",
        "color": "#9b9b9b"
      }
    ]

  },

  //发送模板消息
  template_Msg: function(e) {
    wx.showLoading({ //期间为了显示效果可以添加一个过渡的弹出框提示“加载中”  
      title: '加载中',
      icon: 'loading',
    });

    //获取access_token
    wx.request({
      url: "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + getApp().globalData.appId + "&secret=" + getApp().globalData.secret,
      success: (res) => {
        console.log(res);
        this.setData({
          token: res.data.access_token //将access_token存到data的token里
        });
        console.log("access_token:" + this.data.token);
      }
    });

    var fId = e.detail.formId; //获取formId
    console.log("formId:" + fId);
    var access_token_url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + this.data.token;
    var push_content = {
      "keyword1": this.data.push_content_data[0],
      "keyword2": this.data.push_content_data[1],
      "keyword3": this.data.push_content_data[2],
      "keyword4": this.data.push_content_data[3],
      "keyword5": this.data.push_content_data[4]
    };
    console.log(push_content)
    wx.request({
      url: access_token_url,

      //注意不要用value代替data
      data: {
        touser: this.data.openid,
        template_id: 'w9btZxaxU6kt7PymBh5Z_SS86-TC-DmWyppNxlQTCxk', //换成你申请的模板消息id,  
        page: '/pages/template-message/template-message',
        form_id: fId,
        data: push_content,
        color: '#ccc',
        emphasis_keyword: 'keyword3.DATA'
      },
      method: 'POST',
      success: function(res) {
        wx.hideLoading();
        console.log("发送成功");
        console.log(res);
      },
      fail: function(err) {
        // fail  
        console.log("push err")
        console.log(err);
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    wx.login({
      success: (res) => {
        if (res.code) {
          wx.request({
            url: "https://api.weixin.qq.com/sns/jscode2session",
            data: {
              appid: getApp().globalData.appId, //从app.js中获得你的appid
              secret: getApp().globalData.secret, //从app.js中获得你的secret
              js_code: res.code,
              grant_type: "authorization_code"
            },
            success: (res) => {
              console.log(res);
              that.setData({
                openid: res.data.openid //存储openid
              })
            }
          })
        }
      }
    })
  } //onLoad
}) //Pages

app.js

//app.js
App({

  globalData: {
    userInfo: null,
    appId: "wxabcd1234",	//这里换成你的appid
    secret: "dsks4fdf2r63f5se2rerf23re"   //换成你的密钥
  },

  onLaunch: function () {
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo

              // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  },

  onLoad: function (options) {
    var that = this;
    wx.login({
      success: (res) => {
        if (res.code) {

          //获取openid
          wx.request({
            url: "https://api.weixin.qq.com/sns/jscode2session",
            data: {
              appid: getApp().globalData.appId,
              secret: getApp().globalData.secret,
              js_code: res.code,
              grant_type: "authorization_code"
            },
            success: (res) => {
              console.log(res);
              that.setData({
                openid: res.data.openid//将openid存起来
              }) 
            }
          })
        }
      }
    })
  }
})

总结:
需要准备的东西
1.AppID(小程序ID)

在微信小程序后台获取

2.AppSecret(小程序密钥)

在微信小程序后台获取

3.formId

var fId = e.detail.formId; //获取formId

4.openid

只有用户登录时才能获取到。
这个在app.js中获取,而且只能在手机里才能获取到,编译器里获取不到
//获取openid
          wx.request({
            url: "https://api.weixin.qq.com/sns/jscode2session",
            data: {
              appid: getApp().globalData.appId,
              secret: getApp().globalData.secret,
              js_code: res.code,
              grant_type: "authorization_code"
            },
            success: (res) => {
              console.log(res);
              that.setData({
                openid: res.data.openid//将openid存起来
              }) 
            }
          })

5.access_token

通过api获取
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
    //获取access_token
    wx.request({
    //APPID替换成你的appid, APPSECRET换成你的AppSecret
      url: "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET",
      success: (res) => {
        console.log(res);
        this.setData({
          token: res.data.access_token //将access_token存到data的token里
        });
        console.log("access_token:" + this.data.token);
      }
    });

6.template_id
【微信小程序】模板消息推送(测试成功)。_第8张图片

你可能感兴趣的:(微信小程序)