众所周知,在微信开放平台申请第三方平台成功后,开发完成,需要全网发布,这样其他公众号才可以进行授权,不然只能使用申请第三方平台时自己填写的测试公众号
官网文档地址:https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/Post_Application_on_the_Entire_Network/releases_instructions.html
当需要全网发布的时,微信开放平台会自动化测试,验证通过后才可以发布成功。详见官方文档,会给配置的消息与事件通知的地址发送消息进行测试。
Controller
/**
* 消息与事件接收
* @author yupanpan
* @date 2020/1/10 13:32
* @param request
* @param appid
* @return void
*/
@RequestMapping("/component/{appid}/event")
@ApiOperation("消息与事件接收")
public void eventNotice(HttpServletRequest request, @PathVariable("appid") String appid, HttpServletResponse response) throws AesException, IOException {
boolean eventNotice = wechatOpenPlatformThirdPartyService.eventNotice(request, appid, response);
if(eventNotice){
WXBizMsgCrypt pc = new WXBizMsgCrypt(ApplicationPropertiesUtils.getWechatOpenThirdpartyVerifyToken(), ApplicationPropertiesUtils.getWechatOpenThirdpartyEncodingKey(),
ApplicationPropertiesUtils.getWechatOpenThirdpartyAppid());
String replyMsg = pc.encryptMsg("", System.currentTimeMillis() + "",
WxUtil.generateNonceStr());//加密回复
PrintWriter writer = response.getWriter();
writer.write(replyMsg);
writer.flush();
}
}
WXBizMsgCrypt由官方提供的,
ApplicationPropertiesUtils.getWechatOpenThirdpartyVerifyToken() 对应消息校验Token
ApplicationPropertiesUtils.getWechatOpenThirdpartyEncodingKey() 对应消息加解密Key
ApplicationPropertiesUtils.getWechatOpenThirdpartyAppid() 对应第三方平台的Appid,审核通过后会有
Service
@Override
@Transactional
public boolean eventNotice(HttpServletRequest request, String appid, HttpServletResponse response){
try {
Map mapData = getMapData(request, verifyToken, encodingKey, appId);
return this.subscribeEvent(request,mapData,appid,response);
}catch (Exception e){
logger.error("第三方消息与事件推送异常",e);
return false;
}
}
@Override
@Transactional
public boolean subscribeEvent(HttpServletRequest request,Map mapData,String appid,HttpServletResponse response) throws Exception {
synchronized(this){
logger.info("解密后内容====>>>>{}",mapData.toString());
String event = mapData.get(WxConstant.WX_CARD_EVENT);
String openId = mapData.get("fromUserName");
String devWechatNumber = mapData.get("toUserName");
logger.info("======>>>openId:{}", openId);
if(WechatConstants.Event.SUBSCRIBE.getCodeType().equals(event)||WechatConstants.Event.SCAN.getCodeType().equals(event)) {
//扫码关注
String eventKey = mapData.get("eventKey");
logger.info("eventKey:{}", eventKey);
if (StringUtils.isNotBlank(eventKey)) {
//第一次关注会有qrscene_前缀,已关注再扫码直接跳进公众号,没有qrscene_前缀
if(eventKey.contains("qrscene_")){
eventKey= eventKey.replace("qrscene_", "");
}
if(eventKey.contains("&")){
String[] scene_str = eventKey.split("&");
//解密扫码参数,证明是由自己第三方平台发出的二维码关注通知,非自己第三方平台的事件不做处理
if(WechatConstants.ARTSTEP.equals(AESUtils.AESDncode(null,scene_str[1]))){
Long studentId = Long.valueOf(scene_str[0]);
if(studentId!=null){
logger.info("======>>>studentId:{}", studentId);
//新增或更新微信相关信息
this.saveStudentWechatOpenInfo(studentId, openId, appid);
//禁用旧版本的微信绑定关系通知
this.inActiveParentWechat(studentId, openId, appid);
}
}
}
} else {
//非扫码关注
}
return true;
}
//取消关注,删除绑定者所有微信隐私信息
if(WechatConstants.Event.UN_SUBSCRIBE.getCodeType().equals(event)){
logger.info("openId[{}],appId[{}]解绑",openId,appid);
studentWechatOpenInfoDao.deleteByOpenIdAndAppId(openId,appid);
return true;
}
//全网发布自动化测试公众号
if(appid.equals("wx570bc396a51b8ff8")){
logger.info("第三方平台测试公众号接受event====>>>>{}",event);
if(WechatConstants.Event.TEXT.getCodeType().equals(event)){
String content = mapData.get("content");
processTextMessage(request, response, content, openId, devWechatNumber,appid);
}
if(WechatConstants.Event.EVENT.getCodeType().equals(event)){// 返回类型值,做一下区分
//返回时, 将发送人和接收人 调换一下即可
replyEventMessage(request,response,event,openId,devWechatNumber);
}
return false;
}
return true;
}
}
只需要关注全网发布自动化测试那里的代码即可
/**
* 方法描述: 直接返回给微信开放平台
* @param request
* @param response
* @param content 文本
* @param openId 发送接收人
* @param devWechatNumber 发送人
*/
private void replyTextMessage(HttpServletRequest request, HttpServletResponse response,
String content,String openId, String devWechatNumber) throws Exception {
Long createTime = System.currentTimeMillis() / 1000;
StringBuffer sb = new StringBuffer();
sb.append("");
sb.append(" ");
sb.append(" ");
sb.append("" + createTime + " ");
sb.append(" ");
sb.append(" ");
sb.append(" ");
logger.info("发送的XML明文为====>>>>"+sb.toString());
WXBizMsgCrypt pc = new WXBizMsgCrypt(verifyToken, encodingKey,
appId);
String replyMsg = pc.encryptMsg(sb.toString(), System.currentTimeMillis() + "",
WxUtil.generateNonceStr());//加密回复
logger.info("确定发送的XML====>>>>"+replyMsg);
PrintWriter writer = response.getWriter();
writer.write(replyMsg);
writer.flush();
}
/**
* 方法描述: 类型为enevt的时候,拼接
* @param request
* @param response
* @param event
* @param openId 发送接收人
* @param devWechatNumber 发送人
*/
public void replyEventMessage(HttpServletRequest request, HttpServletResponse response,
String event, String openId, String devWechatNumber)
throws Exception {
String content = event + "from_callback";
replyTextMessage(request,response,content,openId,devWechatNumber);
}
/**
* 方法描述: 立马回应文本消息并最终触达粉丝
* @param content 文本
* @param openId 发送接收人
* @param devWechatNumber 发送人
*/
public void processTextMessage(HttpServletRequest request, HttpServletResponse response,
String content,String openId, String devWechatNumber,String appid)
throws Exception{
if("TESTCOMPONENT_MSG_TYPE_TEXT".equals(content)){
String returnContent = content+"_callback";
replyTextMessage(request,response,returnContent,openId,devWechatNumber);
}else if(StringUtils.startsWithIgnoreCase(content, "QUERY_AUTH_CODE")){
response.getWriter().print("");//需在5秒内返回空串表明暂时不回复,然后再立即使用客服消息接口发送消息回复粉丝
logger.info("content:"+content+" content[1]:"+content.split(":")[1]+" fromUserName:"+devWechatNumber+" toUserName:"+openId);
//接下来客服API再回复一次消息
//此时 content字符的内容为是 QUERY_AUTH_CODE:adsg5qe4q35
replyApiTextMessage(content.split(":")[1],openId,appid);
}
}
/**
* 方法描述: 直接返回给微信开放平台
* @param request
* @param response
* @param content 文本
* @param toUserName 发送接收人
* @param fromUserName 发送人
public void replyTextMessage(HttpServletRequest request, HttpServletResponse response,
String content,String toUserName, String fromUserName)
throws DocumentException, IOException {
Long createTime = System.currentTimeMillis() / 1000;
StringBuffer sb = new StringBuffer(512);
sb.append("");
sb.append(" ");
sb.append(" ");
sb.append(""+createTime.toString()+" ");
sb.append(" ");
sb.append(" ");
sb.append(" ");
String replyMsg = sb.toString();
logger.info("确定发送的XML为:"+replyMsg);
returnJSON(replyMsg,response);
}
*/
/**
* 方法描述: 调用客服回复消息给粉丝
* @param auth_code
* @param openId
* @throws DocumentException
* @throws IOException
* @return void
*/
public void replyApiTextMessage(String auth_code, String openId,String appid) throws Exception {
// 得到微信授权成功的消息后,应该立刻进行处理!!相关信息只会在首次授权的时候推送过来
String componentAccessToken= WechatCache.getThirdPartyAuthorizerAccessToken();//本人平台缓存的token
//https://api.weixin.qq.com/cgi-bin/component/api_query_auth 到这个微信的接口去获取数据
ThirdPartyAuthInfo thirdPartyAuthInfo = thirdPartyAuthInfoDao.findBySchoolIdAndAppId(appid);
String authorizer_access_token = thirdPartyAuthInfo.getAuthorizerAccessToken();
String result = checkCustomMessage(authorizer_access_token, openId, auth_code);
if(result.contains("40001")){
String testAuthorizerAccessToken = getTestAuthorizerAccessToken(appid);
checkCustomMessage(testAuthorizerAccessToken, appid, auth_code);
}
}
private String checkCustomMessage(String authorizer_access_token,String openId,String auth_code) throws Exception{
String url = WechatConstants.MESSAGE_CUSTOM_SEND.replace("AUTHORIZER_ACCESS_TOKEN",authorizer_access_token);
JSONObject json = new JSONObject();
json.put("touser",openId);
json.put("msgtype", "text");
json.put("text", "{\"content\":\""+auth_code+"_from_api"+"\"}");
String result = HTTPUtils.sendPost(url, json.toJSONString());
logger.info("客服发送接口返回值:"+result);
return result;
}
补充:
public Map getMapData(HttpServletRequest request,String token,String encodingKey,String appId) {
BufferedReader reader = null;
PrintWriter writer = null;
try {
reader = request.getReader();
String notifyStr = "";
String tempStr = "";
while ((tempStr = reader.readLine()) != null) {
notifyStr += tempStr;
}
if (StringUtils.isNotBlank(notifyStr)) {
logger.info("=========>微信通知事件【解密参数token==>>{},encodingKey==>>{},appId==>>{}】 ",token,encodingKey,appId);
logger.info("=========>微信通知事件【解密前内容】: " + notifyStr);
WXBizMsgCrypt pc = new WXBizMsgCrypt(token, encodingKey,appId);
Map map = WxUtil.xmlToMapWithLowerStart(notifyStr);
logger.info("=========>微信通知事件【解密前键值对内容】: {}",map.toString());
String decryptMsg = pc.decrypt(map.get(WxConstant.WX_EVENT_ENCRYPT));//解密消息体
return WxUtil.xmlToMapWithLowerStart(decryptMsg);
}
} catch (Exception e) {
logger.error("微信事件通知分发处理异常", e);
} finally {
try {
if (reader != null) {
reader.close();
}
if (writer != null) {
writer.close();
}
} catch (Exception e) {
}
}
return null;
}
WXBizMsgCrypt
/**
* 对公众平台发送给公众账号的消息加解密示例代码.
*
* @copyright Copyright (c) 1998-2014 Tencent Inc.
*/
// ------------------------------------------------------------------------
/**
* 针对org.apache.commons.codec.binary.Base64,
* 需要导入架包commons-codec-1.9(或commons-codec-1.8等其他版本)
* 官方下载地址:http://commons.apache.org/proper/commons-codec/download_codec.cgi
*/
package com.shinedata.util.wxcard;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Random;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 提供接收和推送给公众平台消息的加解密接口(UTF8编码的字符串).
*
* - 第三方回复加密消息给公众平台
* - 第三方收到公众平台发送的消息,验证消息的安全性,并对消息进行解密。
*
* 说明:异常java.security.InvalidKeyException:illegal Key Size的解决方案
*
* - 在官方网站下载JCE无限制权限策略文件(JDK7的下载地址:
* http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
* - 下载后解压,可以看到local_policy.jar和US_export_policy.jar以及readme.txt
* - 如果安装了JRE,将两个jar文件放到%JRE_HOME%\lib\security目录下覆盖原来的文件
* - 如果安装了JDK,将两个jar文件放到%JDK_HOME%\jre\lib\security目录下覆盖原来文件
*
*/
public class WXBizMsgCrypt {
Logger logger = LoggerFactory.getLogger(WXBizMsgCrypt.class);
static Charset CHARSET = Charset.forName("utf-8");
Base64 base64 = new Base64();
byte[] aesKey;
String token;
String appId;
/**
* 构造函数
* @param token 公众平台上,开发者设置的token
* @param encodingAesKey 公众平台上,开发者设置的EncodingAESKey
* @param appId 公众平台appid
*
* @throws AesException 执行失败,请查看该异常的错误码和具体的错误信息
*/
public WXBizMsgCrypt(String token, String encodingAesKey, String appId) throws AesException {
if (encodingAesKey.length() != 43) {
throw new AesException(AesException.IllegalAesKey);
}
this.token = token;
this.appId = appId;
aesKey = Base64.decodeBase64(encodingAesKey + "=");
}
// 生成4个字节的网络字节序
byte[] getNetworkBytesOrder(int sourceNumber) {
byte[] orderBytes = new byte[4];
orderBytes[3] = (byte) (sourceNumber & 0xFF);
orderBytes[2] = (byte) (sourceNumber >> 8 & 0xFF);
orderBytes[1] = (byte) (sourceNumber >> 16 & 0xFF);
orderBytes[0] = (byte) (sourceNumber >> 24 & 0xFF);
return orderBytes;
}
// 还原4个字节的网络字节序
int recoverNetworkBytesOrder(byte[] orderBytes) {
int sourceNumber = 0;
for (int i = 0; i < 4; i++) {
sourceNumber <<= 8;
sourceNumber |= orderBytes[i] & 0xff;
}
return sourceNumber;
}
// 随机生成16位字符串
String getRandomStr() {
String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 16; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
/**
* 对明文进行加密.
*
* @param text 需要加密的明文
* @return 加密后base64编码的字符串
* @throws AesException aes加密失败
*/
public String encrypt(String randomStr, String text) throws AesException {
ByteGroup byteCollector = new ByteGroup();
byte[] randomStrBytes = randomStr.getBytes(CHARSET);
byte[] textBytes = text.getBytes(CHARSET);
byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length);
byte[] appidBytes = appId.getBytes(CHARSET);
// randomStr + networkBytesOrder + text + appid
byteCollector.addBytes(randomStrBytes);
byteCollector.addBytes(networkBytesOrder);
byteCollector.addBytes(textBytes);
byteCollector.addBytes(appidBytes);
// ... + pad: 使用自定义的填充方式对明文进行补位填充
byte[] padBytes = PKCS7Encoder.encode(byteCollector.size());
byteCollector.addBytes(padBytes);
// 获得最终的字节流, 未加密
byte[] unencrypted = byteCollector.toBytes();
try {
// 设置加密模式为AES的CBC模式
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");
IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
// 加密
byte[] encrypted = cipher.doFinal(unencrypted);
// 使用BASE64对加密后的字符串进行编码
String base64Encrypted = base64.encodeToString(encrypted);
return base64Encrypted;
} catch (Exception e) {
e.printStackTrace();
throw new AesException(AesException.EncryptAESError);
}
}
/**
* 对密文进行解密.
*
* @param text 需要解密的密文
* @return 解密得到的明文
* @throws AesException aes解密失败
*/
public String decrypt(String text) throws AesException {
byte[] original;
try {
// 设置解密模式为AES的CBC模式
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec key_spec = new SecretKeySpec(aesKey, "AES");
IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16));
cipher.init(Cipher.DECRYPT_MODE, key_spec, iv);
// 使用BASE64对密文进行解码
byte[] encrypted = Base64.decodeBase64(text);
// 解密
original = cipher.doFinal(encrypted);
} catch (Exception e) {
e.printStackTrace();
throw new AesException(AesException.DecryptAESError);
}
String xmlContent, from_appid;
try {
// 去除补位字符
byte[] bytes = PKCS7Encoder.decode(original);
// 分离16位随机字符串,网络字节序和AppId
byte[] networkOrder = Arrays.copyOfRange(bytes, 16, 20);
int xmlLength = recoverNetworkBytesOrder(networkOrder);
xmlContent = new String(Arrays.copyOfRange(bytes, 20, 20 + xmlLength), CHARSET);
from_appid = new String(Arrays.copyOfRange(bytes, 20 + xmlLength, bytes.length),
CHARSET);
} catch (Exception e) {
e.printStackTrace();
throw new AesException(AesException.IllegalBuffer);
}
// appid不相同的情况
if (!from_appid.equals(appId)) {
throw new AesException(AesException.ValidateAppidError);
}
return xmlContent;
}
/**
* 将公众平台回复用户的消息加密打包.
*
* - 对要发送的消息进行AES-CBC加密
* - 生成安全签名
* - 将消息密文和安全签名打包成xml格式
*
*
* @param replyMsg 公众平台待回复用户的消息,xml格式的字符串
* @param timeStamp 时间戳,可以自己生成,也可以用URL参数的timestamp
* @param nonce 随机串,可以自己生成,也可以用URL参数的nonce
*
* @return 加密后的可以直接回复用户的密文,包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串
* @throws AesException 执行失败,请查看该异常的错误码和具体的错误信息
*/
public String encryptMsg(String replyMsg, String timeStamp, String nonce) throws AesException {
// 加密
String encrypt = encrypt(getRandomStr(), replyMsg);
// 生成安全签名
if (timeStamp == "") {
timeStamp = Long.toString(System.currentTimeMillis());
}
String signature = SHA1.getSHA1(token, timeStamp, nonce, encrypt);
// System.out.println("发送给平台的签名是: " + signature[1].toString());
// 生成发送的xml
String result = XMLParse.generate(encrypt, signature, timeStamp, nonce);
return result;
}
/**
* 检验消息的真实性,并且获取解密后的明文.
*
* - 利用收到的密文生成安全签名,进行签名验证
* - 若验证通过,则提取xml中的加密消息
* - 对消息进行解密
*
*
* @param msgSignature 签名串,对应URL参数的msg_signature
* @param timeStamp 时间戳,对应URL参数的timestamp
* @param nonce 随机串,对应URL参数的nonce
* @param postData 密文,对应POST请求的数据
*
* @return 解密后的原文
* @throws AesException 执行失败,请查看该异常的错误码和具体的错误信息
*/
public String decryptMsg( String msgSignature, String timeStamp, String nonce,
String postData) throws AesException {
// 密钥,公众账号的app secret
// 提取密文
Object[] encrypt = XMLParse.extract(postData);
// 验证安全签名
String signature = SHA1.getSHA1(token, timeStamp, nonce, encrypt[1].toString());
// 和URL中的签名比较是否相等
// System.out.println("第三方收到URL中的签名:" + msg_sign);
// System.out.println("第三方校验签名:" + signature);
if (!signature.equals(msgSignature)) {
throw new AesException(AesException.ValidateSignatureError);
}
// 解密
String result = decrypt(encrypt[1].toString());
return result;
}
/**
* 验证URL
* @param msgSignature 签名串,对应URL参数的msg_signature
* @param timeStamp 时间戳,对应URL参数的timestamp
* @param nonce 随机串,对应URL参数的nonce
* @param echoStr 随机串,对应URL参数的echostr
*
* @return 解密之后的echostr
* @throws AesException 执行失败,请查看该异常的错误码和具体的错误信息
*/
public String verifyUrl(String msgSignature, String timeStamp, String nonce,
String echoStr) throws AesException {
String signature = SHA1.getSHA1(token, timeStamp, nonce, echoStr);
logger.info("signature:" + signature);
if (!signature.equals(msgSignature)) {
throw new AesException(AesException.ValidateSignatureError);
}
String result = decrypt(echoStr);
return result;
}
/**
* 验证URL
* @param msgSignature
* @param timeStamp
* @param nonce
* @return
* @throws AesException
*/
public boolean verifyUrl2( String msgSignature, String timeStamp,
String nonce) throws AesException {
String signature = SHA1.getSHA1(token, timeStamp, nonce);
logger.info("signature:" + signature);
if (!signature.equals(msgSignature)) {
throw new AesException(AesException.ValidateSignatureError);
}
return true;
}
}
WxUtil
public class WxUtil {
private static Logger logger = LoggerFactory
.getLogger(WxUtil.class);
//缓存access_token
private static final ConcurrentHashMap tokenCache = new ConcurrentHashMap();
private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final Random RANDOM = new SecureRandom();
/**
* 获取或更新access_token
* @param restTemplate
* @param appid
* @param appsecret
* @param type
*/
public static AccessToken getAccessToken( RestTemplate restTemplate, String appid,
String appsecret, int type) {
try {
AccessToken token = tokenCache.get(type);
if (token == null || token.isOutExpire()) {
String url = WxConstant.ACCESS_TOKEN_URL + "&appid=" + appid + "&secret="
+ appsecret;
String json = restTemplate.getForObject(url, String.class);
JSONObject jsonObject = JSON.parseObject(json);
if (jsonObject == null) {
logger.error("获取ACCESS_TOKEN失败");
}
String accessTokenObj = jsonObject.getString("access_token");
Integer expiresObj = jsonObject.getInteger("expires_in");
if (accessTokenObj == null) {
logger.error("获取ACCESS_TOKEN失败");
} else {
if (token == null)
token = new AccessToken();
token.update(accessTokenObj, expiresObj);
tokenCache.put(type, token);
}
}
return token;
} catch (Exception e) {
logger.error("获取ACCESS_TOKEN异常", e);
return null;
}
}
/**
* 发送POST请求
* @param restTemplate
* @param url 地址
* @param params 参数(json字符串)
* @return
*/
public static JSONObject postForJson( RestTemplate restTemplate, String url, String token,
String params) {
JSONObject result = null;
try {
url = url + "?access_token=" + token;
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.valueOf("application/json;UTF-8"));
HttpEntity request = new HttpEntity(params, headers);
result = restTemplate.postForObject(url, request, JSONObject.class);
return result;
} catch (Exception e) {
logger.error("POST:" + url + " 请求失败,请求参数:" + params, e);
}
return result;
}
/**
* 带ACCESS_TOKEN失效重试的POST请求
* @param restTemplate
* @param url
* @param token
* @param params
* @return
*/
public static JSONObject postForJsonRetry( RestTemplate restTemplate, String url, String token,
String params) {
JSONObject result = null;
try {
result = postForJson(restTemplate, url, token, params);
int retryTime = 2;//重试次数
boolean flag = result != null && result
.getInteger(WxConstant.ERR_CODE) != WxConstant.CARD_EVT_SUCCESS_CODE;
while (flag && retryTime > 0) {//强制刷新重试
token = WechatCache.getAccessToken(true);
if (token != null) {
result = postForJson(restTemplate, url, token, params);
}
retryTime--;
}
return result;
} catch (Exception e) {
logger.error("POST:" + url + " 请求失败,请求参数:" + params, e);
}
return result;
}
/**
* 上传永久素材图片
* 返回的图片只能在腾讯域下访问
* @param restTemplate
* @param url 图片地址
* @return
*/
public static String uploadImage(RestTemplate restTemplate, String token, String filePath) {
String result = null;
try {
File file = new File(filePath);
if (!file.exists()) {
logger.error("UPLOAD_IMG: 找不到对应文件:[" + filePath + "]");
return result;
}
WritableResource resource = new FileSystemResource(new File(filePath));
MultiValueMap data = new LinkedMultiValueMap();
data.add("buffer", resource);
result = restTemplate.postForObject(
WxConstant.UPLOAD_IMAGE_URL + "?access_token=" + token, data, String.class);
} catch (Exception e) {
logger.error("UPLOAD_IMG:" + filePath + " 上传失败", e);
}
return result;
}
/**
* 获取远程图片并上传至微信素材库
* @param restTemplate
* @param url
* @param remoteUrl
* @return
*/
public static String uploadImageByUrl( RestTemplate restTemplate, String token,
String remoteUrl) {
String result = null;
try {
URL httpUrl = new URL(remoteUrl);
UrlResource resource = new UrlResource(httpUrl);
MultiValueMap data = new LinkedMultiValueMap();
data.add("media", resource);
result = restTemplate.postForObject(
WxConstant.UPLOAD_IMAGE_URL + "?access_token=" + token, data, String.class);
if (result != null) {
JSONObject json = JSONObject.parseObject(result);
if (json != null && json.containsKey("url"))
result = json.getString("url").replaceAll("\\\\", "");
}
} catch (Exception e) {
logger.error("UPLOAD_IMG BY URL:" + remoteUrl + " 上传失败", e);
}
return result;
}
/**
* 本地上传永久素材(包括图片/视频等)
* 返回的图片可以在任何域下访问
* @param restTemplate
* @param url
* @param type
* @param filePath
* @return
*/
public static String uploadMetrail( RestTemplate restTemplate, String token, String type,
String filePath) {
String result = null;
try {
File file = new File(filePath);
if (!file.exists()) {
logger.error("UPLOAD: 找不到对应文件:[" + filePath + "]");
return result;
}
WritableResource resource = new FileSystemResource(new File(filePath));
MultiValueMap data = new LinkedMultiValueMap();
data.add("media", resource);
result = restTemplate.postForObject(
WxConstant.UPLOAD_METRAIL_URL + "?access_token=" + token + "&type=" + type, data,
String.class);
//{"media_id":"5Itlgj8Y69Jbj3HU5hFOTVgc78s4VehAfZ-eUbeeTvk","url":"http:\/\/mmbiz.qpic.cn\/mmbiz_png\/8JBS1XicUAVm3805895ic0gyibLtjpDjsI0GmoCGHHUFVeTVqRichTibBibA4sAZibsLuH3QZkdMicCnrTY2XXVFDQBHMg\/0?wx_fmt=png","item":[]}
if (result != null) {
JSONObject json = JSONObject.parseObject(result);
if (json != null && json.containsKey("url"))
result = json.getString("url").replaceAll("\\\\", "");
}
} catch (Exception e) {
logger.error("UPLOAD:" + filePath + " 上传失败", e);
}
return result;
}
/**
* 获取远程资源并上传至微信素材库
* @param restTemplate
* @param url
* @param type
* @param remoteUrl
* @return
*/
public static JSONObject uploadMetrailByUrl(RestTemplate restTemplate, String token,
String type, String remoteUrl) {
JSONObject result = null;
try {
URL httpUrl = new URL(remoteUrl);
UrlResource resource = new UrlResource(httpUrl);
MultiValueMap data = new LinkedMultiValueMap();
data.add("media", resource);
String res = restTemplate.postForObject(
WxConstant.UPLOAD_METRAIL_URL + "?access_token=" + token + "&type=" + type, data,
String.class);
//{"media_id":"5Itlgj8Y69Jbj3HU5hFOTVgc78s4VehAfZ-eUbeeTvk","url":"http:\/\/mmbiz.qpic.cn\/mmbiz_png\/8JBS1XicUAVm3805895ic0gyibLtjpDjsI0GmoCGHHUFVeTVqRichTibBibA4sAZibsLuH3QZkdMicCnrTY2XXVFDQBHMg\/0?wx_fmt=png","item":[]}
if (res != null) {
result = JSONObject.parseObject(res);
if (result != null && result.containsKey("url"))
result.put("url", result.getString("url").replaceAll("\\\\", ""));
}
} catch (Exception e) {
logger.error("UPLOAD BY URL:" + remoteUrl + " 上传失败", e);
}
return result;
}
/**
* GET请求
* @param restTemplate
* @param url
* @return
*/
public static JSONObject getForJson(RestTemplate restTemplate, String url, String token) {
JSONObject result = null;
try {
url = url + "?access_token=" + token;
String res = restTemplate.getForObject(url, String.class);
if (StringUtils.isNotBlank(res)) {
return JSONObject.parseObject(res);
}
logger.info("GET 请求结果:" + result);
return result;
} catch (Exception e) {
logger.error("GET:" + url + " 请求失败", e);
}
return result;
}
/**
* 获取二维码ticket(base64)
* @param restTemplate
* @param url
* @return
*/
public static String getQtCodeTicket(RestTemplate restTemplate, String ticket) {
String result = null;
String url = null;
try {
url = WxConstant.GET_QCODE_TICKET + "?ticket=" + URLEncoder.encode(ticket, "UTF-8");
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add("Content-Type", "image/jpg");
HttpEntity requestEntity = new HttpEntity(null, requestHeaders);
ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET,
requestEntity, byte[].class);
byte[] imgsrc = response.getBody();
result = WxConstant.IMG_BASE64_PREFIX + Base64.getEncoder().encodeToString(imgsrc);
} catch (Exception e) {
logger.error("GET:" + url + " 请求失败", e);
}
return result;
}
/**
* XML格式字符串转换为Map
*
* @param strXML XML字符串
* @return XML数据转换后的Map
* @throws Exception
*/
public static Map xmlToMap(String strXML) throws Exception {
try {
Map data = new HashMap();
DocumentBuilder documentBuilder = WxXmlUtil.newDocumentBuilder();
InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
org.w3c.dom.Document doc = documentBuilder.parse(stream);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getDocumentElement().getChildNodes();
for (int idx = 0; idx < nodeList.getLength(); ++idx) {
Node node = nodeList.item(idx);
if (node.getNodeType() == Node.ELEMENT_NODE) {
org.w3c.dom.Element element = (org.w3c.dom.Element) node;
data.put(element.getNodeName(), element.getTextContent());
}
}
try {
stream.close();
} catch (Exception ex) {
// do nothing
}
return data;
} catch (Exception ex) {
logger.warn("Invalid XML, can not convert to map. Error message: {}. XML content: {}",
ex);
throw ex;
}
}
/**
* XML格式字符串转换为Map
* 将key首字母转小写
* @param strXML XML字符串
* @return XML数据转换后的Map
* @throws Exception
*/
public static Map xmlToMapWithLowerStart(String strXML) throws Exception {
try {
Map data = new HashMap();
DocumentBuilder documentBuilder = WxXmlUtil.newDocumentBuilder();
InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
org.w3c.dom.Document doc = documentBuilder.parse(stream);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getDocumentElement().getChildNodes();
for (int idx = 0; idx < nodeList.getLength(); ++idx) {
Node node = nodeList.item(idx);
if (node.getNodeType() == Node.ELEMENT_NODE) {
org.w3c.dom.Element element = (org.w3c.dom.Element) node;
String nodeName = element.getNodeName();
nodeName = nodeName.replace(String.valueOf(nodeName.charAt(0)),
String.valueOf(nodeName.charAt(0)).toLowerCase());
data.put(nodeName, element.getTextContent());
}
}
try {
stream.close();
} catch (Exception ex) {
// do nothing
}
return data;
} catch (Exception ex) {
logger.warn("Invalid XML, can not convert to map. Error message: {}. XML content: {}",
ex);
throw ex;
}
}
/**
* 将Map转换为XML格式的字符串
*
* @param data Map类型数据
* @return XML格式的字符串
* @throws Exception
*/
public static String mapToXml(Map data) throws Exception {
org.w3c.dom.Document document = WxXmlUtil.newDocument();
org.w3c.dom.Element root = document.createElement("xml");
document.appendChild(root);
for (String key : data.keySet()) {
String value = data.get(key);
if (value == null) {
value = "";
}
value = value.trim();
org.w3c.dom.Element filed = document.createElement(key);
filed.appendChild(document.createTextNode(value));
root.appendChild(filed);
}
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(document);
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
String output = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
try {
writer.close();
} catch (Exception ex) {
}
return output;
}
/**
* 生成带有 sign 的 XML 格式字符串
*
* @param data Map类型数据
* @param key API密钥
* @return 含有sign字段的XML
*/
public static String generateSignedXml( final Map data,
String key) throws Exception {
return generateSignedXml(data, key, SignType.MD5);
}
/**
* 生成带有 sign 的 XML 格式字符串
*
* @param data Map类型数据
* @param key API密钥
* @param signType 签名类型
* @return 含有sign字段的XML
*/
public static String generateSignedXml( final Map data, String key,
SignType signType) throws Exception {
String sign = generateSignature(data, key, signType);
data.put(WxConstant.FIELD_SIGN, sign);
return mapToXml(data);
}
/**
* 判断签名是否正确
*
* @param xmlStr XML格式数据
* @param key API密钥
* @return 签名是否正确
* @throws Exception
*/
public static boolean isSignatureValid(String xmlStr, String key) throws Exception {
Map data = xmlToMap(xmlStr);
if (!data.containsKey(WxConstant.FIELD_SIGN)) {
return false;
}
String sign = data.get(WxConstant.FIELD_SIGN);
return generateSignature(data, key).equals(sign);
}
/**
* 判断签名是否正确,必须包含sign字段,否则返回false。使用MD5签名。
*
* @param data Map类型数据
* @param key API密钥
* @return 签名是否正确
* @throws Exception
*/
public static boolean isSignatureValid(Map data, String key) throws Exception {
return isSignatureValid(data, key, SignType.MD5);
}
/**
* 判断签名是否正确,必须包含sign字段,否则返回false。
*
* @param data Map类型数据
* @param key API密钥
* @param signType 签名方式
* @return 签名是否正确
* @throws Exception
*/
public static boolean isSignatureValid( Map data, String key,
SignType signType) throws Exception {
if (!data.containsKey(WxConstant.FIELD_SIGN)) {
return false;
}
String sign = data.get(WxConstant.FIELD_SIGN);
return generateSignature(data, key, signType).equals(sign);
}
/**
* 生成签名
*
* @param data 待签名数据
* @param key API密钥
* @return 签名
*/
public static String generateSignature( final Map data,
String key) throws Exception {
return generateSignature(data, key, SignType.MD5);
}
/**
* 生成签名. 注意,若含有sign_type字段,必须和signType参数保持一致。
*
* @param data 待签名数据
* @param key API密钥
* @param signType 签名方式
* @return 签名
*/
public static String generateSignature( final Map data, String key,
SignType signType) throws Exception {
Set keySet = data.keySet();
String[] keyArray = keySet.toArray(new String[keySet.size()]);
Arrays.sort(keyArray);
StringBuilder sb = new StringBuilder();
for (String k : keyArray) {
if (k.equals(WxConstant.FIELD_SIGN)) {
continue;
}
if (data.get(k).trim().length() > 0) // 参数值为空,则不参与签名
sb.append(k).append("=").append(data.get(k).trim()).append("&");
}
sb.append("key=").append(key);
if (SignType.MD5.equals(signType)) {
return MD5(sb.toString()).toUpperCase();
} else if (SignType.HMACSHA256.equals(signType)) {
return HMACSHA256(sb.toString(), key);
} else {
throw new Exception(String.format("Invalid sign_type: %s", signType));
}
}
/**
* 获取随机字符串 Nonce Str
*
* @return String 随机字符串
*/
public static String generateNonceStr() {
char[] nonceChars = new char[43];
for (int index = 0; index < nonceChars.length; ++index) {
nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
}
return new String(nonceChars);
}
/**
* 生成 MD5
*
* @param data 待处理数据
* @return MD5结果
*/
public static String MD5(String data) throws Exception {
java.security.MessageDigest md = MessageDigest.getInstance("MD5");
byte[] array = md.digest(data.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder();
for (byte item : array) {
sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
}
return sb.toString().toUpperCase();
}
/**
* 生成 HMACSHA256
* @param data 待处理数据
* @param key 密钥
* @return 加密结果
* @throws Exception
*/
public static String HMACSHA256(String data, String key) throws Exception {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
sha256_HMAC.init(secret_key);
byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder();
for (byte item : array) {
sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
}
return sb.toString().toUpperCase();
}
/**
* 获取客户端真实ip
* @param request
* @return
*/
public static String getIpAddress(HttpServletRequest request) {
// 避免反向代理不能获取真实地址, 取X-Forwarded-For中第一个非unknown的有效IP字符串
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
/**
* 查询微信卡券详情信息
* @param restTemplate
* @param cardId
* @return
*/
public static JSONObject queryWxCardInfo( RestTemplate restTemplate, String cardId,
String token) {
JSONObject wxCard = null;
try {
JSONObject params = new JSONObject();
params.put("card_id", cardId);
JSONObject jsonObj = WxUtil.postForJsonRetry(restTemplate,
WxConstant.QUERY_CARDINFO_URL, token, params.toString());
if (jsonObj == null
|| jsonObj.getInteger(WxConstant.ERR_CODE) != WxConstant.CARD_EVT_SUCCESS_CODE) {
logger.error("查询卡券详情失败,调用微信查询接口失败 result:[" + jsonObj + "]");
return wxCard;
}
wxCard = jsonObj.getJSONObject(WxConstant.WX_FEILD_CARD);
} catch (Exception e) {
logger.error("查询卡券详情异常", e);
}
return wxCard;
}
/**
* 解析封装会员信息
* @param memberInfo
* @return
*/
public static WxCardMemberInfo parseMemberInfo(JSONObject memberInfo) {
WxCardMemberInfo cardMemberInfo = new WxCardMemberInfo();
try {
if (memberInfo != null) {
cardMemberInfo.setOpenid(memberInfo.getString("openid"));
cardMemberInfo.setMembershipNumber(memberInfo.getLong("membership_number"));
cardMemberInfo.setBonus(memberInfo.getInteger("bonus"));
cardMemberInfo.setSex(memberInfo.getString("sex"));
cardMemberInfo.setUserCardStatus(memberInfo.getString("user_card_status"));
JSONObject userInfo = memberInfo.getJSONObject("user_info");
if (userInfo != null) {
JSONArray arr = userInfo.getJSONArray("common_field_list");
if (arr != null) {
for (int i = 0; i < arr.size(); i++) {
JSONObject obj = arr.getJSONObject(i);
if (WxCardActivateInfo.USER_FORM_INFO_FLAG_MOBILE
.equals(obj.getString("name"))) {
cardMemberInfo.setMobile(obj.getString("value"));
} else if (WxCardActivateInfo.USER_FORM_INFO_FLAG_NAME
.equals(obj.getString("name"))) {
cardMemberInfo.setName(obj.getString("value"));
}
}
}
}
}
} catch (Exception e) {
logger.error("解析封装会员信息异常", e);
}
return cardMemberInfo;
}
/**
* 微信上传图片素材接口
* @param imageUrl
* @param msgType
* @return
*/
public static net.sf.json.JSONObject uploadMaterialImage(String imageUrl, String msgType){
File file = FileUtils.urlToFile(imageUrl);
try {
//上传素材
//HPb4PQugmc1j0Dxhf7_9U4c3MhGHzvkJGhi7Yi6GZ2s
String materialUrl = WechatConstants.MATERIAL_URL.replace("ACCESS_TOKEN", WechatCache.getAccessToken(false)).replace("TYPE", msgType);
String result = connectHttpsByPost(materialUrl, file);
result = result.replaceAll("[\\\\]", "");
net.sf.json.JSONObject resultJSON = net.sf.json.JSONObject.fromObject(result);
if (resultJSON != null) {
if (resultJSON.get("media_id") != null) {
logger.info(resultJSON.get("media_id").toString());
logger.info("上传" + msgType + "永久素材成功");
return resultJSON;
} else {
logger.info("上传" + msgType + "永久素材失败");
}
}
} catch (Exception e) {
logger.info("程序异常---" + e);
} finally {
logger.info("结束上传" + msgType + "永久素材---------------------");
if(file.exists()){
file.delete();
}
}
return new net.sf.json.JSONObject();
}
public static String connectHttpsByPost(String path, File file) throws IOException {
URL url = new URL(path);
HttpURLConnection con = (HttpURLConnection) (url.openConnection());
String result = null;
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false); // post方式不能使用缓存
// 设置请求头信息
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
// 设置边界
String BOUNDARY = "----------" + System.currentTimeMillis();
con.setRequestProperty("Content-Type",
"multipart/form-data; boundary="
+ BOUNDARY);
// 请求正文信息
// 第一部分:
StringBuilder sb = new StringBuilder();
sb.append("--"); // 必须多两道线
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"media\";filelength=\"" + file.length() + "\";filename=\""
+ file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head = sb.toString().getBytes("utf-8");
// 获得输出流
OutputStream out = new DataOutputStream(con.getOutputStream());
// 输出表头
out.write(head);
// 文件正文部分
// 把文件已流文件的方式 推入到url中
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
// 结尾部分
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
out.write(foot);
out.flush();
out.close();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = null;
try {
// 定义BufferedReader输入流来读取URL的响应
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
if (result == null) {
result = buffer.toString();
}
} catch (IOException e) {
logger.error("发送POST请求出现异常!" + e);
e.printStackTrace();
throw new IOException("数据读取异常");
} finally {
if (reader != null) {
reader.close();
}
}
return result;
}
/**
* 文本消息对象转换成xml
* @param textMessage 文本消息对象
* @return xml
*/
public static String textMessageToXml(TextMessage textMessage){
XStream xstream = new XStream();
xstream.alias("xml", textMessage.getClass());
return xstream.toXML(textMessage);
}
}