微信小程序向公众号推送消息超详细教程

  • 官方教程
    官方教程

  • 开通一下服务号公众号

  • 超级管理员登录服务号公众号后台
    登录地址

  • 开通模板消息
    在这里插入图片描述

  • 申请一个模板消息,获取模板ID
    在这里插入图片描述
    注意此处的参数,后续接口需要使用
    在这里插入图片描述

  • 绑定公众号与小程序
    官方教程
    1.登录微信公众号后台
    2.点击小程序管理
    在这里插入图片描述
    3.关联小程序

  • 获取微信公众号APPID
    1.登录微信公众号后台
    2.点击基本配置
    在这里插入图片描述

  • 导入HTTP依赖

     <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.3.6</version>
        </dependency>
   <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.1.15</version>
        </dependency>
  • http请求工具类
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
/**
 * 发送请求工具类
 */
public class HttpUtils {
    private static CloseableHttpClient httpClient;

    static {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(100);
        cm.setDefaultMaxPerRoute(20);
        cm.setDefaultMaxPerRoute(50);
        httpClient = HttpClients.custom().setConnectionManager(cm).build();
    }

    public static String get(String url) {
        CloseableHttpResponse response = null;
        BufferedReader in = null;
        String result = "";
        try {
            HttpGet httpGet = new HttpGet(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
            httpGet.setConfig(requestConfig);
            httpGet.setConfig(requestConfig);
            httpGet.addHeader("Content-type", "application/json; charset=utf-8");
            httpGet.setHeader("Accept", "application/json");
            response = httpClient.execute(httpGet);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            result = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static String post(String url, String jsonString) {
        CloseableHttpResponse response = null;
        BufferedReader in = null;
        String result = "";
        try {
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
            httpPost.setConfig(requestConfig);
            httpPost.setConfig(requestConfig);
            httpPost.addHeader("Content-type", "application/json; charset=utf-8");
            httpPost.setHeader("Accept", "application/json");
            httpPost.setEntity(new StringEntity(jsonString, Charset.forName("UTF-8")));
            response = httpClient.execute(httpPost);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            result = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

}

  • 配置类
/**
 * @Description: 参数配置
 */
public class WxAppletConfig {

        /**小程序appid*/
      
        public static String APPLET_APPID="";

        /**小程序秘钥*/
     
        public static String APPLET_SECRET="";


        /**公众号appid*/

        public static String  OFFICIAL_ACCOUNT_APPID="";

        /**公众号模板id*/
   
        public static String OFFICIAL_ACCOUNT_TEMPLATE_ID="";
    
}

  • 接口
package com.hk.frame.controller.push;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 小程序推送公众号消息测试
 */

@Slf4j
@Controller
public class MsgPushTest {

    /**
     * 获取token
     * @return
     */
    public String getAccessToken() {
            RestTemplate restTemplate = new RestTemplate();
            Map<String, String> params = new HashMap<>();
            params.put("APPID", WxAppletConfig.APPLET_APPID);
            params.put("APPSECRET", WxAppletConfig.APPLET_SECRET);
            params.put("grant_type", "client_credential");
            String tokenUrl="https://api.weixin.qq.com/cgi-bin/token?appid={APPID}&secret={APPSECRET}&grant_type={grant_type}";
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(tokenUrl, String.class, params);
            String body = responseEntity.getBody();
            JSONObject object = JSON.parseObject(body);
            String access_Token = object.getString("access_token");
            System.err.println("access_Token:"+access_Token);
            return access_Token;
        }




    /**
     * 推送
     * @param content
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/testPush",  method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    public String push(@RequestBody Map<String, String> content) {
        //获取需要推送的用户openid
        String openid= content.get("openid");
            //获取用户token
            String token = getAccessToken();

            String resultStatus = "0";//0:失败,1:成功
            try {
                //小程序统一消息推送
                String path = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=" + token;
                //封装参数
                JSONObject jsonData = new JSONObject();
                //小程序用户的openid
                jsonData.put("touser", openid);
                JSONObject jsonObject = new JSONObject();
                //公众号APPID
                jsonObject.put("appid", WxAppletConfig.OFFICIAL_ACCOUNT_APPID);
                //公众号模板ID
                jsonObject.put("template_id", WxAppletConfig.OFFICIAL_ACCOUNT_TEMPLATE_ID);
                //公众号模板消息所要跳转的url
                jsonObject.put("url", "https://blog.csdn.net/qq_46122292/article/details/124961251");

                //公众号模板消息所要跳转的小程序,小程序的必须与公众号具有绑定关系
                JSONObject miniprogram = new JSONObject();
                //小程序APPID
                miniprogram.put("appid",WxAppletConfig.APPLET_APPID);
                //跳转到小程序的页面路径
                miniprogram.put("pagepath","pages/main_Page/mainPage");
                jsonObject.put("miniprogram", miniprogram);

                //公众号消息数据封装
                JSONObject data = new JSONObject();
                //此处的参数key,需要对照模板中的key来设置
                data.put("first", getValue("亲爱的王先生/女士您好,您于2022年07月25日新增加一个客户。"));
                data.put("keyword1", getValue(content.get("phone")));//联系方式
                data.put("keyword2", getValue(content.get("time")));//时间
                data.put("remark", getValue("请前往小程序查看!"));
                jsonObject.put("data", data);

                jsonData.put("mp_template_msg", jsonObject);

                System.out.println("请求参数:"+jsonData);
                String s = HttpUtils.post(path, jsonData.toJSONString());

                System.out.println("返回结果:"+s);

                resultStatus="1";
            } catch (Exception e) {
                log.error("微信公众号发送消息失败!",e.getMessage());
                resultStatus="0";
            }
            return resultStatus;
        }



	 /**
     * 获取data
     * @param value
     * @return
     */
    private JSONObject getValue(String value) {
        // TODO Auto-generated method stub
        JSONObject json = new JSONObject();
        json.put("value", value);
        json.put("color", "#173177");
        return json;
    }
}

  • 测试

在这里插入图片描述
在这里插入图片描述
注意:前提是该用户得先关注该服务号

  • 12
    点赞
  • 85
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 31
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 31
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

亿只王菜菜

各位爷,赏口饭吃吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值