JAVA 获取微信用户信息,看完这篇你必须得学会

3.网页授权域名

这里一样,也是项目的域名。

 

好了,总体我们看了一下,我们需要填写的三个模块的信息,都有一个非常关键的东西,域名。

那怎么有域名呢?本地写demo的小伙伴眉头不由自主一皱?

前期准备工作Part 2  内网穿透 整一个域名出来(如果你有已经可以用的域名,那么你可以不理这个Part 2)

具体内网穿透,将本地127.0.0.1 对应一个外网可以访问的域名。 本来我是写了具体操作示例的,但是涉嫌打广告,导致文章被下架了,所以这个part2,就只能删除了。 请理解。

(微信公众平台测试号的信息还没填?别急)

接下来我们建一个java项目,

第一个工具类,  用来调微信接口的,HttpClientUtil.java:

import org.apache.http.NameValuePair;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.client.utils.URIBuilder;

import org.apache.http.entity.ContentType;

import org.apache.http.entity.StringEntity;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.message.BasicNameValuePair;

import org.apache.http.util.EntityUtils;

import java.io.IOException;

import java.net.URI;

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

/**

  • @Author : JCccc

  • @CreateTime : 2019/8/2

  • @Description :

**/

public class HttpClientUtil {

public static String doGet(String url, Map<String, String> param) {

// 创建Httpclient对象

CloseableHttpClient httpclient = HttpClients.createDefault();

String resultString = “”;

CloseableHttpResponse response = null;

try {

// 创建uri

URIBuilder builder = new URIBuilder(url);

if (param != null) {

for (String key : param.keySet()) {

builder.addParameter(key, param.get(key));

}

}

URI uri = builder.build();

// 创建http GET请求

HttpGet httpGet = new HttpGet(uri);

// 执行请求

response = httpclient.execute(httpGet);

// 判断返回状态是否为200

if (response.getStatusLine().getStatusCode() == 200) {

resultString = EntityUtils.toString(response.getEntity(), “UTF-8”);

}

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

if (response != null) {

response.close();

}

httpclient.close();

} catch (IOException e) {

e.printStackTrace();

}

}

return resultString;

}

public static String doGet(String url) {

return doGet(url, null);

}

public static String doPost(String url, Map<String, String> param) {

// 创建Httpclient对象

CloseableHttpClient httpClient = HttpClients.createDefault();

CloseableHttpResponse response = null;

String resultString = “”;

try {

// 创建Http Post请求

HttpPost httpPost = new HttpPost(url);

// 创建参数列表

if (param != null) {

List paramList = new ArrayList<>();

for (String key : param.keySet()) {

paramList.add(new BasicNameValuePair(key, param.get(key)));

}

// 模拟表单

UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);

httpPost.setEntity(entity);

}

// 执行http请求

response = httpClient.execute(httpPost);

resultString = EntityUtils.toString(response.getEntity(), “utf-8”);

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

response.close();

} catch (IOException e) {

e.printStackTrace();

}

}

return resultString;

}

public static String doPost(String url) {

return doPost(url, null);

}

public static String doPostJson(String url, String json) {

// 创建Httpclient对象

CloseableHttpClient httpClient = HttpClients.createDefault();

CloseableHttpResponse response = null;

String resultString = “”;

try {

// 创建Http Post请求

HttpPost httpPost = new HttpPost(url);

// 创建请求内容

StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);

httpPost.setEntity(entity);

// 执行http请求

response = httpClient.execute(httpPost);

resultString = EntityUtils.toString(response.getEntity(), “utf-8”);

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

response.close();

} catch (IOException e) {

e.printStackTrace();

}

}

return resultString;

}

}

第二个工具类,跟微信碰头验证用的,SignUtil.java:

import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;

import java.util.Arrays;

/**

  • @Author : JCccc

  • @CreateTime : 2019/8/2

  • @Description :

**/

public class SignUtil {

private static String token = “weixinCoursexxxxx”;//填你自己的

public static boolean checkSignature(String signature, String timestamp, String nonce) {

String[] paramArr = new String[] { token, timestamp, nonce };

Arrays.sort(paramArr);

String content = paramArr[0].concat(paramArr[1]).concat(paramArr[2]);

String ciphertext = null;

try {

MessageDigest md = MessageDigest.getInstance(“SHA-1”);

byte[] digest = md.digest(content.toString().getBytes());

ciphertext = byteToStr(digest);

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

}

return ciphertext != null ? ciphertext.equals(signature.toUpperCase()) : false;

}

private static String byteToStr(byte[] byteArray) {

String strDigest = “”;

for (int i = 0; i < byteArray.length; i++) {

strDigest += byteToHexStr(byteArray[i]);

}

return strDigest;

}

private static String byteToHexStr(byte mByte) {

char[] Digit = { ‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’ };

char[] tempArr = new char[2];

tempArr[0] = Digit[(mByte >>> 4) & 0X0F];

tempArr[1] = Digit[mByte & 0X0F];

String s = new String(tempArr);

return s;

}

}

然后最关键的东西,接口,WxLoginController.java:

import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSONObject;

import com.springmvc.util.HttpClientUtil;

import com.springmvc.util.SignUtil;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

import java.net.URLEncoder;

/**

  • @Author : JCccc

  • @CreateTime : 2019/8/2

  • @Description :

**/

@RestController

@RequestMapping(“/wxAuth”)

public class WxLoginController {

private static String APPID=“xxxxxx”;//填你自己的

private static String APPSECRET=“xxxxx”;//填你自己的

/**

  • 用于给微信验证token

  • @param request

  • @param response

  • @return

  • @throws IOException

*/

@RequestMapping(“/checkToken”)

public String checkToken(HttpServletRequest request,HttpServletResponse response) throws IOException {

// 微信加密签名

String signature = request.getParameter(“signature”);

// 时间戳

String timestamp = request.getParameter(“timestamp”);

// 随机数

String nonce = request.getParameter(“nonce”);

// 随机字符串

String echostr = request.getParameter(“echostr”);

if (SignUtil.checkSignature(signature, timestamp, nonce)) {

System.out.println(“校验token成功”);

return echostr;

}else{

System.out.println(“校验token不成功”);

return null;

}

}

/**

  • 用于获取出回调地址 (引导用户调用此接口,成功后自动调取回调地址然后取出用户信息)

  • @param response

  • @throws IOException

*/

@RequestMapping(“/login”)

public void wxLogin(HttpServletResponse response) throws IOException {

//请求获取code的回调地址

//用线上环境的域名或者用内网穿透,不能用ip

String callBack = “http://3xXXXXXXXi.natappfree.cc/wxAuth/callBack”;//域名填你自己的

//请求地址

String url = “https://open.weixin.qq.com/connect/oauth2/authorize” +

“?appid=” + APPID +

“&redirect_uri=” + URLEncoder.encode(callBack) +

“&response_type=code” +

“&scope=snsapi_userinfo” +

“&state=STATE#wechat_redirect”;

System.out.println(url);

//重定向

response.sendRedirect(url);

}

/**

  • 回调方法

  • @param request

  • @param response

  • @throws IOException

*/

// 回调方法

@RequestMapping(“/callBack”)

public String wxCallBack(HttpServletRequest request, HttpServletResponse response) throws IOException {

String code = request.getParameter(“code”);

//获取access_token

String url = “https://api.weixin.qq.com/sns/oauth2/access_token” +

“?appid=” + APPID +

“&secret=” + APPSECRET +

“&code=” + code +

“&grant_type=authorization_code”;

String result = HttpClientUtil.doGet(url);

System.out.println(“请求获取access_token:” + result);

//返回结果的json对象

JSONObject resultObject = JSON.parseObject(result);

//请求获取userInfo

String infoUrl = “https://api.weixin.qq.com/sns/userinfo” +

“?access_token=” + resultObject.getString(“access_token”) +

“&openid=” + resultObject.getString(“openid”) +

“&lang=zh_CN”;

String resultInfo = HttpClientUtil.doGet(infoUrl);

//此时已获取到userInfo,再根据业务进行处理

System.out.println(“请求获取userInfo:” + resultInfo);

return “hello!”;

}

}

好了,到这里,我们其实已经准备就绪了。 就这么点代码足够了。那么接下来我们回去补全刚刚需要填的东西。

第一部分:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值