Springboot微信公众号模板消息推送

1.Controller层代码

package com.example.tuisong.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/api")
public class WeChatConller {
    @Value("${wechat.appId}")
    private String appId;

    @Value("${wechat.appSecret}")
    private String appSecret;

    @Value("${wechat.templateMessageUrl}")
    private String templateMessageUrl;

    @PostMapping("/template-message")
    public String sendTemplateMessage(@RequestBody String data) {
        // 1. 获取access_token
        String accessToken = getAccessToken();

        // 2. 构造模板消息
        String templateMessage = buildTemplateMessage(data);

        // 3. 发送模板消息
        String url = templateMessageUrl + "?access_token=" + accessToken;
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.postForObject(url, templateMessage, String.class);
        return response;
    }

    private String getAccessToken() {
        String url = templateMessageUrl + "&appid=" + appId + "&secret=" + appSecret;
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(url, String.class);
        return response;
    }

    private String buildTemplateMessage(String data) {
        // 根据传入的数据构造模板消息
        // 可以使用JSON转换工具,如Jackson或Gson
        return data;
    }

}

2.配置文件application.properties
请添加图片描述
3.获取access-token
GET:https请求方式: GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
请添加图片描述

发送模板消息http请求方式: POST https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN
请添加图片描述
touser:是openID
template_id是模板id

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值