100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > 微信小程序订阅消息推送

微信小程序订阅消息推送

时间:2020-09-27 07:03:33

相关推荐

微信小程序订阅消息推送

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 .HttpURLConnection;import .URL;import .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 {/*** 向指定URL发送GET方法的请求* * @param url发送请求的URL** @param param* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。* @return URL 所代表远程资源的响应结果*/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", "*/*");connection.setRequestProperty("connection", "Keep-Alive");connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");// 建立实际的连接connection.connect();// 获取所有响应头字段Map<String, List<String>> map = connection.getHeaderFields();// 遍历所有的响应头字段for (String key : map.keySet()) {System.out.println(key + "--->" + map.get(key));}// 定义 BufferedReader输入流来读取URL的响应in = new BufferedReader(new InputStreamReader(connection.getInputStream()));String line;while ((line = in.readLine()) != null) {result += line;}} catch (Exception e) {System.out.println("发送GET请求出现异常!" + e);e.printStackTrace();}// 使用finally块来关闭输入流finally {try {if (in != null) {in.close();}} catch (Exception e2) {e2.printStackTrace();}}return result;}}

/*** 初始化json数据* @param info* @return* @author tyg* @date 11月25日下午5:05:56*/private static JSONObject initJson(String info) {JSONObject jsonObject = new JSONObject();jsonObject.put("value",info);return jsonObject;}/*** 微信订阅消息推送* * @param location* @return*/@RequestMapping("/notification")@ResponseBodypublic 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 {/*===========1、获取access_token ============*/// 小程序唯一标识 (在微信小程序管理后台获取)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./cgi-bin/token", params);// 返回解析相应内容(转换成json对象,取出access_tokenString access_token = JSONObject.parseObject(sr).get("access_token").toString();/*===========2、整理模板参数 ============*/// 请求参数JSONObject jsonObject1 = new JSONObject();JSONObject jsonData = new JSONObject();//模板内容jsonObject1.put("touser", touser);//推送用户的openIDjsonObject1.put("template_id", "G4SuIKBWoO1hsiKCaXJNGoKHuw0l5nFztADfLP7rf4g");//订阅消息模板idjsonObject1.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);//模板内容/*===========3、发送订阅消息============*/String sr1 = HttpRequest.post(jsonObject1,"https://api./cgi-bin/message/subscribe/send?access_token="+access_token);// 返回解析相应内容(转换成json对象)return JSON.toJSONString(JSONObject.parseObject(sr1));} catch (Exception e) {// TODO: handle exceptionSystem.out.println("\n\n====================微信消息推送异常消息:{}"+e);return e.getMessage();}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。