一、什么是消息推送
二、整体效果
三、实现步骤
1 小程序开通订阅消息
2 postApi测试效果
三、uniapp配置
这里有个需要特别注意的点,我们要给用户发送消息,就必须引导用户授权,如下
因为用户不点击允许,你是没有办法给用户推送消息的。每一次授权只允许发送一条消息,所以如果你想尽量多的发送消息,就得尽量多的引导用户授权。
wx.requestSubscribeMessage这个方法,来获取用户的授权。
前端代码:
<button bindtap="getAuthority" type='primary'>获取订阅消息授权</button>//获取授权的点击事件getAuthority() {console.log("点击了")wx.requestSubscribeMessage({tmplIds: ['grwQUkOPAaJg-pzSZWeZawYTRFjmKmVPbkfckxWcPYQ'], //这里填入我们生成的模板idsuccess(res) {console.log('授权成功', res)wx.getUserInfo({//成功后会返回success:(res)=>{console.log(res);// 把你的用户信息存到一个变量中方便下面使用let userInfo= res.userInfo//获取openId(需要code来换取)这是用户的唯一标识符// 获取code值wx.login({//成功放回success:(res)=>{console.log("返回",res);let code=res.codeconsole.log("code",code);// 通过code换取openIdwx.request({url: `https://api.weixin.qq.com/sns/jscode2session?appid=wxf85bf469c5f5d12b&secret=76a1479c2adc31ab8eeefd23a09d4410&js_code=${code}&grant_type=authorization_code`,success:(res)=>{console.log(res);userInfo.openid=res.data.openidconsole.log("openid",userInfo.openid);}})}}) }})},fail(res) {console.log('授权失败', res)}})},
四、 后台整体编写
1、对应实体类
PushDTO.java
package com.soil.data.dto.push;import lombok.Data;import java.util.Map;/*** 小程序推送所需数据** @author hlc*/
@Data
public class PushDTO {/*** 用户openid*/private String touser;/*** //模版id*/private String template_id;/*** 默认*/private String page = "pages/index/index";/*** 跳转小程序页面*/private MiniprogramData miniprogram;/*** 放大那个推送字段*/private String emphasisKeyword = "keyword1.DATA";/*** 推送文字*/private Map<String, TemplateData> data;}
TemplateData.java
package com.soil.data.dto.push;import lombok.Data;/*** 设置推送的文字** @author hlc*/
@Data
public class TemplateData {private String value;public TemplateData(String value) {this.value = value;}
}
MiniprogramData.java
package com.soil.data.dto.push;import lombok.Data;/*** 跳转小程序时填写** @author hlc*/
@Data
public class MiniprogramData {private String appid;private String pagepath;
}
2、代码实现
package com.soil.biz.service.push;import com.alibaba.fastjson.JSONObject;
import com.soil.core.exception.AppServiceException;
import com.soil.core.exception.ExceptionDefinition;
import com.soil.core.util.DateUtils;
import com.soil.core.util.Log;
import com.soil.data.dto.push.MiniprogramData;
import com.soil.data.dto.push.PushDTO;
import com.soil.data.dto.push.TemplateData;
import com.soil.data.enums.UserLoginType;
import lombok.SneakyThrows;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;import java.util.Date;
import java.util.HashMap;
import java.util.Map;/*** hlc*/
@Service
public class PushBizService {private OkHttpClient okHttpClient = new OkHttpClient();public static final String WX_ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type={grant_type}&appid={appid}&secret={secret}";/*** 发送方法* @param pushDTO 所需数据* @return responseEntity*/@SneakyThrowspublic ResponseEntity<String> pushOneUser(PushDTO pushDTO) {final String SEND_INFO_URL = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=";RestTemplate restTemplate = new RestTemplate();String appId = "wxf85bf469c5f5d12b";String appSecret = "76a1479c2adc31ab8eeefd23a09d4410";// 获取accessTokenJsonString accessTokenJson = getAccessTokenJSON(appId, appSecret);// 获取accessTokenJSONObject jsonObject = JSONObject.parseObject(accessTokenJson);String accessToken = jsonObject.getString("access_token");// 获取过期时间Long expiresTime = jsonObject.getLong("expires_in");System.out.println(accessToken);String url = SEND_INFO_URL + accessToken;return restTemplate.postForEntity(url, pushDTO, String.class);}/*** 测试方法*/public static void main(String[] args) {String openid = "o7TAS4zVL5D3IlVEnucI09FrCwjE";String templateId = "grwQUkOPAaJg-pzSZWeZawYTRFjmKmVPbkfckxWcPYQ";//拼接推送的模版PushDTO pushDTO = new PushDTO();//用户的openIdpushDTO.setTouser(openid);pushDTO.setTemplate_id(templateId);MiniprogramData miniprogram = new MiniprogramData();pushDTO.setMiniprogram(miniprogram);Map<String, TemplateData> data = new HashMap<>();data.put("thing9", new TemplateData("新婴儿奶瓶"));data.put("character_string1", new TemplateData("11231323"));data.put("amount24", new TemplateData("0.01"));data.put("time21", new TemplateData("2023-02-16"));pushDTO.setData(data);System.out.println("发送的模板" + data);Date date = new Date();System.out.println(DateUtils.format(date, DateUtils.DATE_TIME_PATTERN));PushBizService pushBizService = new PushBizService();ResponseEntity<String> stringResponseEntity = pushBizService.pushOneUser(pushDTO);System.out.println(stringResponseEntity);}/*** 查微信AcessToken,返回JSON值** @param appId* @param appSecret* @return* @throws Exception*/private String getAccessTokenJSON(String appId, String appSecret) throws Exception {String json = okHttpClient.newCall(new Request.Builder().url("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ appId + "&secret=" + appSecret).build()).execute().body().string();JSONObject jsonObject = JSONObject.parseObject(json);Integer errcode = jsonObject.getInteger("errcode");if (errcode == null || errcode == 0) {return json;} else {Log.info("[微信 getAccessToken] 回复失败 回复报文:" + json);throw new AppServiceException(ExceptionDefinition.THIRD_PART_SERVICE_EXCEPTION);}}}