微信H5获取用户信息以及配套后端代码(Java)

305 阅读1分钟

第一步  获取用户code 

【接口】

https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=URL&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect

【注意】

  1. URL要用base64转义

  2. scope 授权弹窗和静默授权

【结果】code = xxxxxxxxxxxxxx

第二步  通过code换取网页授权access_token 接口

【接口】

https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=APPSECRET&code=CODE&grant_type=authorization_code  

【结果】

得到openid、access_token、refresh_token

{"access_token":"37_nApMk3zglqG02067ltIGa1uxnVEHkCJ7_IuoKD8y278bmLAcT7w3_ThdifIGR3M63GKKQ4yvcUPZufywolQTvw","expires_in":7200,"refresh_token":"37_pwLglB6kWfep5sfsF8RFoL2mwYL0PClGcsJ7o5IWgcn93AtGUtWtcvz1d8zHf8Rz4sI2hiUWIvuy9EvgElDz2Q","openid":"oX6mX57QiiVC0DHls-eQ_igBfkbA","scope":"snsapi_userinfo"} 

【注意】

access_token有效期很短,之后可以通过refresh_token(有效期30天)刷新

【后端】

数据库中存openid

第2.5步 通过refresh_token 获取 access_token

【接口】

https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN

第三步  通过openid获取用户信息 

【接口】 

https://api.weixin.qq.com/sns/userinfo?access_token=37_nApMk3zglqG02067ltIGa1uxnVEHkCJ7_IuoKD8y278bmLAcT7w3_ThdifIGR3M63GKKQ4yvcUPZufywolQTvw&openid=oX6mX57QiiVC0DHls-eQ_igBfkbA&lang=zh_CN 

【注意】

中文乱码要转UTF-8 

附 验证access_token是否有效

**【接口】**GET 

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

【结果】

{ "errcode":0,"errmsg":"ok"}