第三方H5对接微信Oauth2及扫一扫功能回顾

1、先登录微信公众平台,进入“公众号设置”的“功能设置”里填写“JS接口安全域名”,进入“基础配置”,将服务端部署ip配置到IP白名单中。
2、引入JS文件 在需要调用JS接口的页面引入如下JS文件,(支持 https):http://res.wx.qq.com/open/js/jweixin-1.6.0.js
3、通过config接口注入权限验证配置,所需参数从服务端接口获取;

服务端生成签名时需要配置当前网页的URL(不包含#及其后面部分,需域名,本地ip试了不行),可由前端将调用扫一扫的页面url传给服务端生成签名的接口;

前端代码

    let signData = await request('api/demo/auth/sign', { method: 'POST', body: {
      "url": window.location.origin + window.location.pathname, //当前网页的URL传给后端
    } })
    console.log('signData',signData);
    wx.config({
      debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
      appId: 'wx7048dabe52cXXXXX', // 必填,公众号的唯一标识
      timestamp: signData.timestamp, // 必填,生成签名的时间戳
      nonceStr: signData.nonceStr, // 必填,生成签名的随机串
      signature: signData.signature,// 必填,签名
      jsApiList: ['scanQRCode'] // 必填,需要使用的JS接口列表
    });

后端代码

    @PostMapping("/sign")
    public SignResp sign(@RequestBody @Valid SignReq req) {
        try {
            String fkToken = redisTemplate.opsForValue().get(FK_TOKEN_KEY_PREFIX + APP_ID);
            if (fkToken == null) {
                synchronized (FK_TOKEN_KEY_PREFIX) {
                    fkToken = redisTemplate.opsForValue().get(FK_TOKEN_KEY_PREFIX + APP_ID);
                    if (fkToken == null) {
                        Request request = new Request.Builder()
                                .url(genUri("fkAccessToken"))
                                .get()
                                .build();

                        OkHttpClient okHttpClient = new OkHttpClient();
                        Response response = okHttpClient.newCall(request).execute();
                        String result = response.body().string();
                        log.info("fkAccessToken result: {}", result);
                        JSONObject jsonObject = JSONUtil.parseObj(result);

                        fkToken = jsonObject.getStr("access_token");
                        redisTemplate.opsForValue().set(FK_TOKEN_KEY_PREFIX + APP_ID, fkToken);
                        redisTemplate.expire(FK_TOKEN_KEY_PREFIX + APP_ID, 7000, TimeUnit.SECONDS);
                    }
                }
            }

            String ticket = redisTemplate.opsForValue().get(TICKET_KEY_PREFIX + APP_ID);
            if (ticket == null) {
                Request request = new Request.Builder()
                        .url(genUri("ticket", fkToken))
                        .get()
                        .build();

                OkHttpClient okHttpClient = new OkHttpClient();
                Response response = okHttpClient.newCall(request).execute();
                String result = response.body().string();
                log.info("sign result: {}", result);
                JSONObject jsonObject = JSONUtil.parseObj(result);

                ticket = jsonObject.getStr("ticket");
                redisTemplate.opsForValue().set(TICKET_KEY_PREFIX + APP_ID, ticket);
                redisTemplate.expire(TICKET_KEY_PREFIX + APP_ID, 7000, TimeUnit.SECONDS);
            }

            // 签名
            String noncestr = IdUtil.simpleUUID();
            String timestamp = String.valueOf(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());
//            String url = SIGN_PAGE_URI;

            String content = "jsapi_ticket=" + ticket
                    + "&noncestr=" + noncestr
                    + "×tamp=" + timestamp
                    + "&url=" + req.url;

            SignResp signResp = new SignResp();
            signResp.setNonceStr(noncestr);
            signResp.setTimestamp(timestamp);
            signResp.setSignature(SecureUtil.sha1(content));
            log.info("signResp: {}", signResp);
            return signResp;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private String genUri(String type, String... args) {
        switch (type) {
            case "grant":  // 获取授权码
                return "https://open.weixin.qq.com/connect/oauth2/authorize?"
                        + "appid=" + APP_ID
                        + "&redirect_uri=" + URLUtil.encode(REDIRECT_URI, StandardCharsets.UTF_8)
                        + "&response_type=code"
                        + "&scope=snsapi_base"
                        + "&state=STATE"
                        + "#wechat_redirect";
            case "accessToken":  // 获取微信用户accessToken
                return "https://api.weixin.qq.com/sns/oauth2/access_token?"
                        + "appid=" + APP_ID
                        + "&secret=" + APP_SECRET
                        + "&code=" + args[0]
                        + "&grant_type=authorization_code";
            case "refreshAccessToken":  // 刷新微信用户accessToken
                return "https://api.weixin.qq.com/sns/oauth2/refresh_token?"
                        + "appid=" + APP_ID
                        + "&grant_type=refresh_token"
                        + "&refresh_token=" + args[0];
            case "ticket":  // 获取jsapi_ticket
                return "https://api.weixin.qq.com/cgi-bin/ticket/getticket?"
                        + "access_token=" + args[0]
                        + "&type=jsapi";
            case "fkAccessToken":  // 获取公众号accessToken
                return "https://api.weixin.qq.com/cgi-bin/token?"
                        + "grant_type=client_credential"
                        + "&appid=" + APP_ID
                        + "&secret=" + APP_SECRET;
        }
        throw new RuntimeException();
    }
4、调用微信扫一扫;
    wx.scanQRCode({
      needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
      scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码,默认二者都有
      success: function (res) {
        var result = res.resultStr; // 当needResult 为 1 时,扫码返回的结果
        console.log(result);
        request('api/demo/user/query', {
          method: 'POST', body: {
            "number": result
          }
        }).then(res => {
          console.log(res);
          jumpPage('/search/result', JSON.parse(res.data))
        })
      }
    })
5、如果要获取微信用户信息,需网页鉴权-Oauth2,只有通过微信认证的服务号有权限,订阅号不行,进入“公众号设置”的“功能设置”里进行网页授权域名填写;参考链接
6、成功demo(前端获取到code后传给服务端接口,接口返回openId,或者用户信息)

前端代码 (拿到授权码后请求后端获取AccessToken)

    let openId = ''
    let code  =  this.getUrlParam('code','?' +  window.location.href.split('?')[1])
    const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=xxx&redirect_uri=https://xxx.com/deme/&response_type=code&scope=snsapi_base&state=STATE`
    if(!sessionStorage.getItem('openId')){
      if(code){
        request('api/demo/auth/receive', { method: 'POST', body: {
          code: code,
        } }).then(res=>{
          openId = res.openId
          sessionStorage.setItem('openId',openId)
          this.getUserInfo() //通过openId获取用户信息
          history.pushState('', '', 'https://xxx.com/deme/')
        })
      }else{
        window.location.href = url
      }
    }else{
      this.getUserInfo() //通过openId获取用户信息
    }
// 回调回来的地址是:https://xxx.com/deme/?code=xxxxxx&state=xxx
// 如果你是使用hash路由的,一般的取url参数的方法会有点小问题,需要手动调整下

 getUrlParam = (name, location) => {
    const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
    const { hash, search } = window.location;
    const result = ((location||(hash || search)).split('?')[1] || '').match(reg);
    return result ? decodeURIComponent(result[2]) : null;
  }

后端代码 (获取AccessToken)

    @PostMapping("/receive")
    public ReceiveResp receive(@RequestBody @Valid ReceiveReq req) {
        log.info("receiveReq: {}", req);
        Request request = new Request.Builder()
                .url(genUri("accessToken", req.code))
                .get()
                .build();

        try {
            OkHttpClient okHttpClient = new OkHttpClient();
            Response response = okHttpClient.newCall(request).execute();
            String result = response.body().string();
            log.info("receive result: {}", result);
            JSONObject jsonObject = JSONUtil.parseObj(result);
            String openId = jsonObject.getStr("openid");
            if (StringUtils.isBlank(openId)) {
                throw new RuntimeException("error");
            }
            redisTemplate.opsForValue().set(TOKEN_KEY_PREFIX + openId, jsonObject.getStr("access_token"));
            redisTemplate.expire(TOKEN_KEY_PREFIX + openId, 7000, TimeUnit.SECONDS);
            redisTemplate.opsForValue().set(REFRESH_TOKEN_KEY_PREFIX + openId, jsonObject.getStr("access_token"));
            redisTemplate.expire(REFRESH_TOKEN_KEY_PREFIX + openId, 29, TimeUnit.DAYS);
            ReceiveResp resp = new ReceiveResp();
            resp.setOpenId(openId);
            return resp;
        } catch (Exception e) {
            throw new RuntimeException("error", e);
        }
    }

后端代码 (获取缓存的AccessToken,如已过期则刷新AccessToken)

    private String getAccessToken(String openId) throws IOException {
        String accessToken = redisTemplate.opsForValue().get(TOKEN_KEY_PREFIX + openId);
        if (accessToken == null) {
            String refreshAccessToken = redisTemplate.opsForValue().get(REFRESH_TOKEN_KEY_PREFIX + openId);
            if (refreshAccessToken == null) {
                throw new RuntimeException("会话已过期,请重新登录");
            }
            Request request = new Request.Builder()
                    .url(genUri("refreshAccessToken", refreshAccessToken))
                    .get()
                    .build();

            OkHttpClient okHttpClient = new OkHttpClient();
            Response response = okHttpClient.newCall(request).execute();
            String result = response.body().string();
            JSONObject jsonObject = JSONUtil.parseObj(result);

            redisTemplate.opsForValue().set(TOKEN_KEY_PREFIX + openId, jsonObject.getStr("access_token"));
            redisTemplate.expire(TOKEN_KEY_PREFIX + openId, 7000, TimeUnit.SECONDS);

            return jsonObject.getStr("access_token");

        }
        return accessToken;
    }
7、官方链接: JSSDK使用步骤 JS-SDK使用权限签名算法

8、踩坑小记

在微信扫一扫和Oauth2认证的官方文档里,都有提到accessToken,但两者并不是一个东西,获取它们的接口也不相同。扫一扫里的accessToken属于公众号,而Oauth2里的accessToken属于微信用户。扫一扫的签名接口的入参accessToken指的是公众号的accessToken。

你可能感兴趣的:(第三方H5对接微信Oauth2及扫一扫功能回顾)