微信公众号相关


import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.MessageFormat;

public class WeChatTemplateMessageSender {
    public static final String WX_APPID = "xxx";
    public static final String WX_APPSECRET = "xxx";
    public static final String WX_TEMPLATEID = "xxx";

    public static void main(String[] args) {

        String appId = WX_APPID;
        String appSecret = WX_APPSECRET;
        String openId = "xxx";
        String templateId = WX_TEMPLATEID;
        String accessToken = getAccessToken(appId, appSecret);
        System.out.println(accessToken);
        Boolean aBoolean = userIsFollowPublic(accessToken, openId);
        System.out.println(aBoolean);
        // 构造模板消息的数据
        JSONObject data = buildTemplateData();
        // 构造请求参数
        JSONObject params = new JSONObject();
        params.put("touser", openId);
        params.put("template_id", templateId);
        params.put("url", "www.baidu.com");
        params.put("data", data);
        boolean isMessageSent = sendTemplateMessage(accessToken, params);

        if (isMessageSent) {
            System.out.println("模板消息发送成功");
        } else {
            System.out.println("模板消息发送失败");
        }

        String sceneStr = "123"; // 替换为您的场景值
        int expireSeconds = 2592000; // 替换为您的二维码有效时间,单位为秒

        String ticket = generateQRCodeTicket(accessToken, sceneStr, expireSeconds);
        if (ticket != null) {
            String qrCodeUrl = getQRCodeImageUrl(ticket);
            System.out.println("二维码图片URL: " + qrCodeUrl);
        }
    }


    /**
     * 发送模板消息
     * @param accessToken
     * @param params
     * @return
     */
    public static Boolean sendTemplateMessage(String accessToken, JSONObject params) {
        // 发送消息请求
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(MediaType.get("application/json; charset=utf-8"), params.toString());
        Request request = new Request.Builder()
                .url("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken)
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            String s = response.body().string();
            System.out.println(s);
            if (s.contains("\"errcode\":0")) {
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        return false;
    }

    /**
     * 获取accessToken
     * @param appId
     * @param appSecret
     * @return
     */
    public static String getAccessToken(String appId, String appSecret) {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
        String accessToken = "";

        try {
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("GET");

            int responseCode = con.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // 解析返回的JSON数据,获取access_token
                // 注意:实际开发中,建议使用JSON解析库来解析JSON数据
                String jsonString = response.toString();
                int startIndex = jsonString.indexOf("\"access_token\":\"") + 16;
                int endIndex = jsonString.indexOf("\",\"expires_in\"");
                accessToken = jsonString.substring(startIndex, endIndex);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return accessToken;
    }


    /**
     * 用户是否关注公众号
     * @param token
     * @param openid
     * @return
     */
    public static Boolean userIsFollowPublic(String token, String openid) {
        Integer subscribe = 0;
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_CN";
        url = MessageFormat.format(url, token, openid);
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            http.connect();
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String message = new String(jsonBytes, "UTF-8");
            JSONObject demoJson = JSONObject.parseObject(message);
            subscribe = demoJson.getIntValue("subscribe"); // 此字段为关注字段  关注为1 未关注为0
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 1 == subscribe;
    }

    private static JSONObject buildTemplateData() {
        JSONObject data = new JSONObject();

        JSONObject first = new JSONObject();
        first.put("value", "Hello, World!");
        first.put("color", "#173177");

        JSONObject keyword1 = new JSONObject();
        keyword1.put("value", "Keyword 1");
        keyword1.put("color", "#173177");

        JSONObject keyword2 = new JSONObject();
        keyword2.put("value", "Keyword 2");
        keyword2.put("color", "#173177");

        JSONObject keyword3 = new JSONObject();
        keyword3.put("value", "Keyword 3");
        keyword3.put("color", "#173177");

        JSONObject keyword4 = new JSONObject();
        keyword4.put("value", "Keyword 4");
        keyword4.put("color", "#173177");

        JSONObject keyword5 = new JSONObject();
        keyword5.put("value", "Keyword 5");
        keyword5.put("color", "#173177");

        JSONObject remark = new JSONObject();
        remark.put("value", "This is a sample template message.");
        remark.put("color", "#173177");

        data.put("first", first);
        data.put("keyword1", keyword1);
        data.put("keyword2", keyword2);
        data.put("keyword3", keyword3);
        data.put("keyword4", keyword4);
        data.put("keyword5", keyword5);
        data.put("remark", remark);

        return data;
    }


    /**
     * 生成公众号二维码
     * @param accessToken
     * @param sceneStr
     * @param expireSeconds
     * @return
     */
    public static String generateQRCodeTicket(String accessToken, String sceneStr, int expireSeconds) {
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(MediaType.get("application/json; charset=utf-8"), getRequestBody(sceneStr, expireSeconds));
        Request request = new Request.Builder()
                .url("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            String s = response.body().string();
            System.out.println(s);
            JSONObject jsonObject = JSONObject.parseObject(s);
            String ticket = jsonObject.getString("ticket");
            if (ticket != null && !ticket.isEmpty()) {
                return ticket;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getQRCodeImageUrl(String ticket) {
        return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket;
    }

    public static String getRequestBody(String sceneStr, int expireSeconds) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("expire_seconds", expireSeconds);
        jsonObject.put("action_name", "QR_STR_SCENE");
        JSONObject actionInfo = new JSONObject();
        JSONObject scene = new JSONObject();
        scene.put("scene_str", sceneStr);
        actionInfo.put("scene", scene);
        jsonObject.put("action_info", actionInfo);
        return jsonObject.toString();
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值