【微信】获取用户OpenId等信息

一,问题

由于以前跟微信相关的操作都不是我来负责的,但是最近跟那边的人对接非常多问题。因此,我决定自己去实践一下跟微信的操作。第一步就是去拿用户的openid等信息。

二,配置腾讯开发者平台

2.1 申请微信的测试号,拿到AppId和AppSecret

地址:http://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index

在这里插入图片描述

2.2 在刚才的页面那里,往下拉,关注你的测试公众号

在这里插入图片描述

2.3 在刚才的页面,继续往下拉。找到“网页授权获取用户基本信息”。点击修改

在这里插入图片描述

填写域名即可。当用户确定授权给你之后,微信会主动调你一个接口A,然后将用户的信息发给你。因此,这个域名必须能访问得到你的A接口!!!

在这里插入图片描述

三,代码编写

获取OpenId的官方文档:
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842

3.1 流程

1 第一步:引导用户进入授权页面

2 第二步:用户确认授权,微信调你的一个接口,然后将code传给你

3 第三步:用code再去访问微信,去跟微信拿access_token和openId

4 第四步:用access_token和openId,再去跟微信拿更多用户的信息

3.2 代码

①AuthUtil工具类

/**
 * 
 */
package controller;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import net.sf.json.JSONObject;

/**
 * @author: KOLO
 * @date:2018年12月19日 下午4:51:08
 * @version: 1.0
 */
public class AuthUtil {
	public static final String APPID = "你的APPID";
	public static final String APPSECRET = "你的APP密码";

	public static JSONObject doGetJson(String url) throws ClientProtocolException, IOException {
		JSONObject jsonObject = null;
		// 首先初始化HttpClient对象
		DefaultHttpClient client = new DefaultHttpClient();
		// 通过get方式进行提交
		HttpGet httpGet = new HttpGet(url);
		// 通过HTTPclient的execute方法进行发送请求
		HttpResponse response = client.execute(httpGet);
		// 从response里面拿自己想要的结果
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			String result = EntityUtils.toString(entity, "UTF-8");
			jsonObject = jsonObject.fromObject(result);
		}
		// 把链接释放掉
		httpGet.releaseConnection();
		return jsonObject;
	}
}

②获取openId的Controller类

/**
 * 
 */
package controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.client.ClientProtocolException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import net.sf.json.JSONObject;

/**
 * @author: KOLO
 * @date:2018年12月19日 下午4:19:59
 * @version: 1.0
 */
@Controller
@RequestMapping("/user")
public class WeChatLogin {

	/**
	 * @Title: loginByWeChat
	 * @Description: 通过获取微信openid的方式来登录账号
	 * @param:
	 * @return:
	 * @throws IOException
	 */
	@RequestMapping("/loginByWechat")
	public String loginByWeChat(HttpServletResponse response) throws IOException {

		System.out.println("===========loginByWeChat方法执行了!===========");

		String backUrl = "你刚才在“网页授权获取用户基本信息”设置的域名  /本项目名 /user/code";
		
		//这个backUrl必须encode,不然会失败!!!
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=你的APPID&" + "redirect_uri="
				+ URLEncoder.encode(backUrl) + "&response_type=code&scope=snsapi_userinfo&"
				+ "state=STATE#wechat_redirect";
		
		//这里重定向去微信那边,跟它说有人在我这里登录了。微信收到后,就会让用户确认是否授权,是,就会将code通过上面的backUrl来传给你
		return "redirect:" + url;

	}

	/**
	 * 通过code去换取access_token
	 * 
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	@RequestMapping("/code")
	public @ResponseBody Object CodeForUserInfo(HttpServletRequest request, HttpServletResponse response)
			throws ClientProtocolException, IOException {
		// 第二步:通过code换取网页授权access_token

		// 从request里面获取code参数(当微信服务器访问回调地址的时候,会把code参数传递过来)
		String code = request.getParameter("code");

		System.out.println("获取到的code为:" + code);

		// 获取code后,请求以下链接获取access_token
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=你的APPID&"
				+ "secret=你的APP密码&code=" + code + "&grant_type=authorization_code";

		// 通过网络请求方法来请求上面这个接口
		JSONObject jsonObject = AuthUtil.doGetJson(url);

		System.out.println("==========================jsonObject" + jsonObject);

		// 从返回的JSON数据中取出access_token和openid,拉取用户信息时用
		String token = jsonObject.getString("access_token");
		String openid = jsonObject.getString("openid");

		// 第三步:刷新access_token(如果需要)

		// 第四步:拉取用户信息(需scope为 snsapi_userinfo)
		String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + token + "&openid=" + openid
				+ "&lang=zh_CN";
		// 通过网络请求方法来请求上面这个接口
		JSONObject userInfo = AuthUtil.doGetJson(infoUrl);

		HashMap<String, String> map = new HashMap<String, String>();

		map.put("openid", userInfo.getString("openid"));
		map.put("nickname", userInfo.getString("nickname"));
		map.put("sex", userInfo.getString("sex"));
		map.put("province", userInfo.getString("province"));
		map.put("city", userInfo.getString("city"));
		map.put("country", userInfo.getString("country"));
		map.put("headimgurl", userInfo.getString("headimgurl"));
		map.put("privilege", userInfo.getString("privilege"));

		String str = userInfo.getString("openid");
		
		return str;
	}

}

参考之:https://blog.csdn.net/Santiago_M/article/details/79109154

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值