Java 小程序推送模板消息到公众号
具体逻辑
1.需用户先关注公众号
2.小程序端登录时前端静默授权获取code
3.根据code获取公众号openId并存入数据库
4.获取公众号accessToken
代码实现
1.获取公众号openId
/**
* 前端在小程序中通过静默授权获取code再通过code来获取关注公众号的某一个用户的公众号opendId
* @return
*/
public Result getOfficialAccountOpenId(String code,String phone){
if(Strings.isNullOrEmpty(code)){//Strings调用的方法是自己定义的工具类
throw new BusinessException("code不能为空");
}
if(Strings.isNullOrEmpty(phone)){
throw new BusinessException("phone不能为空");
}
LinkedHashMap<String, String> params = new LinkedHashMap<>();
//微信公众号的appid
String appid = "****";
//微信公众号的secret
String secret = "****";
params.put("appid",appid);
params.put("secret",secret);
params.put("code",code);
params.put("grant_type","authorization_code");
String resultStr=" ";
try {
//请求获取公众号信息
resultStr = Https.get(" https://api.weixin.qq.com/sns/oauth2/access_token",params);
} catch (IOException e) {
log.info("请求失败:"+e);
}
log.info("=============获取公众号用户openId返回:" + resultStr);
//定义实体类接收返回信息
WeChatOfficialAccountResponse resp = Jsons.toBean(resultStr, WeChatOfficialAccountResponse.class);
if(Strings.isNotNullOrEmpty(resp.getErrcode())){
log.info("=============获取公众号用户openId口返回:" + resp.getErrmsg());
return Results.failure("获取公众号用户openId异常");
}
//获取到公众号id
String officialAccountId = resp.getOpenid();
//下面均为业务逻辑判断
SysUser phone1 = sysUserDao.get(Search.newSearch().addPiece("phone", Operator.eq, phone));
if(phone1 == null){
return Results.failure("查无此人");
}
String officialAccount = phone1.getOfficialAccount();
if(Strings.isNullOrEmpty(officialAccount)){
phone1.setOfficialAccount(officialAccountId);
sysUserDao.update(phone1);
return Results.success("获取成功");
}
return Results.success();
}
2.获取公众号token及参数封装
/**
* 小程序推送到公众号消息通知
* @param openId 发送给谁的id
* @param content 详细类容
* @param approvalName 审批名称
* @param applyName 申请人
* @param date 申请时间
* @param applicationContent 申请内容
* @param remark
* @return
* @throws IOException
*/
public Result sendMessageToXXX( String openId, String content,String approvalName,String applyName,String date,String applicationContent,String remark){
Map params = new HashMap(16);
params.put("grant_type", "client_credential");
//公众号appid
params.put("appid", "***");
//公众号secret
params.put("secret", "***");
String resultStr = null;
try {
resultStr = Https.get(https://api.weixin.qq.com/cgi-bin/token, params);
} catch (IOException e) {
e.printStackTrace();
}
log.info("=============服务号微信token接口返回:" + resultStr);
/**
* WxTokenResponse 定义的返回实体类
*/
WxTokenResponse wxTokenResponse = Jsons.toBean(resultStr, WxTokenResponse.class);
String accessToken=" ";
//成功
if (wxTokenResponse.getErrCode() == null) {
//获取公众号的accesstoken
accessToken= wxTokenResponse.getAccessToken();
}else{
log.warn("服务号微信token获取异常");
}
//封装发送通知的请求参数
HashMap<String, TemplateData> data = new LinkedHashMap<>();
data.put("first",new TemplateData(content));
data.put("keyword1",new TemplateData(approvalName));
data.put("keyword2",new TemplateData(applyName));
data.put("keyword3",new TemplateData(date));
data.put("keyword4",new TemplateData(applicationContent));
data.put("remark",new TemplateData(remark));
HashMap<Object, Object> miniprogramMap = new HashMap<>();
//跳转到小程序
miniprogramMap.put("appid","***");
//accessToken:公众号的accessToken,openId:之前通过code获取的openId ApplicationConstants.OFFICIAL_ACCOUNT_PUSH:模板id,data:封装的数据,miniprogramMap具体可添加类容请查看微信文档
return sendOfficialAccountXXX(accessToken,openId,ApplicationConstants.OFFICIAL_ACCOUNT_PUSH,data,miniprogramMap);
}
3.发送消息到公众号
/**
* 发送消息到公众号
* @param accessToken 公众号token
* @param openId 之前获取的关注公众号用户的id
* @param templateId 发送模板id
* @param data 封装的发送请求数据
* @param miniprogram 跳转页面
* @return
*/
public Result sendOfficialAccountXXX(String accessToken, String openId, String templateId, Map data,Map miniprogram){
try {
Map params = new LinkedHashMap(16);
params.put("touser", openId);
params.put("template_id", templateId);
params.put("miniprogram",miniprogram);
/* if(BaseHelper.isNotEmpty(url)) {
params.put("url", url);
}*/
params.put("data", data);
log.info("微信服务号token:"+accessToken);
String resultStr = Https.httpPostWithjson("https://api.weixin.qq.com/cgi-bin/message/template/send"+"?access_token="+accessToken, Jsons.toJSONString(params));
log.info("微信公众号推送消息结果:"+resultStr);
log.info("请求参数"+Jsons.toJSONString(params));
WeChatResponse weChatResponse = Jsons.toBean(resultStr, WeChatResponse.class);
if(!SUCCESS_CODE.equals(weChatResponse.getErrcode())){
return Results.failure(weChatResponse.getErrmsg());
}
} catch (Exception e) {
log.error("========微信公众号通信异常========"+e);
return Results.failure("微信公众号通信异常");
}
return Results.success();
}