栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

微信小程序订阅消息推送

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

微信小程序订阅消息推送

1、需要小程序后台申请消息模板

2、小测程序推送实现

//发起推送授权
wx.requestSubscribeMessage({
    tmplIds: ["模板id"],
    success(re3) {
      if (re3.errMsg == "requestSubscribeMessage:ok") {
        //调用推送接口
        api.request('/notification', {
          touser: openid,
          page: '公众号页面',
          name4: //名称
          amount2: //价格
          character_string1: //订单号
          date3: //下单时间
        }).then(res => {
          if (res.errcode == 0) {
             api.showToast("推送成功");
            } else if (res.errcode == 40003) {
                api.showToast("touser字段openid为空或者不正确");
            } else if (res.errcode == 400037) {
                api.showToast("订阅模板id为空不正确");
            } else if (res.errcode == 43101) {            
                api.showToast("用户拒绝接受消息,如果用户之前曾经订阅过,则表示用户取消了订阅关系");
            } else if (res.errcode == 47003) {
                api.showToast("模板参数不准确");
            } else if (res.errcode == 41030) {
                api.showToast("page路径不正确,需要保证在现网版本小程序中存在,与app.json保持一致");
            }
        }).catch(err => {
          api.showToast("接口异常");
        });
      }
    }
  })

3、后端接口实现(工具类和接口)

package com.***.util.WeCahtApplet;
 
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import com.alibaba.fastjson.JSONObject;
 
public class HttpRequest {
 
    
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*
	private static JSONObject initJson(String info) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("value",info);
		return jsonObject;
	}
	
	
	
	@RequestMapping("/notification")
	@ResponseBody
	public String notification(
			@RequestParam(value = "touser", required = false) String touser,
			@RequestParam(value = "page", required = false) String page,
			@RequestParam(value = "name4" , required=false)String name4,
			@RequestParam(value = "amount2",required=false)String amount2,
			@RequestParam(value = "character_string1" , required = false)String character_string1,
			@RequestParam(value = "date3",required= false)String date3,
			HttpServletRequest httpRequest
			) {
		try {
			
			// 小程序唯一标识 (在微信小程序管理后台获取)
			String wxspAppid = "appid";
			// 小程序的 app secret (在微信小程序管理后台获取)
			String wxspSecret = "wx_secret ";
			// 请求参数
			String params = "grant_type=client_credential&appid=" + wxspAppid + "&secret=" + wxspSecret;
			// 发送获取access_token请求
			String sr = HttpRequest.sendGet("https://api.weixin.qq.com/cgi-bin/token", params);
			// 返回解析相应内容(转换成json对象,取出access_token
			String access_token = JSONObject.parseObject(sr).get("access_token").toString();
			
			
			// 请求参数
			JSONObject jsonObject1 = new JSONObject();
			JSONObject jsonData = new JSONObject();//模板内容
			jsonObject1.put("touser", touser);//推送用户的openID     
			jsonObject1.put("template_id", "G4SuIKBWoO1hsiKCaXJNGoKHuw0l5nFztADfLP7rf4g");//订阅消息模板id
			jsonObject1.put("page", page);//点击模板卡片后的跳转页面
			
			jsonData.put("name4",initJson(name4));//物品名称
			jsonData.put("amount2", initJson(amount2));//金额
			jsonData.put("character_string1", initJson(character_string1));//单号
			jsonData.put("date3", initJson(date3));//下单时间
			jsonObject1.put("data", jsonData);//模板内容
			
			
			String sr1 = HttpRequest.post(jsonObject1,"https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+access_token);
			// 返回解析相应内容(转换成json对象)
			return JSON.toJSONString(JSONObject.parseObject(sr1));
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("nn====================微信消息推送异常消息:{}"+e);
			return e.getMessage();
		}
	}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/946751.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号