怎麼進行微博第三方登入?以下這篇文章跟大家介紹一下使用node實作微博第三方登入的方法,希望對大家有幫助!

接入微博第三方登入可以免註冊,對用戶的體驗更好,今天我們就用nodejs實現微博第三方登入(用其它語言也可以)。 【相關教學推薦:nodejs影片教學】
實作效果
線上實例: http://www. lolmbbs.com/login
1、點選微博登入按鈕登入

#2、直接掃碼登入
具體實現
一、申請weibo網站存取
登入https://open.weibo.com/connect申請web網站存取
本機開發的時候應用程式位址寫入:127.0.0.1



#二、點選按鈕微博登入
採用OAuth2.0授權,詳細可參考文件https://open.weibo.com/wiki/Connect/login
1. 產生微博登入授權驗證碼appKey: 建立應用程式成功後weibo給你的appKey
redirectUrl: 使用者授權成功後跳轉的你的前端頁面,我這裡寫的是http://127.0.0.1:8080/login
2. 授權頁面跳到,取得使用者code
##使用者授權登入後,會跳到你上一步寫的redirectUrl,並帶上使用者code,url類似http://127.0.0.1:8080/login?code=abcdef
vue監聽路由url,如果url上有code就去請求後端的登入回調介面
1 2 3 4 5 6 7 8 9 10 11 12 13 | created() {
const { code } = this. $route .query;
if (code) {
loginCallback({ code }).then((res) => {
this. $message ({
message: `${res.nickname} 欢迎您`,
type: "success" ,
});
this.setUser(res);
this. $router .push( "/tool/qr" );
});
}
}
|
登入後複製
3. 後端登入回呼接口,透過使用者code取得accessToken,再透過accessToken取得使用者資訊,完成登入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | async loginCallback(ctx) {
let { code } = ctx.request.body
if (!code) {
return ctx.error(errCode.PARAMS_ERROR, '参数错误')
}
const { access_token, uid } = await got.post('https:
form: {
client_id: weiboConfig.appKey,
client_secret: weiboConfig.appSecret,
grant_type: 'authorization_code',
redirect_uri: weiboConfig.redirectUrl,
code
}
}).json()
const { id, name: nickname, avatar_hd: avatar } = await got.get(`https:
let [user, isCreate] = await WeiboUser.upsert({ id, nickname, avatar })
const token = await jwt.createToken({ ...user.toJSON(), userType: 'weiboUser' })
return ctx.success({ nickname, avatar, token })
}
|
登入後複製
三、微博掃碼登入
1. 產生微博掃碼登入二維碼
1 2 3 4 5 | async getWeiboLoginQr(ctx) {
const qrApi = `https:
const { url, vcode } = await got.get(qrApi).json()
return ctx.success({ weiboQrUrl: url, vcode })
}
|
登入後複製
###回傳的url就是微博登入二維碼url,vcode相當於此二維碼唯一標識,用來查詢使用者是否掃碼######2. 前端不停輪詢,查詢此二維碼是否被掃碼授權######前端:###
1 2 3 4 5 6 7 8 9 | const id = setInterval(() => {
getWeiboLoginQrStatus({ vcode }).then((res) => {
const { status, url } = res;
if (status === "3" ) {
window.location = url;
clearInterval(id);
}
});
}, 3000);
|
登入後複製
###後端:###
1 2 3 4 5 6 7 8 9 | async getWeiboLoginQrStatus(ctx) {
const { vcode } = ctx.request.query
if (!vcode) {
return ctx.error(errCode.PARAMS_ERROR, '参数错误')
}
const queryQrApi = `https:
const { status, url } = await got(queryQrApi).json()
return ctx.success({ status, url })
}
|
登入後複製
###如果status為3,程式碼使用者已經掃碼授權了,同時回傳的url即點擊按鈕登入後的前端回呼url。之後的步驟就跟2. 授權頁面跳轉,獲取用戶code一模一樣了.######更多node相關知識,請訪問:###nodejs 教程###! ###
以上是淺析node怎麼進行微博第三方登錄的詳細內容。更多資訊請關注PHP中文網其他相關文章!