微信公众号获取openId——开发阶段

1、注册测试号

微信公众平台

2、理解获取逻辑

获得微信的openid,需要先访问微信提供的一个网址来获取code。
再访问微信提供的另一网址从而获取openId。

两个链接分别为:

https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_base&state=STATE

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

3、选择预览环境

第一个链接需要在微信客户端打开,可以选择微信开发者工具

选择公众号网页项目

打开后在地址栏中输入第一个URL地址,我这边后面跟的是跳转的网页

https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxa5b9c7f2a5ab9d1e&redirect_uri=http://192.168.3.130:3000&response_type=code&scope=snsapi_base&state=STATE

 注意:这个redirect_uri填写的地址需要在公众号或者是测试号中网页账号中进行配置

扫描二维码关注公众号,回复: 15698141 查看本文章

 跳转后可以看到地址栏中出现了两个参数,code和state,这个时候,我们就可以拿到我们需要的code

 4、获取openId

获取到code后,就可以通过第二个链接,将所需的内容填写后,获取到openId了。

推荐从后端获取openId,可能会存在跨域、code不可用等等一系列问题,code只能使用一次。

@GetMapping("/getOpenId")
    @ApiOperation("获取OpenId")
    public JSONObject getOpenId(@RequestParam("code") String code){
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={appid}&secret={secret}&code={code}&grant_type={grant_type}";
        HashMap<String,String> params = new HashMap<>();
        params.put("appid","");
        params.put("secret","");
        params.put("code",code);
        params.put("grant_type","authorization_code");
        String result = new RestTemplate().getForEntity(url, String.class, params).getBody();
        return JSONObject.fromObject(result);
    }

猜你喜欢

转载自blog.csdn.net/weixin_42078172/article/details/127917025