Browse Source

更新了WxGzhUtil

master
wei 6 years ago
parent
commit
b35097adc7
  1. 14
      src/main/java/com/ccsens/opensource/wxconfigurer/bean/po/WxAccessToken.java
  2. 12
      src/main/java/com/ccsens/opensource/wxconfigurer/bean/po/WxBaseEntity.java
  3. 6
      src/main/java/com/ccsens/opensource/wxconfigurer/bean/po/WxGzhMenu.java
  4. 26
      src/main/java/com/ccsens/opensource/wxconfigurer/bean/po/WxOauth2AccessToken.java
  5. 42
      src/main/java/com/ccsens/opensource/wxconfigurer/bean/po/WxOauth2UserInfo.java
  6. 2
      src/main/java/com/ccsens/opensource/wxconfigurer/exception/WxException.java
  7. 132
      src/main/java/com/ccsens/opensource/wxconfigurer/util/WxGzhUtil.java
  8. 79
      src/main/java/com/ccsens/opensource/wxconfigurer/util/WxXcxUtil.java

14
src/main/java/com/ccsens/opensource/wxconfigurer/bean/po/WxAccessToken.java

@ -1,15 +1,19 @@
package com.ccsens.opensource.wxconfigurer.bean.po;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import lombok.Data;
/**
* @author __zHangSan
*/
@Data
public class WxAccessToken {
private String access_token;
private Long expires_in;
private Integer errcode;
private String errmsg;
public class WxAccessToken extends WxBaseEntity{
@JsonProperty("access_token")
private String accessToken;
@JsonProperty("expires_in")
private Long expiresIn;
@JsonIgnore
private Long createdAt;
}

12
src/main/java/com/ccsens/opensource/wxconfigurer/bean/po/WxBaseEntity.java

@ -0,0 +1,12 @@
package com.ccsens.opensource.wxconfigurer.bean.po;
import lombok.Data;
/**
* @author __zHangSan
*/
@Data
public class WxBaseEntity {
private Integer errcode;
private String errmsg;
}

6
src/main/java/com/ccsens/opensource/wxconfigurer/bean/po/WxGzhMenu.java

@ -68,7 +68,8 @@ public class WxGzhMenu {
/**
* media_id类型和view_limited类型必须
*/
private String media_id;
@JsonProperty("media_id")
private String mediaId;
/**
* miniprogram类型必须
*/
@ -77,7 +78,8 @@ public class WxGzhMenu {
/**
* optional
*/
private List<Button> sub_button;
@JsonProperty("sub_button")
private List<Button> subButton;
}
@JsonProperty("button")
private List<Button> buttons;

26
src/main/java/com/ccsens/opensource/wxconfigurer/bean/po/WxOauth2AccessToken.java

@ -0,0 +1,26 @@
package com.ccsens.opensource.wxconfigurer.bean.po;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
/**
* @author __zHangSan
*/
@Data
public class WxOauth2AccessToken extends WxBaseEntity{
@JsonProperty("access_token")
private String accessToken;
@JsonProperty("expires_in")
private int expiresIn;
@JsonProperty("refresh_token")
private String refreshToken;
@JsonProperty("openid")
private String openId;
@JsonProperty("scope")
private String scope;
@JsonProperty("unionid")
private String unionId;
@JsonIgnore
private Long createdAt;
}

42
src/main/java/com/ccsens/opensource/wxconfigurer/bean/po/WxOauth2UserInfo.java

@ -0,0 +1,42 @@
package com.ccsens.opensource.wxconfigurer.bean.po;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import java.util.List;
/**
* @author __zHangSan
*/
@Data
public class WxOauth2UserInfo extends WxBaseEntity{
@JsonProperty("openid")
private String openId;
@JsonProperty("nickname")
private String nickname;
@JsonProperty("sex")
private int sex;
@JsonProperty("province")
private String province;
@JsonProperty("city")
private String city;
@JsonProperty("country")
private String country;
@JsonProperty("headimgurl")
private String headImgUrl;
@JsonProperty("privilege")
private List<String> privilegeList;
@JsonProperty("unionid")
private String unionId;
@JsonProperty("language")
private String language;
}

2
src/main/java/com/ccsens/opensource/wxconfigurer/exception/WxException.java

@ -10,7 +10,7 @@ import lombok.Setter;
*/
@Data
public class WxException extends BaseException{
private String type = "BusinessError";
private String type = "WxError";
public WxException(){

132
src/main/java/com/ccsens/opensource/wxconfigurer/util/WxGzhUtil.java

@ -4,9 +4,8 @@ import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import com.ccsens.opensource.wxconfigurer.bean.po.WxGzhAuthType;
import com.ccsens.opensource.wxconfigurer.bean.po.WxGzhMenu;
import com.ccsens.opensource.wxconfigurer.bean.po.WxAccessToken;
import cn.hutool.http.HttpUtil;
import com.ccsens.opensource.wxconfigurer.bean.po.*;
import com.ccsens.opensource.wxconfigurer.exception.BaseException;
import com.ccsens.opensource.wxconfigurer.exception.BusinessException;
import com.ccsens.opensource.wxconfigurer.exception.WxException;
@ -54,9 +53,12 @@ public class WxGzhUtil {
= " https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%1$s";
private static final String URL_QUERY_MENU
= "https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info?access_token=%1$s";
private static final String GZH_AUTH_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%1$s&redirect_uri=%2$s&response_type=code&scope=%3$s&state=STATE#wechat_redirect";
private static final String GZH_AUTH_URL
= "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%1$s&redirect_uri=%2$s&response_type=code&scope=%3$s&state=STATE#wechat_redirect";
private static final String URL_GET_OAUTH2_ACCESS_TOKEN
= "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%1$s&secret=%2$s&code=%3$s&grant_type=authorization_code";
private static final String URL_GET_OAUTH2_USERINFO
= "https://api.weixin.qq.com/sns/userinfo?access_token=%1$s&openid=%2$s";
private static final String APPID = "wx7af1bf1e14facf82";
private static final String SECRET = "a6613fae11b497639c0224b820aaf6d9";
private static final String TOKEN = "nNzkL9KkZUOIS8uU";
@ -66,21 +68,19 @@ public class WxGzhUtil {
/**
* 数组转字符串
* @param arr
* @return
*/
private static String ArrayToString(String[] arr) {
StringBuffer bf = new StringBuffer();
for (int i = 0; i < arr.length; i++) {
bf.append(arr[i]);
private static String arrayToString(String[] arr) {
StringBuilder bf = new StringBuilder();
for (String s : arr) {
bf.append(s);
}
return bf.toString();
}
/**
* sha1加密
* sha1加密
*/
private static String SHA1Encode(String sourceString) {
private static String sha1Encode(String sourceString) {
String resultString = null;
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
@ -91,24 +91,27 @@ public class WxGzhUtil {
return resultString;
}
private static final String byte2hexString(byte[] bytes) {
StringBuffer buf = new StringBuffer(bytes.length * 2);
for (int i = 0; i < bytes.length; i++) {
if (((int) bytes[i] & 0xff) < 0x10) {
/**
* 字节数组转字符串
*/
private static String byte2hexString(byte[] bytes) {
StringBuilder buf = new StringBuilder(bytes.length * 2);
for (byte aByte : bytes) {
if (((int) aByte & 0xff) < 0x10) {
buf.append("0");
}
buf.append(Long.toString((int) bytes[i] & 0xff, 16));
buf.append(Long.toString((int) aByte & 0xff, 16));
}
return buf.toString().toUpperCase();
}
/**
* 公众号接入验证
* @param signature
* @param timestamp
* @param nonce
* @param echostr
* @return
* @param signature signature
* @param timestamp timestamp
* @param nonce nonce
* @param echostr echostr
* @return true or false
*/
public static boolean checkSignature(String signature,String timestamp,String nonce,String echostr){
if(StrUtil.isEmpty(signature) || StrUtil.isEmpty(timestamp) || StrUtil.isEmpty(nonce) || StrUtil.isEmpty(echostr)){
@ -116,7 +119,7 @@ public class WxGzhUtil {
}
String[] tmpArr = { TOKEN, timestamp, nonce };
Arrays.sort(tmpArr);
String sign = SHA1Encode( ArrayToString(tmpArr));
String sign = sha1Encode( arrayToString(tmpArr));
Console.log("sign:{} , signature: {}",sign,signature);
if (sign.equalsIgnoreCase(signature)) {
return true;
@ -126,12 +129,10 @@ public class WxGzhUtil {
/**
* 获取Access_token
* @return
* @throws BaseException
*/
public static String getAccessToken() throws BaseException {
if(globalWxAccessToken == null ||
globalWxAccessToken.getCreatedAt() + globalWxAccessToken.getExpires_in()
globalWxAccessToken.getCreatedAt() + globalWxAccessToken.getExpiresIn()
>= DateUtil.currentSeconds() - ACCESS_TOKEN_RESERVED_SECONDS){
WxAccessToken wxAccessToken = null;
String url = String.format(URL_GET_ACCESS_TOKEN,"client_credential",APPID,SECRET);
@ -148,18 +149,17 @@ public class WxGzhUtil {
if(null != wxAccessToken.getErrcode()){
throw new WxException(wxAccessToken.getErrcode(),wxAccessToken.getErrmsg());
}
if (StrUtil.isEmpty(wxAccessToken.getAccess_token())) {
if (StrUtil.isEmpty(wxAccessToken.getAccessToken())) {
throw new BusinessException(-1,"can't find the access_token attribute.");
}
globalWxAccessToken = wxAccessToken;
globalWxAccessToken.setCreatedAt(DateUtil.currentSeconds());
}
return globalWxAccessToken.getAccess_token();
return globalWxAccessToken.getAccessToken();
}
/**
* 查询微信公众号底部菜单
* @throws BaseException
*/
public static String queryMenu() throws BaseException {
String url = String.format(URL_QUERY_MENU,getAccessToken());
@ -170,8 +170,6 @@ public class WxGzhUtil {
/**
* 创建微信公众号底部菜单
* @param gzhMenu
* @throws Exception
*/
public static void createMenu(WxGzhMenu gzhMenu) throws BaseException {
String url = String.format(URL_CREATE_MENU,getAccessToken());
@ -203,4 +201,72 @@ public class WxGzhUtil {
public static String getAuthedUrl(String url, WxGzhAuthType wxGzhAuthType){
return String.format(GZH_AUTH_URL,APPID, URLUtil.encode(url),wxGzhAuthType.getText());
}
/**
* 获取网页授权凭证
* @param code OAuth2授权码
* @return WxOauth2AccessToken
*/
public static WxOauth2AccessToken getOauth2AccessToken(String code) throws BaseException {
WxOauth2AccessToken wxOauth2AccessToken = null;
String url = String.format(URL_GET_OAUTH2_ACCESS_TOKEN,APPID,SECRET,code);
String response = HttpRequest.get(url).execute().body();
Console.log("url: {}\nresponse: {}",url,response);
try {
if(StrUtil.isEmpty(response) || null == (wxOauth2AccessToken = JacksonUtil.jsonToBean(response,WxOauth2AccessToken.class))) {
throw new BusinessException(-1,"the response of HttpRequest is empty.");
}
} catch (IOException e) {
throw new BusinessException(-1,e.getMessage());
}
if(null != wxOauth2AccessToken.getErrcode()){
throw new WxException(wxOauth2AccessToken.getErrcode(),wxOauth2AccessToken.getErrmsg());
}
if (StrUtil.isEmpty(wxOauth2AccessToken.getAccessToken())) {
throw new BusinessException(-1,"can't find the access_token attribute.");
}
wxOauth2AccessToken.setCreatedAt(DateUtil.currentSeconds());
return wxOauth2AccessToken;
}
/**
* 通过网页授权获取用户信息
*
* @param accessToken 网页授权接口调用凭证
* @param openId 用户标识
* @return SNSUserInfo
*/
public static WxOauth2UserInfo getOauth2UserInfo(String accessToken, String openId) throws BaseException {
WxOauth2UserInfo wxOauth2UserInfo = null;
String url = String.format(URL_GET_OAUTH2_USERINFO,accessToken,openId);
String response = HttpRequest.get(url).execute().body();
Console.log("url: {}\nresponse: {}",url,response);
try {
if(StrUtil.isEmpty(response) || null == (wxOauth2UserInfo = JacksonUtil.jsonToBean(response,WxOauth2UserInfo.class))) {
throw new BusinessException(-1,"the response of HttpRequest is empty.");
}
} catch (IOException e) {
throw new BusinessException(-1,e.getMessage());
}
if(null != wxOauth2UserInfo.getErrcode()){
throw new WxException(wxOauth2UserInfo.getErrcode(),wxOauth2UserInfo.getErrmsg());
}
if (StrUtil.isEmpty(wxOauth2UserInfo.getOpenId())) {
throw new BusinessException(-1,"can't find the openid attribute.");
}
return wxOauth2UserInfo;
}
/**
* 通过网页授权code拉取用户信息封装了getOauth2AccessToken和getOauth2UserInfo(accessToken,openId)
* @param code 网页授权码
* @return WxOauth2UserInfo
* @throws BaseException 异常
*/
public static WxOauth2UserInfo getOauth2UserInfo(String code) throws BaseException {
WxOauth2AccessToken wxOauth2AccessToken = getOauth2AccessToken(code);
return getOauth2UserInfo(wxOauth2AccessToken.getAccessToken(),wxOauth2AccessToken.getOpenId());
}
}

79
src/main/java/com/ccsens/opensource/wxconfigurer/util/WechatUtil.java → src/main/java/com/ccsens/opensource/wxconfigurer/util/WxXcxUtil.java

@ -2,10 +2,15 @@ package com.ccsens.opensource.wxconfigurer.util;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.ccsens.opensource.wxconfigurer.bean.po.WxOauth2UserInfo;
import com.ccsens.opensource.wxconfigurer.exception.BusinessException;
import com.ccsens.opensource.wxconfigurer.exception.WxException;
import lombok.Data;
import org.apache.commons.codec.digest.DigestUtils;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.util.*;
@ -33,7 +38,10 @@ class PayException extends RuntimeException{
}
}
public class WechatUtil {
/**
* @author __zHangSan
*/
public class WxXcxUtil {
/**
* 被Jasckson使用的内部类 必须是static的
@ -42,7 +50,7 @@ public class WechatUtil {
public String openid;
public String session_key;
public String unionid;
public String errcode;
public Integer errcode;
public String errmsg;
}
@ -140,22 +148,20 @@ public class WechatUtil {
* @throws Exception
*/
public static WechatUser getUserInfo(String code) throws Exception {
String response = null;
WechatUser wechatUser = null;
String url_login = String.format(URL_LOGIN, appid, secret, code, "authorization_code");
String url = String.format(URL_LOGIN, appid, secret, code, "authorization_code");
String response = HttpRequest.get(url).execute().body();
try {
response = HttpsUtil.httpsRequest(url_login, "GET", null);
wechatUser = JacksonUtil.jsonToBean(response, WechatUser.class);
}catch (Exception e){
throw new GetUserInfoException(-1,e.getMessage());
if(StrUtil.isEmpty(response) || null == (wechatUser = JacksonUtil.jsonToBean(response, WechatUser.class))) {
throw new BusinessException(-1,"the response of HttpRequest is empty.");
}
} catch (IOException e) {
throw new BusinessException(-1,e.getMessage());
}
if(wechatUser == null)
throw new GetUserInfoException(-1,"Get UserInfoByCode failed.");
if(!StrUtil.isEmpty(wechatUser.errcode))
throw new GetUserInfoException(Integer.valueOf(wechatUser.errcode),wechatUser.errmsg);
if(null != wechatUser.errcode){
throw new WxException(wechatUser.errcode, wechatUser.errmsg);
}
return wechatUser;
}
@ -189,8 +195,9 @@ public class WechatUtil {
preparePayBean.openid = openid;
preparePayBean.total_fee = total_fee;
preparePayBean.out_trade_no = out_trade_no;
preparePayBean.body = new String(body.getBytes("ISO-8859-1"),"UTF-8");//以utf-8编码放入paymentPo,微信支付要求字符编码统一采用UTF-8字符编码
//preparePayBean.body = new String("聊天密码小程序-充值");
//以utf-8编码放入paymentPo,微信支付要求字符编码统一采用UTF-8字符编码
preparePayBean.body = new String(body.getBytes("ISO-8859-1"),"UTF-8");
//preparePayBean.body = new String("小程序-充值");
preparePayBean.spbill_create_ip = spbill_create_ip;
preparePayBean.notify_url = notify_url;
preparePayBean.trade_type = "JSAPI";
@ -224,9 +231,9 @@ public class WechatUtil {
PreparePayReSignBean reSignBean = new PreparePayReSignBean();
resultBean = JacksonUtil.xmlToBean(new ByteArrayInputStream(respXml.getBytes()),PreparePayResultBean.class);
if(ObjectUtil.isNull(resultBean))
if(ObjectUtil.isNull(resultBean)) {
throw new PayException("PreparePay 返回的resultBean为空");
}
if(!StrUtil.isEmpty(resultBean.return_code)
&& !StrUtil.isEmpty(resultBean.result_code)){
if(resultBean.result_code.equals("SUCCESS") && resultBean.return_code.equals(resultBean.result_code)){
@ -250,9 +257,9 @@ public class WechatUtil {
throw new PayException("[" + resultBean.err_code + "]"
+ resultBean.err_code_des);
}
}else
}else {
throw new PayException(resultBean.return_msg);
//return null;
}
}
/**
@ -277,12 +284,14 @@ public class WechatUtil {
*/
private static Map paraFilter(Map<String,Object> sArray) {
Map result = new HashMap();
if (sArray == null || sArray.size() <= 0)
if (sArray == null || sArray.size() <= 0) {
return result;
}
for (String key : sArray.keySet()) {
String value = "" + sArray.get(key);
if (StrUtil.isEmpty(value) || key.equalsIgnoreCase("sign") || key.equalsIgnoreCase("sign_type"))
if (StrUtil.isEmpty(value) || key.equalsIgnoreCase("sign") || key.equalsIgnoreCase("sign_type")) {
continue;
}
result.put(key, value);
}
return result;
@ -294,19 +303,19 @@ public class WechatUtil {
* @return 拼接后字符串
*/
private static String createLinkString(Map<String,String> params) {
List<String> keys = new ArrayList(params.keySet());
List<String> keys = new ArrayList<String>(params.keySet());
Collections.sort(keys);
String prestr = "";
StringBuilder prestr = new StringBuilder();
for (int i = 0; i < keys.size(); i++) {
String key = keys.get(i);
String value = params.get(key);
if (i == keys.size() - 1) {// 拼接时,不包括最后一个&字符
prestr = prestr + key + "=" + value;
if (i == keys.size() - 1) {
prestr.append(key).append("=").append(value);
} else {
prestr = prestr + key + "=" + value + "&";
prestr.append(key).append("=").append(value).append("&");
}
}
return prestr;
return prestr.toString();
}
/**
@ -322,11 +331,7 @@ public class WechatUtil {
}
/**
* @param content
* @param charset
* @return
* @throws
* @throws UnsupportedEncodingException
* getContentBytes
*/
private static byte[] getContentBytes(String content, String charset) {
if (charset == null || "".equals(charset)) {
@ -346,6 +351,7 @@ public class WechatUtil {
public static Map<String,Object> payToUsrWx(
String partner_trade_no,String openid,int total_fee,String desc,String spbill_create_ip)
throws Exception{
final String SUCCESS = "SUCCESS";
//1.构造请求字符串
Map<String,Object> reqMap = new HashMap<>();
reqMap.put("mch_appid",appid);
@ -378,14 +384,15 @@ public class WechatUtil {
result_code = (String)respMap.get("result_code");
if(!StrUtil.isEmpty(return_code) && !StrUtil.isEmpty(result_code)){
if(return_code.equals("SUCCESS") && return_code.equals(result_code)){
if(return_code.equals(SUCCESS) && return_code.equals(result_code)){
return respMap;
}else{
throw new PayException("[" + respMap.get("err_code") + "]"
+ respMap.get("err_code_des"));
}
}else
throw new PayException((String)respMap.get("return_msg"));
}else {
throw new PayException((String) respMap.get("return_msg"));
}
//return null;
}
Loading…
Cancel
Save