基于上篇文章的测试公众号,我们实现h5获取用户基本信息的功能。
1、基础配置
- 测试的微信需要关注该测试公众号
- 修改授权回调域名
公众平台官网中: 开发 - 接口权限 - 网页服务 - 网页帐号 - 网页授权获取用户基本信息”的配置选项中,修改授权回调域名。测试环境回调地址支持域名和ip,正式公众号回调地址只支持域名。
测试环境:
2、开发流程
具体而言,网页授权获取用户信息流程分为四步:
1、引导用户进入授权页面同意授权,获取code
2、通过code换取网页授权access_token(与基础支持中的access_token不同)
3、如果需要,开发者可以刷新网页授权access_token,避免过期
4、通过网页授权access_token和openid获取用户基本信息(支持UnionID机制)
微信官网文档地址: https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
3、获取Code
实现: 具体就是引导用户或自动打开打开一个微信特定的地址,按微信的要求拼接参数即可。
- 微信给的特定地址: https://open.weixin.qq.com/connect/oauth2/authorize
- 参数:
- 代码用例:
let redirect_uri = window.location.href;
let appId = res.object; //从后端获取的appId
window.location.href="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appId+"&redirect_uri="
+encodeURIComponent(redirect_uri)+"&response_type=code&scope=snsapi_userinfo#wechat_redirect";
- 获取code
用户同意授权后,微信回在你的回调地址上拼接返回参数,例如:http://192.168.0.112:8080/car?code=xxxxxxx&state=xxxx。state是原样返回。
在你传的回调页面中获取code:
- 可以使用substring & split 的方式
- 如果是vue-router且是history模式:通过query直接获取
this.$route.query.code;
vue-router如果不是history的情况下,返回值会是:http://192.168.0.112:8080/?code=xxxxxxx&state=xxxx#/car
这种情况下使用substring & split
4、获取access_token
这个token与上篇讲的js-token不同。
- 获取token链接: https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
- 参数说明:
- 返回值:
- 示例代码:
WxServiceConfig wxServiceConfig = wxServiceConfigRepository.findOne(Constans.WX_SERVICE_CONFIG_ID);//查询微信配置信息
HashMap<String, String> params = new HashMap<String, String>();
params.put("appid", wxServiceConfig.getWxAppId());
params.put("secret", wxServiceConfig.getWxSecret());
params.put("code", code); //获取到的code
params.put("grant_type", "authorization_code");
Result tokenResult = OkHttpUtils.getData(Constans.WX_WEBPAGE_TOKEN_URL, params);
5、获取用户信息(需scope为 snsapi_userinfo)
如果第3步的获取code中 scope的参数传的为snsapi_base,则不弹出授权页面,直接跳转,只能获取用户openid,不能获取用户信息
- 获取链接:
https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
- 参数说明
- 返回值:
- 代码示例:
params.clear();
params.put("access_token", tokenInfo.getString("access_token")); //获取到access_token
params.put("openid", tokenInfo.getString("openid")); //获取到的openId
params.put("lang", "zh_CN");
Result userInfoResult = OkHttpUtils.getData(Constans.WX_GET_USER_INFO_URL, params);
if(userInfoResult.getCode() != 200) {
return new Result(Result.CODE_ERROR, "获用户信息失败!");
}
WxUserInfo userInfo = JSONObject.parseObject(userInfoResult.getMsg(),WxUserInfo.class);
OK完工。以上就是H5实现微信分享自定义&地图的全部内容,如果还有其他不懂的可以添加右下角微信,欢迎骚扰!
大家也可以点击我的gitee来获取我的其他项目源码。 拜拜!