最终效果图

在这里插入图片描述

在这里插入图片描述

步骤如下:

1、开通消息推送

开发—)开发设置—)消息推送

找到消息推送并配置URL、Token等相关选项
在这里插入图片描述
在这里插入图片描述

2、添加消息模板

在公共模板库配置自己想用的模板
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

配置小程序服务器域名

配置好服务器域名后,在开发工具中把 不校验合法域名、web-view(业务域名)、TLS 版本以及 HTTPS 证书选项勾上
在这里插入图片描述

// 以下代码框架是uniapp,如果是原生语法就要对应的改下语法

<template>
  <view>
    <view @click="templateMsg">点击发送模板消息</view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // access_token
      token: '',
      
      // 模板数据
      // 需要对应模板详情里面的key
      templateData: {
        // 商品
        thing1: {
          value: '通用正面pe6c+背面压纹8c自封包装袋'
        },
        // 支付金额
        amount3: {
          value: '100'
        },
        // 下单时间
        date5: {
          value: '2019-10-14 27:34:21'
        },
        // 订单编号
        character_string6: {
          value: 'ADWMP2933887762'
        }
      }
    };
  },
  onLoad(e) {
    this.getToken();
  },
  methods: {

    //获取access_token
    getToken() {
      const that = this;
      wx.request({
        url: `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${小程序appID}&secret=${小程序密钥}`,
        success: res => {
          that.token = res.data.access_token;
        }
      });
    },

    // 调起小程序订阅消息界面
    templateMsg(e) {
      const that = this;
      const data = {
        touser: '推送用户的openid',
        template_id: '模板id',
        page: '小程序页面路径',
        data: this.templateData // 模板数据
      };
      
      // 调起客户端小程序订阅消息界面
      wx.requestSubscribeMessage({
        tmplIds: ['模板id'],
        success: res =>  {
          console.log(res);
          if (res.errMsg === 'requestSubscribeMessage:ok') {
            that.submit(data);
          }
        }
      });
    },

    // 发送订阅消息
    submit(data) {
      wx.request({
        url: `https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${this.token}`,
        data,
        method: 'POST',
        success: res => {
          console.log('发送成功');
          console.log(res);
        },
        fail: err => {
          console.log('push err');
          console.log(err);
        }
      });
    }
  }
};
</script>

<style lang="less" scoped></style>

tips

开发者工具中点击无效、必须要真机上点击测试。

参考文档

介绍
请求接口文档
requestSubscribeMessage API文档

更多推荐