记得看开发文档
1、第一步:用户同意授权,获取code
一般由前段调用,拿到code,传给后端。
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirec
参数 | 是否必须 | 说明 |
---|---|---|
appid | 是 | 公众号的唯一标识 |
redirect_uri | 是 | 授权后重定向的回调链接地址, 请使用 urlEncode 对链接进行处理 |
response_type | 是 | 返回类型,请填写code |
scope | 是 | 应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 ) |
state | 否 | 重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节 |
#wechat_redirect | 是 | 无论直接打开还是做页面302重定向时候,必须带此参数 |
用户同意授权后
如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE。
code说明 : code作为换取access_token的票据,每次用户授权带上的code将不一样,code只能使用一次,5分钟未被使用自动过期。
2、通过code换取网页授权access_token
获取code后,请求以下链接获取access_token: https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
参数 | 是否必须 | 说明 |
---|---|---|
appid | 是 | 公众号的唯一标识 |
secret | 是 | 公众号的appsecret |
code | 是 | 填写第一步获取的code参数 |
grant_type | 是 | 填写为authorization_code |
3、第三步:刷新access_token(如果需要)
由于access_token拥有较短的有效期,当access_token超时后,可以使用refresh_token进行刷新,refresh_token有效期为30天,当refresh_token失效之后,需要用户重新授权。
请求方法
获取第二步的refresh_token后,请求以下链接获取access_token:
https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN
参数 | 是否必须 | 说明 |
---|---|---|
appid | 是 | 公众号的唯一标识 |
grant_type | 是 | 填写为refresh_token |
refresh_token | 是 | 填写通过access_token获取到的refresh_token参数 |
4、第四步:拉取用户信息(需scope为 snsapi_userinfo)
如果网页授权作用域为snsapi_userinfo,则此时开发者可以通过access_token和openid拉取用户信息了。
请求方法
http:GET(请使用https协议) https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
参数说明
参数 | 描述 |
---|---|
access_token | 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同 |
openid | 用户的唯一标识 |
lang | 返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语 |
附:检验授权凭证(access_token)是否有效
请求方法
http:GET(请使用https协议) https://api.weixin.qq.com/sns/auth?access_token=ACCESS_TOKEN&openid=OPENID
参数说明
参数 | 描述 |
---|---|
access_token | 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同 |
openid | 用户的唯一标识 |
我的代码:
//wxLoginInfo 是后端自己测试时,传url,可以直接请求,拿到code,重定向到callBackInfo
@RequestMapping("/wxLoginInfo")
@ResponseBody
public void wxLoginInfo(HttpServletRequest req,HttpServletResponse resp) throws IOException { String parameter = req.getParameter("url"); //String backUrl = AuthUtil.WEIXINURL+"tourism/weixin/callBackInfo"; String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+AuthUtil.APPID + "&redirect_uri="+URLEncoder.encode(parameter) + "&response_type=code" + "&scope=snsapi_userinfo"//弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 + "&state=STATE#wechat_redirect"; System.out.println("url=="+url); /* * https://open.weixin.qq.com/connect/oauth2/authorize? * appid=wx64c8d530002513ab& * redirect_uri=https://sjysp.cn& * response_type=code& * scope=snsapi_userinfo& * state=STATE#wechat_redirect * * String url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+AuthUtil.APPID + "&redirect_uri="+URLEncoder.encode(backUrl) + "&response_type=code" + "&scope=snsapi_base" + "&state=STATE#wechat_redirect";*/ resp.sendRedirect(url); }
//拿到code后请求接口,拿到用户数据,关联公众平台后会拿到unionid,然后是进行的数据操作 @SuppressWarnings("unchecked") @RequestMapping("/callBackInfo") @ResponseBody public BaseResponse<Object> callBackInfo(HttpServletRequest req,HttpServletResponse resp) throws IOException { BaseResponse<Object> result = new BaseResponse<Object>(StatusCode.Success); String code = req.getParameter("code"); String codeUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+AuthUtil.APPID + "&secret="+AuthUtil.APPSECRET + "&code="+code + "&grant_type=authorization_code"; JSONObject codeJson = AuthUtil.doGetJson(codeUrl); System.out.println("codeJson= "+codeJson); String openid = codeJson.getString("openid"); String unionid = "" ; Set<Object> keySet = codeJson.keySet(); for (Object object : keySet) { if(object.equals("unionid")){ unionid = codeJson.getString("unionid"); System.out.println("unionid==="+unionid); } } String accessToken = codeJson.getString("access_token"); String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+accessToken + "&openid="+openid + "&lang=zh_CN"; JSONObject info = AuthUtil.doGetJson(infoUrl); System.out.println("info= "+info); String nickname = info.getString("nickname"); String sex = info.getString("sex"); String city = info.getString("city"); String headimgurl = info.getString("headimgurl"); String openId = info.getString("openid"); System.out.println("openid= "+openId); System.out.println("sex= "+sex); System.out.println("city= "+city); System.out.println("nickname= "+nickname); System.out.println("headimgurl= "+headimgurl);
//数据操作 UserPO userPO = new UserPO(); userPO.setOpenId(openid); BaseResponse<Object> selectList = userService.selectList(userPO); List<UserPO> list = (List<UserPO>) selectList.getData(); if(list==null || list.size()==0){ VisitorPO entity = new VisitorPO(); entity.setVisitorName(nickname); if(sex.equals("1")){ entity.setSex("男"); }else if(sex.equals("2")){ entity.setSex("女"); }else{ entity.setSex(""); } entity.setCity(city); entity.setSource("微信"); entity.setHeadImage(headimgurl); entity.setOpenId(openId); entity.setUnionId(unionid); BaseResponse<Object> insert = visitorService.insert(entity); String msg = insert.getMsg(); UserPO user = new UserPO(); user.setAccount(msg); user.setCreateTime(DateTimeUtil.getDateTime2Str()); user.setState(1); user.setUserName(entity.getVisitorName()); user.setUserType(3); user.setLogo(entity.getHeadImage()); user.setOpenId(openId); user.setUnionId(unionid); LoginUser login = new LoginUser(msg, nickname, PwdUtil.EncoderByMd5(msg)); String token = JWT.sign(login, 60L* 1000L* 30L); // RedisLogin redisLogin = (RedisLogin)redisCacheManager.get(msg); Map<String,Object> infoMap =new HashMap<String,Object>(); infoMap.put("loginToken", token); infoMap.put("userId", msg); infoMap.put("user", user); result.setData(infoMap); RedisLogin redisLogin = new RedisLogin(msg, token, System.currentTimeMillis() + 60L* 1000L* 60L*24*365); redisCacheManager.set(msg , redisLogin, 3600*24*365); recordSuccess(0, msg, "公众号登录,操作成功", 0); System.out.println(1); }else{ UserPO entity = list.get(0); LoginUser login = new LoginUser(entity.getAccount(), entity.getUserName(), entity.getPassWord()); String token = JWT.sign(login, 60L* 1000L* 30L); // RedisLogin redisLogin = (RedisLogin)redisCacheManager.get(entity.getAccount()); Map<String,Object> infoMap =new HashMap<String,Object>(); infoMap.put("loginToken", token); infoMap.put("userId", entity.getAccount()); entity.setPassWord(""); infoMap.put("user", entity); result.setData(infoMap); RedisLogin redisLogin = new RedisLogin(entity.getAccount(), token, System.currentTimeMillis() + 60L* 1000L* 60L*24*365); redisCacheManager.set(entity.getAccount() , redisLogin, 3600*24*365); recordSuccess(0, entity.getAccount(), "公众号登录,操作成功", 0); System.out.println(2); } return result; }
AuthUtil.APPID,AuthUtil.APPSECRET:公众平台的appid和APPSECRET
package com.fltd.tourism.util; 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; public class AuthUtil { public static final String WEIXINURL= "https://xxxxx.cn/"; public static JSONObject doGetJson(String url) throws ClientProtocolException, IOException{ JSONObject jsonObject = null; DefaultHttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); HttpResponse response = client.execute(httpGet); HttpEntity entity = response.getEntity(); if(entity != null){ String result = EntityUtils.toString(entity,"UTF-8"); jsonObject = JSONObject.fromObject(result); } httpGet.releaseConnection(); return jsonObject; } }
总结:
1、其中 AuthUtil.APPID,AuthUtil.APPSECRET是微信公众号正式的,不要弄错了,很容易和小程序、开放平台、开发环境等弄混,回报错。
2、wxLoginInfo中url,一定要看清楚是否和公众号上的一致,不然也会报错:redirect_url域名与后台配置不一致。
3、unionid正常情况是没有的,要关联上才会有。具体看微信的文档