La última versión de la función de inserción del subprograma WeChat (notificación de envío al servicio java + bloque de código del subprograma WeChat)

     微信小程序的消息推送简单的说就是发送一条微信通知给用户,用户点开消息可以查看消息内容,可以链接进入到小程序的指定页面。

1. Preparativos
Primero, habilite la función de envío de mensajes en la plataforma pública WeChat y agregue una plantilla de mensaje. Puede seleccionar una plantilla de la biblioteca de plantillas o crear una plantilla. Después de agregar la plantilla, la ID de la plantilla se utilizará a continuación.
Inserte la descripción de la imagen aquí
El subprograma APPID luego obtiene las teclas y el Inserte la descripción de la imagen aquí
dimer para abrir las herramientas de desarrollo de micro-canales
más un botón, el botón con la función para activar el método

,//记得添加逗号哦。
  sendDYMsg: function(e) {
    
    
    wx.requestSubscribeMessage({
    
    
      tmplIds: ['ooaZWfK6liHpqDAcnR2hgObdQuh2JqQP2Z_UR6vvraU'],
      success(res) {
    
    
        console.log("可以给用户推送一条中奖通知了。。。");
      }
    })
  }

tmplIds es el ID de plantilla de su subprograma. Al activar esta función, aparecerá el siguiente cuadro.
Inserte la descripción de la imagen aquí
3. Desarrollo de código de servidor (java):
1. Para las reglas antiguas, primero consulte el documento de la API de Tencent del sitio web oficial: https: // developers. weixin.qq.com /miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.send.html

Inserte la descripción de la imagen aquí
2. Presente una herramienta para el desarrollo de WeChat (personalmente se siente muy bien, puede ir y verlo usted mismo):

dirección de git: https://github.com/Wechat-Group/WxJava

Dirección del documento del mini programa: http://binary.ac.cn/weixin-java-miniapp-javadoc/

3. Archivo pom integrado:

 <!-- 小程序开发包-->
        <dependency>
            <groupId>com.github.binarywang</groupId>
            <artifactId>weixin-java-miniapp</artifactId>
            <version>3.6.0</version>
        </dependency>
 
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
 
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>4.1.21</version>
        </dependency>

4. Obtenga el openid de acuerdo con el código:
código: (énfasis) solo se puede usar una vez, y solo es válido por 5 minutos .
Inserte la descripción de la imagen aquí

/*
获取openid
 */

    private static  String getOpenid(String code){
    
    
        //临时登录凭证
        String URL = "https://api.weixin.qq.com/sns/jscode2session?appid="+APPID1+"&secret="+AppSecret1+"&js_code="+code+"&grant_type=authorization_code";
        String openId=interfaceUtil(URL, "");
        return openId;
    };

Este openid debe ser el openid del subprograma, y ​​el otro openid no puede ser
5. El enlace final es enviar el mensaje de suscripción al subprograma

La transmisión del mensaje de suscripción parámetro es diferente del mensaje de plantilla, que debe ser rellenado de acuerdo con las reglas de otras personas, y se añade la verificación periódica.
Inserte la descripción de la imagen aquí
Inserte la descripción de la imagen aquí
Código de empuje

 /**
     * 微信小程序推送订阅消息
     * create By KingYiFan on 2020/09/29
     */
    @GetMapping(value = "/messagePush")
    @ResponseBody
    public Object sendDYTemplateMessage(String openId) throws Exception {
    
    

        System.err.println("openId:"+openId);
        wxsmallTemplate tem = new wxsmallTemplate();
        //跳转小程序页面路径
        tem.setPage("pages/index/index");
        //模板消息id
        tem.setTemplate_id("-UBAuupYlK2RAbxYvhk6UvK48ujQD72RpEOdkF-sJ2s");
        //给谁推送 用户的openid (可以调用根据code换openid接口)
        tem.setToUser(openId);
        //==========================================创建一个参数集合========================================================

        List<wxsmallTemplateParam> paras = new ArrayList<wxsmallTemplateParam>();
        //这个是满参构造 keyword1代表的第一个提示  红包已到账这是提示 #DC143C这是色值不过废弃了
      wxsmallTemplateParam templateParam = new wxsmallTemplateParam(
                "thing2", "红包已到账", "#DC143C");

        paras.add(templateParam);
        paras.add(new wxsmallTemplateParam("phrase3", "刘骞", ""));
        tem.setData(paras);
        //模板需要放大的关键词,不填则默认无放大
        tem.setToken(getAccessToken());
        //=========================================封装参数集合完毕========================================================
        try {
    
    
            //进行推送
            //获取微信小程序配置:
            if(sendTemplateMsg1(getAccess_token(APPID1,AppSecret1), tem)){
    
    
                return "推送成功";
            }else{
    
    
                JSONObject jsonObject = new JSONObject();   //返回JSON格式数据
                jsonObject.put("buTie",tem);
                return jsonObject;
            }

        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        return "推送失败";
    }

    public static boolean sendTemplateMsg1(String token,wxsmallTemplate template) {
    
    
        System.err.println("token:"+token);
        boolean flag = false;

        String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN";
//        String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";

        requestUrl = requestUrl.replace("ACCESS_TOKEN", token);
        JSONObject jsonResult =JSON.parseObject(post(JSON.parseObject(template.toJSON()) ,requestUrl)) ;
        if (jsonResult != null) {
    
    
            Integer errorCode = jsonResult.getInteger("errcode");
            String errorMessage = jsonResult.getString("errmsg");
            if (errorCode == 0) {
    
    
                flag = true;
            } else {
    
    
                System.out.println("模板消息发送失败:" + errorCode + "," + errorMessage);
                flag = false;
            }
        }
        return flag;
    }

    public String getAccess_token(String appid, String appsecret) {
    
    
        String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+appsecret;
//                      https://api.weixin.qq.com/cgi-bin/token.
        JSONObject jsonObject = doGet1(url);
        System.out.println(jsonObject.toString());
        String errCode = jsonObject.getString("expires_in");
        if (!StringUtils.isEmpty(errCode)  && !StringUtils.isEmpty(jsonObject.getString("access_token").toString())) {
    
    
            String token = jsonObject.get("access_token").toString();
            return token;
        } else {
    
    
            return null;
        }
    }

    public static JSONObject doGet1(String url) {
    
    
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        JSONObject jsonObject = null;
        try {
    
    
            HttpResponse httpResponse = client.execute(httpGet);
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
    
    
                String result = EntityUtils.toString(entity, "UTF-8");
                jsonObject = JSONObject.parseObject(result);
            }
        } catch (Exception e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            try {
    
    
                //        释放连接
                httpGet.releaseConnection();
                client.close();
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }
        return jsonObject;
    }
    //post请求
public static String post(JSONObject json,String URL) {
    
    

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(URL);
        post.setHeader("Content-Type", "application/json");
        post.addHeader("Authorization", "Basic YWRtaW46");
        String result = "";

        try {
    
    

            StringEntity s = new StringEntity(json.toString(), "utf-8");
            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));
            post.setEntity(s);

            // 发送请求
            HttpResponse httpResponse = client.execute(post);

            // 获取响应输入流
            InputStream inStream = httpResponse.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    inStream, "utf-8"));
            StringBuilder strber = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
                strber.append(line + "\n");
            inStream.close();

            result = strber.toString();
            System.out.println(result);

            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
    
    
                System.out.println("请求服务器成功,做相应处理");
            } else {
    
    
                System.out.println("请求服务端失败");
            }
        } catch (Exception e) {
    
    
            System.out.println("请求异常");
            throw new RuntimeException(e);
        }

        return result;
    }

Inserte la descripción de la imagen aquí
Hasta ahora, este es el final del mensaje de suscripción al subprograma WeChat, ¿es súper simple?

Permítanme compartir con ustedes una solución que solo solicita al usuario una vez, y siempre puede enviar notificaciones sin preguntar la próxima vez: WeChat está configurado para mantener siempre las selecciones anteriores, no el botón de consulta, simplemente haga clic en la marca. La próxima vez que haga clic en la función de notificación, no se le pedirá al usuario. Hice clic en el botón y ahora no he encontrado dónde abrir este mensaje.

Inserte la descripción de la imagen aquí

Supongo que te gusta

Origin blog.csdn.net/songyinyi/article/details/108861438
Recomendado
Clasificación