cn.takujo.common_api.util.WeiXinUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of common-api Show documentation
Show all versions of common-api Show documentation
takujoframework common-api
package cn.takujo.common_api.util;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import cn.takujo.common_api.exception.BaseException;
import cn.takujo.common_api.exception.HttpException;
import cn.takujo.common_api.exception.JsonException;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* 微信小程序服务
*
* @author wzx
*
*/
@AllArgsConstructor
@Data
public final class WeiXinUtil {
private String appId;
private String appSecret;
/**
* 获取微信接口调用凭证
*
* @return token
* @throws BaseException
* 获取失败,抛出异常
*/
public String accessToken() throws BaseException {
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret="
+ appSecret;
String tokenId = HttpUtil.get(url);
Map map = JsonUtil.toMap(tokenId);
long errcode = (long) map.get("errcode");
if (errcode == 0) {
return (String) map.get("access_token");
} else {
throw new BaseException("WeiXin" + errcode, "获取accessToken失败");
}
}
/**
* 发送模板消息
*
* @param accessToken
* 接口调用凭证,如果传入null,则每次发送都会重新获取token
*
* @param map
* 调用templateMessageParamMap方法生成参数集,也可以参考小程序文档自定义
*
* @return true是发送成功,失败会抛出异常
* @throws BaseException
* 发送模板消息异常
*/
public boolean sendTemplateMessage(String accessToken, Map map) throws BaseException {
if (accessToken == null) {
accessToken = accessToken();
}
String url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + accessToken;
String post = HttpUtil.post(url, JsonUtil.toString(map));
long errcode = (long) JsonUtil.toMap(post).get("errcode");
if (errcode == 0) {
return true;
} else {
throw new BaseException("WeiXin" + errcode, "发送模板消息失败");
}
}
/**
* 模板消息参数map
*
* @param touser
* 接收者(用户)的 openid
* @param templateId
* 模板消息的id
* @param page
* 点击模板卡片后的跳转页面,仅限本小程序内的页面。
* @param formId
* 表单提交场景下,为 submit 事件带上的 formId;支付场景下,为本次支付的 prepay_id
* @param emphasisKeyword
* 模板需要放大的关键词,为null则无放大
* @param keywords
* 调用templateMessageKeyword方法生成后放入集合
* @return map 返回模板消息参数集
*/
public Map templateMessageParamMap(String touser, String templateId, String page, String formId,
String emphasisKeyword, List