微信小程序/公众号获取手机号、OpenId等的工具类
注:微信公众号无法获取用户绑定的手机号,只能通过小程序来获取。部分接口小程序和公众号调用的是同一个。
·
注:微信公众号无法获取用户绑定的手机号,只能通过小程序来获取。部分接口小程序和公众号调用的是同一个。
请求地址常量
public class WxUrlConstant {
//获取access_token
public static final String GETACCESSTOKENURL = "https://api.weixin.qq.com/cgi-bin/token";
//获取jsapi_ticket
public static final String GETJSAPITICKET = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
//获取openid
public static final String GETOPINIDURL = "https://api.weixin.qq.com/sns/oauth2/access_token";
//获取用户绑定的手机号
public static final String GETPHONENUMBERURL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber";
}
微信接口工具类
/**
* 微信部分功能工具类
*/
@Slf4j
public class WxUtil {
/**
* 获取 access_token 公众号的全局唯一接口调用凭证 有效期两小时
*
* @return
*/
public static String getAccessToken(WxSystemparam wxSystemparam) {
HashMap<String, String> map = new HashMap<>();
map.put("grant_type", "client_credential");
map.put("appid", wxSystemparam.getAppid());
map.put("secret", wxSystemparam.getAppsecret());
String resInfo = HttpUtil.doGet(WxUrlConstant.GETACCESSTOKENURL, map);
JSONObject resObject = JSONObject.parseObject(resInfo);
String access_token = resObject.getString("access_token");
if (access_token == null) {
throw new CommonException("获取access_token失败");
}
return access_token;
}
/**
* 获取 jsapi_ticket 公众号用于调用微信JS接口的临时票据 有效期两小时
*
* @param access_token
* @return
*/
public static String getTicket(String access_token) {
HashMap<String, String> map = new HashMap<>();
map.put("access_token", access_token);
map.put("type", "jsapi");
String resInfo = HttpUtil.doGet(WxUrlConstant.GETJSAPITICKET, map);
JSONObject resObject = JSONObject.parseObject(resInfo);
if (!resObject.getString("errmsg").equals("ok")) {
throw new CommonException("获取jsapi-ticket失败");
}
String ticket = resObject.getString("ticket");
return ticket;
}
/**
* 获取微信用户openid
*
* @param wxSystemparam
* @param code
* @return
*/
public static String getOpenid(WxSystemparam wxSystemparam, String code) {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("appid", wxSystemparam.getAppid());
hashMap.put("secret", wxSystemparam.getAppsecret());
hashMap.put("code", code);
hashMap.put("grant_type", "authorization_code");
String retInfo = HttpUtil.doGet(WxUrlConstant.GETOPINIDURL, hashMap);
System.out.println(retInfo);
JSONObject jsonObject = JSONObject.parseObject(retInfo);
String openid = jsonObject.getString("openid");
return openid;
}
/**
* 小程序获取微信用户绑定的手机号
*
* @param token
* @param code
* @return
*/
public static String getPhoneNum(String token, String code) {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("access_token", token);
String json = "{\"code\":" + "\"" + code + "\"}";
System.out.println(json);
String retInfo = HttpUtil.doPost(WxUrlConstant.GETPHONENUMBERURL, hashMap,json);
System.out.println(retInfo);
JSONObject jsonObject = JSONObject.parseObject(retInfo);
Object phone_info = jsonObject.get("phone_info");
JSONObject jsonObject1 = JSONObject.parseObject(phone_info.toString());
String phoneNumber = jsonObject1.getString("phoneNumber");
return phoneNumber;
}
/**
* 进行SHA1加密
*
* @param input
* @return
*/
public static String getSHA1(String input) {
try {
MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
byte[] bytes = sha1.digest(input.getBytes());
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02x", b));
}
return sb.toString();
} catch (Exception e) {
throw new CommonException("SHA1加密出错:" + e);
}
}
public static String encryptSHA(String signStr) {
StringBuffer hexValue = new StringBuffer();
MessageDigest sha = null;
try {
sha = MessageDigest.getInstance("SHA-1");
byte[] byteArray = signStr.getBytes("UTF-8");
byte[] md5Bytes = sha.digest(byteArray);
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16) {
hexValue.append("0");
}
hexValue.append(Integer.toHexString(val));
}
} catch (Exception e) {
e.printStackTrace();
return "";
}
return hexValue.toString();
}
public static String getSign(String shaStr){
try {
MessageDigest mDigest = MessageDigest.getInstance("SHA1");
byte[] result = mDigest.digest(shaStr.getBytes());
StringBuffer signature = new StringBuffer();
for (int i = 0; i < result.length; i++) {
signature.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
}
return signature.toString();
} catch (NoSuchAlgorithmException e) {
log.error("获取微信签名异常",e);
return null;
}
}
}
HTTP请求工具类
public class HttpUtil {
private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);
protected static final String POST_METHOD = "POST";
private static final String GET_METHOD = "GET";
static {
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
logger.debug("ClientTrusted");
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
logger.debug("ServerTrusted");
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{};
}
}};
HostnameVerifier doNotVerify = (s, sslSession) -> true;
try {
SSLContext sc = SSLContext.getInstance("SSL", "SunJSSE");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(doNotVerify);
} catch (Exception e) {
logger.error("Initialization https impl occur exception : {}", e);
}
}
/**
* 默认的http请求执行方法
*
* @param url url 路径
* @param method 请求的方法 POST/GET
* @param map 请求参数集合
* @param data 输入的数据 允许为空
* @return result
*/
private static String HttpDefaultExecute(String url, String method, Map<String, String> map, String data) {
String result = "";
try {
url = setParmas(url, map, null);
result = defaultConnection(url, method, data);
} catch (Exception e) {
logger.error("出错参数 {}", map);
}
return result;
}
public static String httpGet(String url, Map<String, String> map) {
return HttpDefaultExecute(url, GET_METHOD, map, null);
}
public static String httpPost(String url, Map<String, String> map, String data) {
return HttpDefaultExecute(url, POST_METHOD, map, data);
}
/**
* 默认的https执行方法,返回
*
* @param url url 路径
* @param method 请求的方法 POST/GET
* @param map 请求参数集合
* @param data 输入的数据 允许为空
* @return result
*/
private static String HttpsDefaultExecute(String url, String method, Map<String, String> map, String data) {
try {
url = setParmas(url, map, null);
logger.info(data);
return defaultConnection(url, method, data);
} catch (Exception e) {
logger.error("出错参数 {}", map);
}
return "";
}
public static String doGet(String url, Map<String, String> map) {
return HttpsDefaultExecute(url, GET_METHOD, map, null);
}
public static String doPost(String url, Map<String, String> map, String data) {
return HttpsDefaultExecute(url, POST_METHOD, map, data);
}
/**
* @param path 请求路径
* @param method 方法
* @param data 输入的数据 允许为空
* @return
* @throws Exception
*/
private static String defaultConnection(String path, String method, String data) throws Exception {
if (StringUtils.isBlank(path)) {
throw new IOException("url can not be null");
}
String result = null;
URL url = new URL(path);
HttpURLConnection conn = getConnection(url, method);
if (StringUtils.isNotEmpty(data)) {
OutputStream output = conn.getOutputStream();
output.write(data.getBytes(StandardCharsets.UTF_8));
output.flush();
output.close();
}
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream input = conn.getInputStream();
result = IOUtils.toString(input, StandardCharsets.UTF_8);
input.close();
conn.disconnect();
}
// log.info(result);
return result;
}
/**
* 根据url的协议选择对应的请求方式
*
* @param url 请求路径
* @param method 方法
* @return conn
* @throws IOException 异常
*/
//待改进
protected static HttpURLConnection getConnection(URL url, String method) throws IOException {
HttpURLConnection conn;
if (StringUtils.equals("https", url.getProtocol())) {
conn = (HttpsURLConnection) url.openConnection();
} else {
conn = (HttpURLConnection) url.openConnection();
}
if (conn == null) {
throw new IOException("connection can not be null");
}
conn.setRequestProperty("Pragma", "no-cache");// 设置不适用缓存
conn.setRequestProperty("Cache-Control", "no-cache");
conn.setRequestProperty("Connection", "Close");// 不支持Keep-Alive
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setInstanceFollowRedirects(true);
conn.setRequestMethod(method);
conn.setConnectTimeout(8000);
conn.setReadTimeout(8000);
return conn;
}
/**
* 根据url
*
* @param url 请求路径
* @return isFile
* @throws IOException 异常
*/
//待改进
protected static HttpURLConnection getConnection(URL url, boolean isFile) throws IOException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (conn == null) {
throw new IOException("connection can not be null");
}
//设置从httpUrlConnection读入
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
//如果是上传文件,则设为POST
if (isFile) {
conn.setRequestMethod(POST_METHOD); //GET和 POST都可以 文件略大改成POST
}
// 设置请求头信息
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", String.valueOf(StandardCharsets.UTF_8));
conn.setConnectTimeout(8000);
conn.setReadTimeout(8000);
return conn;
}
/**
* 拼接参数
*
* @param url 需要拼接参数的url
* @param map 参数
* @param charset 编码格式
* @return 拼接完成后的url
*/
public static String setParmas(String url, Map<String, String> map, String charset) throws Exception {
String result = StringUtils.EMPTY;
boolean hasParams = false;
if (StringUtils.isNotEmpty(url) && MapUtils.isNotEmpty(map)) {
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey().trim();
String value = entry.getValue().trim();
if (hasParams) {
builder.append("&");
} else {
hasParams = true;
}
if (StringUtils.isNotEmpty(charset)) {
builder.append(key).append("=").append(URLEncoder.encode(value, charset));
} else {
builder.append(key).append("=").append(value);
}
}
result = builder.toString();
}
URL u = new URL(url);
if (StringUtils.isEmpty(u.getQuery())) {
if (url.endsWith("?")) {
url += result;
} else {
url = url + "?" + result;
}
} else {
if (url.endsWith("&")) {
url += result;
} else {
url = url + "&" + result;
}
}
logger.debug("request url is {}", url);
return url;
}
}
写的不好,欢迎交流。
更多推荐

所有评论(0)