400-915-1135
详细

微信——获取用户基本信息及openid 、access_token、code

发表日期:2022-01-26 11:44:05   作者来源:超级管理员   浏览:0


access_token:公众号的全局唯一票据,
获取access_token,需要调用https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

openid:普通用户的标识,对当前公众号唯一
获取openid需要先获取code,
获取用户信息步骤:

  • 引导用户进入授权页面同意授权,获取code

    这一步其实就是将需要授权的页面url拼接到微信的认证请求接口里面,比如需要用户在访问页面 时进行授权认证
    其中的scope参数有两个值:
    1.snsapi_base:只能获取到用户openid。好处是静默认证,无需用户手动点击认证按钮,感觉上像是直接进入网站一样。
    2.snsapi_userinfo:可以获取到openid、昵称、头像、所在地等信息。需要用户手动点击认证按钮。

  • 通过第一步获取的code换取网页授权access_token(与基础支持中的access_token不同)

    这一步需要在控制器中获取微信回传给我们的code,通过这个code来请求access_token,通过access_token和openid获取用户基本信息

1.获取code需要调用接口

https://open.weixin.qq.com/connect/oauth2/authorize?appid=appid&redirect_uri=现在访问的方法的url&response_type=code&scope=snsapi_userinfo&state=STATE

eg: https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx761cf6338fb3ad4a&redirect_uri=http://bnetweixin.yto56test.com&res&res&response_type=code&scope=snsapi_userinfo#wechat_redirect

@ApiIgnore
@InvokeLog(name = "sendRedirect", description = "获取code")
@RequestMapping(value = "/sendRedirect", method = { RequestMethod.POST, RequestMethod.GET })
public void sendRedirect(@RequestBody Map<String, Object> reqMap, HttpServletResponse response) {
    if (reqMap.get("redirect_uri") == null) {
        log.info("redirect_uri为空!!!");
        return;
    }
    String redirect_uri = reqMap.get("redirect_uri").toString();
    //回调地址
    redirect_uri = getURLEncoderString(redirect_uri);
    //授权页面地址
    String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
    url = url.replace("APPID", APPID).replace("REDIRECT_URI", redirect_uri).replace("SCOPE", "snsapi_base");
    try {
       //重定向到授权页面   跳转回调redirect_uri,应当使用https链接来确保授权code的安全性
        response.sendRedirect(url);
    } catch (Exception e) {
    }
}


参数是否必须说明
appid公众号的唯一标识
redirect_uri授权后重定向的回调链接地址, 请使用 urlEncode 对链接进行处理
response_type返回类型,请填写code
scope应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 )
state重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节
#wechat_redirect无论直接打开还是做页面302重定向时候,必须带此参数

2.获取access_token及openId接口 (通过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
secret填写第一步获取的code参数
grant_type填写为authorization_code

正确时返回的JSON数据包如下:

{
	“access_token”:”ACCESS_TOKEN”, (网页授权接口调用凭证)
	“expires_in”:7200, (access_token接口调用凭证超时时间,单位(秒))
	“refresh_token”:”REFRESH_TOKEN”, (用户刷新access_token )
	“openid”:”OPENID”, (用户唯一标识,请注意,在未关注公众号时,用户访问公众号的网页,也会产生一个用户和公众号唯一的OpenID )
	“scope”:”SCOPE”(用户授权的作用域,使用逗号(,)分隔)
 }


具体代码:

@ApiIgnore
@InvokeLog(name = "getWeChatOpenid", description = "获取openid")
@RequestMapping(value = "/getWeChatOpenid", method = { RequestMethod.POST, RequestMethod.GET })
@ResponseBody
public String getWeChatOpenid(@RequestParam("code") final String code) {
    if (StringUtil.isEmpty(code)) {
        return "{}";
    } else {
    }
    BasicHeader header = new BasicHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
    String openidUrl = https://api.weixin.qq.com/sns/oauth2/access_token;

    Map<String, String> paraMaps = Maps.newConcurrentMap();
    paraMaps.put("appid", APPID);
    paraMaps.put("secret", APPSECRET);
    paraMaps.put("code", code);
    paraMaps.put("grant_type", "authorization_code");

    String result = "{}";
    String responseStr = null;
    Gson gson = new Gson();
    try {
        responseStr = HttpClientUtil.sendHttpPost(openidUrl, paraMaps, header);
        if (StringUtil.isNotEmpty(responseStr)) {
            JsonObject responseData = new JsonParser().parse(responseStr).getAsJsonObject();
            String openid = responseData.get("openid").getAsString();
        }
    } catch (Exception e) {
        log.error("获取openid失败", e);
    }
    return result;
}

3. 获取用户信息需要调用的接口

https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN

具体代码:

@ApiIgnore
@InvokeLog(name = "getWeChatUserInfo", description = "获取用户信息")
@RequestMapping(value = "/getWeChatUserInfo", method = { RequestMethod.POST, RequestMethod.GET })
@ResponseBody
public String getWeChatUserInfo(@RequestParam("webAccessToken") final String webAccessToken,
        @RequestParam("openId") final String openId) {
    if (StringUtil.isEmpty(openId) || StringUtil.isEmpty(webAccessToken)) {
        return CommonUtil.getReturn(MessageConstants.MISSING_ARGUMETN, SysErrorConsts.MISSING_ARGUMETN_ERROR_CODE,
                null);
    }
    String token = webAccessToken;
    JsonObject jsonObject = new JsonObject();
    String url = https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN.replace("ACCESS_TOKEN", token).replace("OPENID", openId)
    try {
        String responseStr = HttpClientUtil.sendHttpGet(url);
     return  responseStr ;
}

正确时返回的JSON数据包如下:

{ 
  "openid":" OPENID", (用户的唯一标识 )
  "nickname": NICKNAME, 
  "sex":"1", (用户的性别,值为1时是男性,值为2时是女性,值为0时是未知 )
  "province":"PROVINCE" (用户个人资料填写的省份 )
  "city":"CITY", (普通用户个人资料填写的城市 )
  "country":"COUNTRY", 
  "headimgurl": "http://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46", (用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空。若用户更换头像,原有头像URL将失效。)
  "privilege":["PRIVILEGE1” “PRIVILEGE2"], (用户特权信息,json 数组,如微信沃卡用户为(chinaunicom))
  "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL" (只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。)
}



本文章多为网络内容整理而来,如有侵犯您的权益,请联系我们免费删除