公众号相关配置
这里暂时以测试界面展示,实际界面和测试界面出入不大。
登录公众号调试网址:https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
参数 | 解释 |
---|---|
appID | 应用ID |
appsecret | 应用秘钥 |
URL | 应用的回调地址接口 |
Token | 用来双向加密 |
JS域名 | 对哪些域名开放JS接口 |
接口配置相关代码
/**
* 接口信息配置
*
* @param request
* @param response
*/
@RequestMapping("/interfaceConfiguration")
public void interfaceConfiguration(HttpServletRequest request, HttpServletResponse response) {
// 微信加密签名
String signature = request.getParameter("signature");
// 时间戳
String timestamp = request.getParameter("timestamp");
// 随机数
String nonce = request.getParameter("nonce");
// 随机字符串
String echostr = request.getParameter("echostr");
// 安全认证
String security = "";
PrintWriter out = null;
try {
out = response.getWriter();
// 注意一下,这里的token就是我们上面填的token要保持一直,再进行SHA1加密
security = SHA1.getSHA1(token, timestamp, nonce,"");
// 判断是否是同一个请求
if (! StrManager.isEmpty(security) && security.equals(signature)) {
// 判断是否接口配置事件
if (! StrManager.isEmpty(echostr)) {
logger.info("配置成功");
out.print(echostr);
} else {
// 下面就自由发挥 根据不同的事件执行不同的逻辑
// 事件参数都包含在Request请求中,遍历参数即可
//......
}
}
} catch (Exception e) {
e.printStackTrace();
logger.error("程序出错", e);
} finally {
out.close();
out = null;
}
}
/**
* SHA1加密
*
* @param token
* @param timestamp
* @param nonce
* @param encrypt
* @return
*/
public String getSHA1(String token, String timestamp, String nonce, String encrypt) {
try {
String[] array = new String[] { token, timestamp, nonce, encrypt };
StringBuffer sb = new StringBuffer();
// 字符串排序
Arrays.sort(array);
for (int i = 0; i < 4; i++) {
sb.append(array[i]);
}
String str = sb.toString();
// SHA1签名生成
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(str.getBytes());
byte[] digest = md.digest();
StringBuffer hexstr = new StringBuffer();
String shaHex = "";
for (int i = 0; i < digest.length; i++) {
shaHex = Integer.toHexString(digest[i] & 0xFF);
if (shaHex.length() < 2) {
hexstr.append(0);
}
hexstr.append(shaHex);
}
return hexstr.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
获取access_token
科普一下access_token吧,它是我们调用公众号接口的凭据,有效期只有两个小时, 需要用户定时去刷新。废物不多了说直接上代码。
/**
* 更新AccessToken
*/
public void updateAccessToken() throws Exception {
// 写自己Appid
String appId = "xxxxxxx";
// 写自己Appsecret
String secret = "xxxxxxx";
String endpoint = "https://api.weixin.qq.com/cgi-bin/token";
Map<String, String> heads = new HashMap<String, String>(5);
Map<String, String> params = new HashMap<>() ;
params.put("grant_type", "client_credential");
params.put("appid", appId);
params.put("secret", secret);
try {
// 这是封装的httpGet请求,请求方法需要你们自己写。
Map<String, String> ret = HttpMethodUtil.httpGetMethod(endpoint, heads, params);
String retJson = ret.get(HttpMethodUtil.retKey);
if (StrManager.isEmpty(retJson)) {
logger.error("Appid: ".concat(appId.concat(" 更新ACCESSTOKENJOB失败 返回数据为空")));
return;
}
// 转成JSON字符串
JSONObject o = JSONObject.parseObject(retJson);
// 判断报错字段
if (o.containsKey("errcode") && o.getInteger("errcode") != 0) {
throw new Exception(o.getString("errmsg"));
}
// AccessToken
String accessToken = o.getString("access_token");
// 后面就自己写啦,更新保存的操作
//
// ......
} catch (Exception e) {
e.printStackTrace();
logger.error("Appid: ".concat(appId.concat(" 更新ACCESSTOKENJOB失败 ")), e);
}
}
消息模板推送
先去我们公众号后台配置推送模板,如下图
属性 | 解释 |
---|---|
first.DATA | 模板标题 |
key1.DATA | 目标内容 |
这里的key1.DATA只是这款模板的变量名,其他模板可能有key2.DATA , key3.DATA …
消息推送代码
/**
* 发送模板消息
*
* @param wxTemplate
* @param accessToken
* @throws Exception
*/
public void sendTemplate(WxTemplate wxTemplate, String accessToken) throws Exception {
String endpoint = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
String wxTemplateJson = JSONObject.toJSONString(wxTemplate);
Map<String, String> heads = new HashMap<String, String>(5);
heads.put("Content-Type", "application/json");
String openId = wxTemplate.getTouser();
try {
// 这是封装的httpPost请求,请求方法需要你们自己写。
Map<String, String> ret = HttpMethodUtil.httpPostMethod(endpoint, heads, null, wxTemplateJson, "application/json");
String retJson = ret.get(HttpMethodUtil.retKey);
if (StrManager.isEmpty(retJson)) {
throw new Exception("OpenId: ".concat(openId.concat(" 发送模板消息失败 返回数据为空")));
}
System.out.println(retJson);
JSONObject result = JSONObject.parseObject(retJson);
// 判断报错字段
if (result.containsKey("errcode") && result.getInteger("errcode") != 0) {
throw new Exception(result.getString("errmsg"));
}
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e.getMessage());
}
}
WxTemplate的实体类
public class WxTemplate {
/**
* 模板消息id
*/
private String template_id;
/**
* 用户openId
*/
private String touser;
/**
* URL置空,则在发送后,点击模板消息会进入一个空白页面(ios),或无法点击(android)
*/
private String url;
/**
* 标题颜色
*/
private String topcolor;
/**
* 详细内容
*/
private Map<String,TemplateData> data;
public String getTemplate_id() {
return template_id;
}
public void setTemplate_id(String template_id) {
this.template_id = template_id;
}
public String getTouser() {
return touser;
}
public void setTouser(String touser) {
this.touser = touser;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getTopcolor() {
return topcolor;
}
public void setTopcolor(String topcolor) {
this.topcolor = topcolor;
}
public Map<String, TemplateData> getData() {
return data;
}
public void setData(Map<String, TemplateData> data) {
this.data = data;
}
}
网页授权
在后台配置授权回调地址 如下图:
注意:沙盒是可以支持ip的,正式环境就必须用域名了。(正式环境提示支持域名带项目名的,其实是不支持带项目名的 避免踩坑)
创建授权链接
参数 | 是否必须 | 说明 |
---|---|---|
appid | 是 | 应用ID |
redirect_uri | 是 | 授权后重定向的回调地址,请使用 urlEncode 对链接进行处理 |
response_type | 是 | 返回类型,请填写code |
scope | 是 | 应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 ) |
state | 否 | 重定向后会带上state参数,不支持特殊字符,最多128字节 |
#wechat_redirect | 是 | 无论直接打开还是做页面302重定向时候,必须带此参数 |
列子:
用户同意授权后
如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE。
最后总结
以上就是公众号配置消息推送的相关教程啦,如果想深入了解或者觉得上面的信息不够详细。可以在这里找找看https://developers.weixin.qq.com/doc/offiaccount/Getting_Started/Overview.html