Mensagem push do serviço de modelo de mensagem de conta oficial do WeChat

A primeira etapa é configurar o maven primeiro.

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <version>2.2.2.RELEASE</version>
        </dependency>

        <!-- apache commons-text-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-text</artifactId>
            <version>1.1</version>
        </dependency>


        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-http</artifactId>
            <version>5.8.6</version>
        </dependency>

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-json</artifactId>
            <version>5.8.6</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.28</version>
        </dependency>

O segundo passo é carregar o código diretamente! ei ei

public static final String APPID = "你的公众号的APPID";
public static final String SECRET = "你的公众号的SECRET";

A obtenção da credencial AccessToken é muito importante e precisa ser atualizada a cada duas horas.

public static String getAccessToken() throws Exception {
        String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                + APPID + "&secret=" + SECRET;
        System.out.println("URL for getting accessToken accessTokenUrl=" + accessTokenUrl);

        URL url = new URL(accessTokenUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.connect();

        //获取返回的字符
        InputStream inputStream = connection.getInputStream();
        int size = inputStream.available();
        byte[] bs = new byte[size];
        inputStream.read(bs);
        String message = new String(bs, "UTF-8");

        //获取access_token
        JSONObject jsonObject = JSONObject.parseObject(message);
        String accessToken = jsonObject.getString("access_token");
        String expires_in = jsonObject.getString("expires_in");
        System.out.println("accessToken=" + accessToken);
        System.out.println("expires_in=" + expires_in);
        return accessToken;
    }

public static String httpRequest(String requestUrl,String requestMethod,String output){
        try{
            URL url = new URL(requestUrl);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setRequestMethod(requestMethod);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            if(null != output){
                OutputStream outputStream = connection.getOutputStream();
                outputStream.write(output.getBytes("utf-8"));
                outputStream.close();
            }
            // 从输入流读取返回内容
            InputStream inputStream = connection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null){
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            connection.disconnect();
            return buffer.toString();
        }catch(Exception e){
            e.printStackTrace();
        }
        return "";
    }
private String sendMsg() throws Exception {
        String result = null;
        //通过上述方法获取accessToken
        String accessToken = getAccessToken();
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+accessToken;

        JSONObject requestBody = new JSONObject();
        requestBody.put("touser", "指定用户的openId");
        requestBody.put("template_id", "消息模板id");

        JSONObject data = new JSONObject();
        JSONObject thing3 = new JSONObject();
        thing3.put("value", "你的数据");
        JSONObject time7 = new JSONObject();
        time7.put("value", "你的数据");
        JSONObject thing6 = new JSONObject();
        thing6.put("value", "你的数据");
        JSONObject date3 = new JSONObject();
        date3.put("value", "你的数据");

        data.put("first", thing3);
        data.put("keyword1", time7);
        data.put("keyword2", thing6);
        data.put("remark", date3);

        requestBody.put("data", data);
        System.out.println("数据为:" + requestBody);
        //将数据通过流的方式进行解析返回
        result = httpRequest(requestUrl, "POST", requestBody.toString());
        return result;
    }

Finalmente, vamos apresentar o modelo de mensagem. Isso também é uma armadilha, e 70% do tempo é gasto apenas neste lugar! ! ! !

Primeiro, entre na plataforma oficial de gerenciamento de contas e, em seguida, encontre o modelo de mensagem conforme mostrado na figura abaixo. Se você não o tiver no início, vá para a nova função para ativá-lo. Não procure notificações de assinatura. Observe que, embora os dois sejam muito semelhantes, os pedidos são diferentes. , o modelo também é diferente.

Desta forma, você pode adicioná-lo passo a passo, especifique a linha! ! !

Acho que você gosta

Origin blog.csdn.net/m0_74141658/article/details/129145549
Recomendado
Clasificación