微信小程序订阅消息发送

这里我写的是自己测试的过程

前期准备工作

1.申请一个微信小程序

https://mp.weixin.qq.com/cgi-bin/wx?token=&lang=zh_CN

2.找到开发管理->选择开发设置记录下AppID(小程序ID)和AppSecret(小程序密钥)这个后面代码要用

3.开启订阅消息->选择模板记录模板id这个也是要用

4.记录模板KEY

key就是我圈起来的部分

5.记录用户使用小程序的唯一id(openid)

我这里用的微信开发工具测试获取的

这里我没有选用模板(因为我不会前端)

代码是网上扒的自己改的下

index.wxml中代码

<view class="container">


<form bindsubmit="getOpenIdTap">
      <button formType='submit'>获取用户唯一标识openid</button>  
      <view class='widget'> 
        <text class='column'>openid:{{openid}}</text>
      </view> 
</form>

 <button bindtap="but">点击事件触发用户订阅功能</button>

</view>

index.js

//index.js
//获取应用实例
const app = getApp()
const APP_ID = '';//输入小程序appid  
const APP_SECRET = '';//输入小程序app_secret  
var OPEN_ID = ''//储存获取到openid  

Page({
  but: function(){  // 通过but点击事件触发后面的函数
    console.log("你好")
    var that = this;
    //订阅消息模板id
    var template_id ="";//这里输入消息模板id
    wx.requestSubscribeMessage({
      tmplIds: ['这里是模板id的集合'],
      success(res) {
        console.log("订阅成功")
      }
    })
  },
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../list/list'
    })
  },
  onLoad: function () {
    
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  getUserInfo: function (e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  getOpenIdTap: function (e) {
    var that = this;
  
    wx.login({
      success: function (res) {
        wx.request({
          //获取openid接口  
          url: 'https://api.weixin.qq.com/sns/jscode2session',
          data: {
            appid: APP_ID,
            secret: APP_SECRET,
            js_code: res.code,
            grant_type: 'authorization_code'
          },
          method: 'GET',
          success: function (res) {
            OPEN_ID = res.data.openid;//获取到的openid  
            console.log("openid:" + OPEN_ID)
            that.setData({
              openid: OPEN_ID,
              
            })
          }
        })
      }
    })
  },  
})

6.开启真机调试

7.点击获取openID然后再点击(点击事件按钮)

点击获取openID获取openID,(这里可以自己传给后端处理,我这里由于不会前端所以自己记录了openID写死在后端了)

 

8.点击事件的按钮会在微信端弹出订阅消息

这里我已经选择了不提示消息所以没发截图了

9.后端代码,这个我是在网上扒的

9.1.获取accessToken

package com.qing.wx.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class accessToken {
    static String appid = "";//前面记录的appid
    static String secret = "";//前面记录的APPscret
    public static String getAccessToken() throws Exception {
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid
                + "&secret=" + secret;
        URL url = new URL(requestUrl);
        // 打开和URL之间的连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        // 设置通用的请求属性
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);
        // 得到请求的输出流对象
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.writeBytes("");
        out.flush();
        out.close();
        // 建立实际的连接
        connection.connect();
        // 定义 BufferedReader输入流来读取URL的响应
        BufferedReader in = null;
        if (requestUrl.contains("nlp"))
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
        else
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        String result = "";
        String getLine;
        while ((getLine = in.readLine()) != null) {
            result += getLine;
        }
        in.close();
        JSONObject jsonObject = JSON.parseObject(result);
        String accesstoken = jsonObject.getString("access_token");
        System.out.println(accesstoken);
        return accesstoken;
    }
}

9.2

2个封装的实体类

1.

package com.qing.wx.controller;

import java.util.Map;

/**
 * 订阅消息*/
public class SubscribeMessage {
    //接口调用凭证
    private String access_token;
    //接收者(用户)的 openid
    private String touser;
    //所需下发的订阅模板id
    private String template_id;
    //点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例index?foo=bar)。该字段不填则模板无跳转。
    private String page;
    //模板内容,格式形如 { "key1": { "value": any }, "key2": { "value": any } }
    private Map<String, TemplateData> data;
 
    public String getAccess_token() {
        return access_token;
    }
 
    public void setAccess_token(String access_token) {
        this.access_token = access_token;
    }
 
    public String getTouser() {
        return touser;
    }
 
    public void setTouser(String touser) {
        this.touser = touser;
    }
 
    public String getTemplate_id() {
        return template_id;
    }
 
    public void setTemplate_id(String template_id) {
        this.template_id = template_id;
    }
 
    public String getPage() {
        return page;
    }
 
    public void setPage(String page) {
        this.page = page;
    }
 
    public Map<String, TemplateData> getData() {
        return data;
    }
 
    public void setData(Map<String, TemplateData> data) {
        this.data = data;
    }
}

2.

package com.qing.wx.controller;


public class TemplateData {
 
    private String value;
 
    public String getValue() {
        return value;
    }
 
    public void setValue(String value) {
        this.value = value;
    }
 
    public TemplateData(String value) {
        this.value = value;
    }
 
}

3.测试代码

package com.qing.wx.controller;

import com.alibaba.fastjson.JSONObject;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;

import java.util.HashMap;
import java.util.Map;

import static com.qing.wx.controller.accessToken.getAccessToken;

public class subscribeMessage11 {
    public static void subscribeMessage(String openId, String page, Map<String, TemplateData> map) {
        try {
            String accessToken = getAccessToken();
            SubscribeMessage subscribeMessage = new SubscribeMessage();
            // 拼接数据
            subscribeMessage.setAccess_token(accessToken);
            subscribeMessage.setTouser(openId);
            subscribeMessage.setTemplate_id("");//事先定义好的模板id
            subscribeMessage.setPage(page);
            subscribeMessage.setData(map);
            String json = JSONObject.toJSONString(subscribeMessage);
            HttpResponse<JsonNode> jsonNodeHttpResponse =
                    Unirest.post("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+accessToken)
                    .body(json).asJson();
            System.out.println(jsonNodeHttpResponse.getBody());
            System.out.println(jsonNodeHttpResponse.getHeaders());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Map<String, TemplateData> map = new HashMap<>();
        map.put("thing7", new TemplateData("准备签到"));
        map.put("thing10", new TemplateData("12345"));
        map.put("character_string11", new TemplateData("1111"));
        map.put("thing9", new TemplateData("123456"));
        map.put("thing1", new TemplateData("随便"));
        subscribeMessage("记录下来的openid放这里", "这里不写则没有跳转,我没写", map);
    }
}

 

posted @ 2022-06-02 10:47  续写兰亭  阅读(687)  评论(0)    收藏  举报