那些年用node接入微信走过的坑之(四)---微信扫码登录第三方网站

序言

随着微信使用者不断增多,很多网站使用了微信扫码登录功能,这里做一个简单的实现。

第三方网页授权和微信网页端授权

这两个笔者当初区分了好久,有什么区别和联系呢?

相同点:
两者的过程基本是类似的,都是通过appId和secret和code首先获取access_token(注意这里的access_token跟通用api调取token是不一样的 ),然后通过access_token和openId获取用户基本信息进行操作,比如说登录。

不同点:

  1. 微信网页授权,一般情况下在微信端打开的页面,出现如下授权方式的,如图
  2. 第三方网页授权一般是,比腾讯的易迅

    授权的界面也是不同的。

实现

###微信网页授权

首先我们要有自己的公众号,查看appId和secret
1. 跳转链接
https://open.weixin.qq.com/connect/oauth2/authorize?appid=yourId&redirect_uri=yourUrl&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect

2.生成链接 yourUrl + &code=xxxxxxxx,这个链接我们可以哪里进行获取用户信息,比如openId。

第三方网页授权登录

首先我们要在微信开发平台中建立一个网页应用(重要)
两种方式,一种是直接使用微信页面,一种是将微信页面(ifram)嵌入到我们自己的网页中来,我采用第二种

  1. 首先在页面生成ifram。关键代码如下
 wxInit: function () {
        !function (a, b) {
            function d(a) {
                var e, c = b.createElement("iframe"),
                    d = "https://open.weixin.qq.com/connect/qrconnect?appid=" + a.appid + "&scope=" + a.scope + "&redirect_uri=" + a.redirect_uri + "&state=" + a.state + "&login_type=jssdk";
                d += a.style ? "&style=" + a.style : "",
                    d += a.href ? "&href=" + a.href : "",
                    c.src = d,
                    c.frameBorder = "0",
                    c.allowTransparency = "true",
                    c.scrolling = "no",
                    c.width = "300px",
                    c.height = "400px",
                    e = b.getElementById(a.id),
                    e.innerHTML = "",
                    e.appendChild(c)
            }

            a.WxLogin = d
        }(window, document);
        //初始化
        var obj = new WxLogin({
            id: "login_container",
            appid: "yourId",
            scope: "snsapi_login",
            redirect_uri: encodeURIComponent("http://www.idianbang.cn/user/login"),
            state: Math.ceil(Math.random() * 1000),
            style: "black",
            href: ""
        });
    }

2.跟上一步一样,生成链接 yourUrl + &code=xxxxxxxx,这个链接我们可以哪里进行获取用户信息,比如openId。

最后做一些处理比如说登录

就是获取用户信息,对用户进行登录或者注册的操作

function getWXUser(req, res) {
    var code = req.body.code;
    var type = req.body.type || 0;
    var appid, appsecret;

    if (parseInt(type) == 0) {
        appid = constant.WX_WEB_OPEN_APPID;
        appsecret = constant.WX_WEB_OPEN_APPSECRET;
    } else {
        appid = constant.WX_OPEN_APPID;
        appsecret = constant.WX_OPEN_APPSECRET;
    }
    AV.Cloud.httpRequest({
        method: 'GET',
        url: 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' + appid + '&secret=' + appsecret + '&code=' + code + '&grant_type=authorization_code',
        success: function (httpResponse) {
            var data = JSON.parse(httpResponse.data)
            var access_token = data.access_token;
            var openid = data.openid;
            //获取unionid
            AV.Cloud.httpRequest({
                method: 'GET',
                url: 'https://api.weixin.qq.com/sns/userinfo?access_token=' + access_token + '&openid=' + openid,
                success: function (httpResponse) {
                    var data = JSON.parse(httpResponse.data)
                    data.access_token = access_token
                    res.send({
                        'code': 0,
                        'data': data
                    })
                },
                error: function (httpResponse) {
                    res.error({
                        "code": httpResponse.status,
                        "message": httpResponse.data.error + httpResponse.data.error_description
                    });
                }
            });

        },
        error: function (httpResponse) {
            res.error({
                "code": httpResponse.status,
                "message": httpResponse.data.error + httpResponse.data.error_description
            });
        }
    });
}

结语:

这里有一个梗,微信用户在不同平台的openId是不一样的,这里就要注意了,如果您要使用网页第三方登录和微信客户端授权登录,是两个应用,同一用户的openId是不一样的,你可以和我们一样使用unionid来生成用户和登录,这样就不会有太多的问题了,否则产生两个用户。

不过还有一种方式是只用公众号授权方式,典型的是石墨文档,想了解的朋友可以去体验下是怎么实现的,有空可以把这个改成那种方式,体验可能更好一些吧。

ITDogFire –sky

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在Vue 3和Koa中实现第三方登录(比如微信扫码)的过程如下: 1. 创建Vue 3项目:首先,你需要创建一个Vue 3项目。你可以使用Vue CLI来创建一个新的Vue项目,执行以下命令: ``` vue create my-project ``` 按照提示进行配置选择,并等待项目创建完成。 2. 安装依赖:进入到项目目录,执行以下命令安装相关的依赖: ``` cd my-project npm install axios vue-axios ``` 3. 创建登录页面:在Vue项目中创建一个登录页面,可以使用Vue的单文件组件来实现。在你的Vue项目中的`src/views`目录下,创建一个名为`Login.vue`的文件,并添加以下代码: ```html <template> <div> <h2>第三方登录</h2> <div v-if="!isLogged"> <button @click="wechatLogin">微信扫码登录</button> </div> <div v-else> <p>登录成功!</p> <p>{{ userInfo }}</p> </div> </div> </template> <script> import axios from 'axios'; export default { data() { return { isLogged: false, userInfo: null, }; }, methods: { wechatLogin() { // 发起微信扫码登录请求 axios.get('/api/wechat/login').then(response => { // 处理登录成功后的逻辑 if (response.data.success) { this.isLogged = true; this.userInfo = response.data.userInfo; } }).catch(error => { console.error(error); }); }, }, }; </script> ``` 4. 创建Koa后端:接下来,你需要创建一个Koa后端来处理微信扫码登录的逻辑。在项目根目录下,创建一个名为`server.js`的文件,并添加以下代码: ```javascript const Koa = require('koa'); const Router = require('koa-router'); const axios = require('axios'); const app = new Koa(); const router = new Router(); // 处理微信扫码登录的路由 router.get('/api/wechat/login', async (ctx, next) => { try { // 生成一个随机的state参数 const state = Math.random().toString(36).substr(2); ctx.cookies.set('state', state); // 将state存储在cookie中 // 构造微信扫码登录的URL const wechatLoginUrl = `https://wechat.example.com/login?appid=YOUR_APPID&redirect_uri=${encodeURIComponent('http://your-domain.com/api/wechat/callback')}&state=${state}`; ctx.body = { success: true, wechatLoginUrl, }; } catch (error) { console.error(error); ctx.body = { success: false, error: 'Failed to initiate WeChat login', }; } }); // 处理微信扫码登录回调的路由 router.get('/api/wechat/callback', async (ctx, next) => { try { const { state, code } = ctx.query; const storedState = ctx.cookies.get('state'); // 从cookie中获取之前存储的state if (state === storedState) { // 校验state参数是否正确 // 发起获取access_token和openid的请求 const response = await axios.get(`https://wechat.example.com/access_token?appid=YOUR_APPID&secret=YOUR_SECRET&code=${code}&grant_type=authorization_code`); const { access_token, openid } = response.data; // 获取用户信息的请求 const userInfoResponse = await axios.get(`https://wechat.example.com/userinfo?access_token=${access_token}&openid=${openid}`); const userInfo = userInfoResponse.data; // 这里可以将用户信息存储到数据库或进行其他操作 // ... // 返回用户信息给前端 ctx.body = { success: true, userInfo, }; } else { ctx.body = { success: false, error: 'Invalid state parameter', }; } } catch (error) { console.error(error); ctx.body = { success: false, error: 'Failed to handle WeChat login callback', }; } }); app.use(router.routes()); app.listen(3000, () => { console.log('Server is running on http://localhost:3000'); }); ``` 上述代码中,需要将`YOUR_APPID`和`YOUR_SECRET`替换为你自己的微信开放平台的App ID和App Secret。 5. 启动应用:在项目根目录下,执行以下命令启动应用: ``` node server.js ``` 6. 访问登录页面:在浏览器中访问`http://localhost:3000`,你将看到一个点击按钮。点击按钮后,将会发起微信扫码登录的请求,然后跳转到微信扫码页面进行登录登录成功后,将会返回用户信息并显示在页面上。 以上就是使用Vue 3和Koa实现微信扫码登录的简单案例。请根据实际情况修改代码,并替换其中的具体参数和URL。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值