小程序获取access_token——后端

参考原文:小程序 java后台 如何获取access_token的示例方法_getaccesstoken-CSDN博客

微信小程序,用户订阅消息,后端服务发送订阅消息_小程序后端发送订阅消息-CSDN博客

private static final String GET_ACCESS_TOKEN_URL =
            "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";

    public static String getAccessToken(String appId, String appSecret) throws Exception {
        String url = String.format(GET_ACCESS_TOKEN_URL, appId, appSecret);
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // 设置请求属性
        con.setRequestMethod("GET");
        con.setRequestProperty("Content-Type", "application/json");

        int responseCode = con.getResponseCode();
        System.out.println("----token----" + responseCode);
        if (responseCode == HttpURLConnection.HTTP_OK) { // 200
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
            String inputLine;
            StringBuilder response = new StringBuilder();
//            System.out.println("--in--" + in.readLine() );
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 解析JSON获取access_token
            String accessToken = parseAccessTokenFromJson(response.toString());
//            System.out.println("--accessToken*:"+accessToken);
            return accessToken;
        } else {
            throw new Exception("Error while fetching access token. Response Code: " + responseCode);
        }
    }

    private static String parseAccessTokenFromJson(String jsonStr) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(jsonStr);
            return rootNode.get("access_token").asText();
        } catch (Exception e) {
            throw new RuntimeException("Failed to parse access token from JSON", e);
        }
    }
    public static void main(String[] args) {
        try {
            String appId = "wxeba0********bb351";
            String appSecret = "2414ef4341e*******e3f700b57";
            String accessToken = getAccessToken(appId, appSecret);
            System.out.println("Access Token: " + accessToken);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

订阅消息(小程序端订阅模版)

var TemplateID = 'wFdkNcCcfywuteOo*******Vx5tVKU'
                    var TemplateStatus = uni.getStorageSync('TemplateID')
                    if(TemplateStatus != 'accept'){
                      uni.requestSubscribeMessage({
                        tmplIds: [TemplateID],
                        complete (res) {
                          console.log("complete: ",res)
                          uni.setStorageSync('TemplateID', res[TemplateID])
                        },
                      })
                    }

后端发送订阅信息:

public static class TemplateData {

        private String value;//

        public TemplateData(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }
public static class WxMssVo {
        private String touser;//用户openid
        private String template_id;//订阅消息模版id
        private String page = "pages/index/index";//默认跳到小程序首页
        private Map<String, TemplateData> data;//推送文字

        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;
        }
    }
public static String push(String openid, String access_token) {
        RestTemplate restTemplate = new RestTemplate();
        //这里简单起见我们每次都获取最新的access_token(时间开发中,应该在access_token快过期时再重新获取)
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + access_token;
        //拼接推送的模版
        WxMssVo wxMssVo = new WxMssVo();
        wxMssVo.setTouser(openid);//用户的openid(要发送给那个用户,通常这里应该动态传进来的)
        wxMssVo.setTemplate_id("c-UuNalv6-34k8Oz6hZsnwRDkY8**********erYM");//订阅消息模板id
        wxMssVo.setPage("pages/index/index");

        Map<String, TemplateData> m = new HashMap<>(3);
        m.put("character_string1", new TemplateData("04-01-0001"));
        m.put("time2", new TemplateData("2021年05月05日 08:30"));
        m.put("thing3", new TemplateData("张三"));

        wxMssVo.setData(m);
        ResponseEntity<String> responseEntity =
                restTemplate.postForEntity(url, wxMssVo, String.class);
        return responseEntity.getBody();
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值