微信公众号推送客服消息,点击进入小程序

本文介绍了如何通过Apache HttpClient库调用微信API上传图片至永久多媒体素材,并获取mediaId,随后利用mediaId实现消息推送至小程序。涉及了HTTP请求、JSON解析和OAuth授权的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

添加依赖

    <dependency>
        <groupId>commons-httpclient</groupId>
        <artifactId>commons-httpclient</artifactId>
        <version>3.1</version>
    </dependency>

调用微信上传永久多媒体素材接口,获取mediaId

/**
 * 上传图片 至公众号媒体素材
 * accessToken 接口调用凭证
 **/
public static String uploadImage(){
    String postUrl = replaceURL("https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={ACCESS_TOKEN}&type={TYPE}", access_token, "image");
    File file = new File("C:\\Users\\x1c\\Desktop\\img\\a.jpg");
    String mediaId = uploadImage(postUrl, file);
    return mediaId;
}


/**
 * 图片上传,返回mediaId
 */
public static String uploadImage(String url, File file) {
    org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
    PostMethod post = new PostMethod(url);
    post.setRequestHeader("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:30.0) Gecko/20100101 Firefox/30.0");
    post.setRequestHeader("Host", "file.api.weixin.qq.com");
    post.setRequestHeader("Connection", "Keep-Alive");
    post.setRequestHeader("Cache-Control", "no-cache");
    String result = null;
    try{
        if (file != null && file.exists()){
            FilePart filepart = new FilePart("media", file, "image/jpeg","UTF-8");
            Part[] parts = new Part[] {filepart};
            MultipartRequestEntity entity = new MultipartRequestEntity(parts, post.getParams());
            post.setRequestEntity(entity);
            int status = client.executeMethod(post);
            if (status == HttpStatus.SC_OK) {
                String responseContent = post.getResponseBodyAsString();
                // 初始化解析json格式的对象
                JsonParser jsonparer = new JsonParser();
                JsonObject json = jsonparer.parse(responseContent).getAsJsonObject();
                LogUtil.logInfo("uploadImage json =====> " + json.toString());
                //"errcode":40004,"errmsg":"invalid media type"}{ // 上传成功  {"type":"TYPE","media_id":"MEDIA_ID","created_at":123456789}
                if (json.get("errcode") == null) {
                    result = json.get("media_id").getAsString();
                }
            }
        }
    }catch (Exception e) {
        e.printStackTrace();
    }finally{
        return result;
    }
}

根据上一步返回mediaId 推送消息

/**
 * 扫码推送/关注推送 消息   点击进入小程序
 *
 * openid为公众号openid
 * mediaId上一步返回
 * appid小程序appid,注:需将小程序与公众号绑定在同一个开放平台下
 */
public void sendToApplet(String openId, String mediaId) {
    String jsonStr = "{" +
            "    \"touser\":\""+openId+"\"," +
            "    \"msgtype\":\"miniprogrampage\"," +
            "    \"miniprogrampage\":" +
            "    {" +
            "        \"title\":\"小程序首页\"," +
            "        \"appid\":\""+小程序appid+"\"," +
            "        \"pagepath\":\"pages/index\"," +
            "        \"thumb_media_id\":\""+mediaId+"\"," +
            "    }" +
            "}";
    JSONObject params = JSONObject.parseObject(jsonStr);

    JSONObject res = hrefPost("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={ACCESS_TOKEN}", "POST", params.toJSONString(), access_token);
}

工具方法

/**
 * 更换url
 */
public static String replaceURL(String url, String... params) {
    for (String param : params) {
        url = url.replaceFirst("\\{.*?\\}", param);
    }
    return url;
}

/**
 * wx http请求
 */
public static JSONObject hrefPost(String url, String method, String content, String... params) {
    try {
        URL realUrl = new URL(replaceURL(url, params));
        trustAllHttpsCertificates();
        HttpURLConnection conn = (HttpURLConnection) realUrl
                .openConnection();
        // 连接超时
        conn.setConnectTimeout(25000);
        // 读取超时 --服务器响应比较慢,增大时间
        conn.setReadTimeout(25000);
        HttpURLConnection.setFollowRedirects(true);
        // 请求方式
        conn.setRequestMethod(method);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0");
        conn.connect();
        // 获取URLConnection对象对应的输出流
        // 发送请求参数
        OutputStream os = conn.getOutputStream();
        os.write(content.getBytes("UTF-8"));// 传入参数
        InputStream is = conn.getInputStream();
        int size = is.available();
        byte[] jsonBytes = new byte[size];
        is.read(jsonBytes);
        String result = new String(jsonBytes, "UTF-8");
        os.flush();
        os.close();
        if (conn != null) {
            conn.disconnect();
        }
        return JSONObject.parseObject(result);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
### 关于微信公众号推送消息API的使用 #### 获取Access Token 为了能够调用微信公众号消息推送接口,开发者首先需要获得`access_token`。这是微信公众平台提供的一种凭证机制,用于验证请求的身份合法性。获取此令牌的过程涉及向特定URL发起GET请求,并附带应用ID(AppID)和应用密钥(AppSecret),这些参数可以在公众平台设置页面找到[^1]。 ```java // Java示例代码片段:获取 access_token 的 HTTP 请求构建 String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APP_ID&secret=APP_SECRET"; HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection(); conn.setRequestMethod("GET"); ``` #### 创建并发送模板消息 一旦成功取得有效的`access_token`之后,就可以准备创建想要推送给用户的模板消息了。这一步骤通常包括定义消息的内容结构、指定接收者的OpenID以及其他必要的字段如模板ID等。需要注意的是,每种类型的模板都有其固定的格式要求,因此建议参照官方提供的样例来填充相应部分的数据[^3]。 ```json { "touser":"OPENID", "template_id":"TEMPLATE_ID", "url":"http://weixin.qq.com/download", // 可选链接地址 "miniprogram":{ "appid":"MINI_PROGRAM_APPID", // 小程序 AppId "pagepath":"/pages/index/index" // 页面路径 }, "data": { ... } } ``` #### 发送POST请求至服务器端口 最后一步则是将上述构造好的JSON对象作为body内容,连同之前得到的`access_token`一起提交给微信服务器。这里采用HTTP POST方式发送请求,目标网址形似如下所示: `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=TOKEN_VALUE` 确保所使用的IP已被加入到微信公众账号的安全中心->服务器配置下的合法域名列表内;对于测试环境中同样适用这一规则[^4]。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值