基于uniapp H5页面调用微信授权获取code

1、判断是否微信浏览器
// 判断是否为公众号模拟器环境
    const isWechat = () => {
        return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
    }
2、访问特定微信链接来获取code
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
3、截取code方法
getUrlCode() {
      // 截取url中的code方法
      var url = location.search;
      var theRequest = new Object();
      if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        var strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
          theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
        }
      }
      console.log(theRequest);
      return theRequest;
    },
4、上demo
// 判断是否为微信环境
    const isWechat = () => {
        return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
    }
    export default {
        data() {
            return {
                code: ''
            }
        },
        onLoad() {
            this.getWechatCode()
        },
        methods: {
            getWechatCode() {
                if (isWechat) {
                    let appid = "公众号后台获取的APPID"; //微信APPid
                    let code = this.getUrlCode().code; //是否存在code
                    let local = window.location.href;
                    if (code == null || code === "") {
                      //不存在就打开上面的地址进行授权
                      window.location.href =
                        "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
                        appid +
                        "&redirect_uri=" +
                        encodeURIComponent(local) +
                        "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
                    } else {
                      this.code = code;
                    }
                  }
                },
            getUrlCode() {
              // 截取url中的code方法
              var url = location.search;
              var theRequest = new Object();
              if (url.indexOf("?") != -1) {
                var str = url.substr(1);
                var strs = str.split("&");
                for (var i = 0; i < strs.length; i++) {
                  theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
                }
              }
              console.log(theRequest);
              return theRequest;
            },
        }
    }
5、调试工具(微信开发者工具 ::公众号网页)

        输入重定向域名

uniapp中实现H5调用微信登录,可以通过以下步骤完成: 1. **配置微信公众号**: - 登录微信公众平台,进入“开发” -> “基本配置”,记录下AppID和AppSecret。 - 在“接口权限”中,确保已开通“网页授权获取用户基本信息”权限,并配置授权回调域名。 2. **前端代码**: -uniapp项目中,引入微信的JS SDK。 - 使用`uni.login`方法调用微信登录接口。 ```html <template> <button @click="login">微信登录</button> </template> <script> export default { methods: { login() { uni.login({ provider: 'weixin', success: (loginRes) => { // 登录成功后的处理逻辑 console.log(loginRes.authResult); // 这里可以发送登录凭证到服务器进行验证 }, fail: (err) => { console.error('登录失败:', err); } }); } }, mounted() { // 配置微信JS SDK uni.getProvider({ service: 'oauth', success: (res) => { if (~res.provider.indexOf('weixin')) { uni.login({ provider: 'weixin', success: (loginRes) => { // 登录成功后的处理逻辑 console.log(loginRes.authResult); } }); } } }); } } </script> ``` 3. **服务器端代码**: - 接收前端的登录凭证(code),并调用微信的接口获取用户信息。 - 使用AppID和AppSecret向微信服务器发送请求,获取access_token和openid。 - 使用access_token和openid获取用户的基本信息。 ```javascript const axios = require('axios'); async function getWeChatUserInfo(code) { const appid = 'YOUR_APPID'; const secret = 'YOUR_APPSECRET'; const url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=${secret}&code=${code}&grant_type=authorization_code`; try { const response = await axios.get(url); const { access_token, openid } = response.data; const userInfoUrl = `https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}`; const userInfoResponse = await axios.get(userInfoUrl); return userInfoResponse.data; } catch (error) { console.error('获取微信用户信息失败:', error); } } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王旭晨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值