小程序推送服务通知(前后端代码)

微信公众平台设置

1.点击功能里的订阅消息
在这里插入图片描述

2.在我的模板中选择需要的模板
在这里插入图片描述

前端相关代码

   data() {
    
    
        return {
    
    
          token: '',
          openId:'',
          // 模板数据
          // 需要对应模板详情里面的key
          templateData: {
    
    
            // 商品
            thing1: {
    
    
              value: '通用正面pe6c+背面压纹8c自封包装袋'
            },
            // 支付金额
            amount3: {
    
    
              value: '100'
            },
            // 下单时间
            date5: {
    
    
              value: '2019-10-14 27:34:21'
            },
            // 订单编号
            character_string6: {
    
    
              value: 'ADWMP2933887762'
            }
          }
        };
      },

1. 需要获取openid

 getOpenid(){
    
    
    		uni.login({
    
    
    			success: res => {
    
    
    				// console.log(res);
    				uni.request({
    
    
    				  url: `https://api.weixin.qq.com/sns/jscode2session?appid=appid&secret=secret&js_code=${
      
      res.code}&grant_type=authorization_code`,
    				  success:(res)=>{
    
    
    					this.openId = res.data.openid
    				  }
    				})
    			}
    		})
    	},

2.需要获取token

 getToken() {
    
    
          uni.request({
    
    
                url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=appid&secret=secret',
                success: res => {
    
    
    				this.token = res.data.access_token
                }
              })
        },

3.调起小程序订阅消息界面

<view @click="sendMessage">点击发送模板消息</view>

   	sendMessage(e) {
    
    
          const data = {
    
    
            touser: this.openId,
            template_id: 'cOC88hrTVanokHdVoSvvUhr54o44ShPQA3iN-1jeFXY', //微信公众平台上有对应的模板id
            page: 'pages/index/index',
            data: this.templateData // 模板数据
          };
          
          // 调起客户端小程序订阅消息界面
          uni.requestSubscribeMessage({
    
    
            tmplIds: ['cOC88hrTVanokHdVoSvvUhr54o44ShPQA3iN-1jeFXY'],
            success: res =>  {
    
    
              console.log(res);
              if (res.errMsg === 'requestSubscribeMessage:ok') {
    
    
                this.submit(data);
              }
            }
          });
        },

4.发送订阅消息

 submit(data) {
    
    
          wx.request({
    
    
            url: `https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${
      
      this.token}`,
            data,
            method: 'POST',
            success: res => {
    
    
              console.log('发送成功');
              console.log(res);
            },
            fail: err => {
    
    
              console.log('发送失败');
              console.log(err);
            }
          });
        }

后端相关代码

 String accessToken;//因为用到的地方很多,所以我写成全局变量了
    	//获取accessToken
    	@RequestMapping("at")
    	@ResponseBody
    	public JSONObject at() {
    
    
            // 微信小程序ID
            String appid = "你自己的appid";
            // 微信小程序秘钥
            String secret = "你自己的秘钥";
    
            String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
            // 发送请求,返回Json字符串
            String str = WeChatUtil.httpRequest(url, "GET", null);
            // 转成Json对象 获取openid
            Map<String,String> map=new HashMap<String,String>();
            //转化成json
            JSONObject fromObject = JSONObject.fromObject(str);
            //获取at
            accessToken = fromObject.getString("access_token");
            System.out.println("后台获取的"+accessToken);
            //给小程序端返回at
            map.put("mes", accessToken);
        	JSONObject json=JSONObject.fromObject(map);
    		return json;
            //JSONObject jsonObject = JSONObject.parseObject(str);
            //System.out.println("access_token---"+jsonObject.toJSONString());
            // 我们需要的openid,在一个小程序中,openid是唯一的
    //        String access_token = jsonObject.get("access_token").toString();
    //        return access_token;	
    	}
    

    //发送消息
    	@RequestMapping("addsenddata")
        @ResponseBody
          public void sendMessage(@RequestBody String _jsonData){
    
    
            System.out.println("sendMesg传入参数"+_jsonData);
            // 微信小程序ID
            String appid = "自己appid";
            // 微信小程序秘钥
            String secret = "自己的秘钥";
    
            String ACCESS_TOKEN=accessToken;
            // 根据小程序穿过来的code想这个url发送请求
            String url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token="+ACCESS_TOKEN;
            // 发送请求,返回Json字符串
            String str = WeChatUtil.httpRequest(url, "POST", _jsonData);
            // 转成Json对象 获取openid
            JSONObject fromObject = JSONObject.fromObject(str);
            
            //JSONObject jsonObject = JSONObject.parseObject(str);
            System.out.println("jsonObject____"+fromObject.toString());
            // 我们需要的openid,在一个小程序中,openid是唯一的
        }
    

    public class WeChatUtil {
    
    
        public static String httpRequest(String requestUrl,String requestMethod,String output){
    
    
            try{
    
    
                URL url = new URL(requestUrl);
                HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setUseCaches(false);
                if(null != output){
    
    
                    OutputStream outputStream = connection.getOutputStream();
                    outputStream.write(output.getBytes("utf-8"));
                    outputStream.close();
                }
                // 从输入流读取返回内容
                InputStream inputStream = connection.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String str = null;
                StringBuffer buffer = new StringBuffer();
                while ((str = bufferedReader.readLine()) != null){
    
    
                    buffer.append(str);
                }
                bufferedReader.close();
                inputStreamReader.close();
                inputStream.close();
                inputStream = null;
                connection.disconnect();
                return buffer.toString();
            }catch(Exception e){
    
    
                e.printStackTrace();
            }
            return "";
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_58648235/article/details/126798106