微信公众号消息推送

公众号相关配置

这里暂时以测试界面展示,实际界面和测试界面出入不大。

登录公众号调试网址: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重定向时候,必须带此参数

列子:

scope为snsapi_base
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx520c15f417810387&redirect_uri=https%3A%2F%2Fchong.qq.com%2Fphp%2Findex.php%3Fd%3D%26c%3DwxAdapter%26m%3DmobileDeal%26showwxpaytitle%3D1%26vb2ctag%3D4_2030_5_1194_60&response_type=code&scope=snsapi_base&state=123#wechat_redirect

scope为snsapi_userinfo
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf0e81c3bee622d60&redirect_uri=http%3A%2F%2Fnba.bluewebgame.com%2Foauth_response.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect

用户同意授权后

如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE。

最后总结

以上就是公众号配置消息推送的相关教程啦,如果想深入了解或者觉得上面的信息不够详细。可以在这里找找看https://developers.weixin.qq.com/doc/offiaccount/Getting_Started/Overview.html

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值