生活随笔
收集整理的這篇文章主要介紹了
微信—前端获取openId方法和步骤
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
執(zhí)行流程
前端 --> 后端服務(wù) --> 微信服務(wù)(openId/UnionID)
微信公眾號網(wǎng)頁開發(fā)授權(quán):https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html#0
<template
><div
></div
>
</template
><script
>
export default
{name:
'Index',
data () {return {}},
created () {this.getCode
()},// ***放main.js中;放入口文件中methods:
{getCode () { // 非靜默授權(quán),第一次有彈框const code
= getUrlParam
('code') // 截取路徑中的code,如果沒有就去微信授權(quán),如果已經(jīng)獲取到了就直接傳code給后臺獲取openIdconst
local = window.location.href
if (code
== null
|| code
=== '') {window.location.href
= 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + window.APPID +
'&redirect_uri=' + encodeURIComponent
(local
) +
'&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect'} else {this.getOpenId
(code
) //把code傳給后臺獲取用戶信息
}},getOpenId
(code
) { // 通過code獲取 openId等用戶信息,/api/user/wechat/login 為后臺接口
let _this
= this// 后端接口實現(xiàn):獲取code后,請求以下連接獲取access_token: https://api.weixin.qq.com/sns/oauth2/access_token?appid
=APPID
&secret=SECRET
&code=CODE
&grant_type=authorization_codethis.
$http.post
('/api/user/wechat/login',
{code: code
}).then
((res
) => {let datas
= res.data/* // 前端--
> 應(yīng)用后臺 --
> 微信后臺
{"access_token": "ACCESS_TOKEN",
"expires_in": 7200,
"refresh_token": "REFRESH_TOKEN",
"openid": "OPENID",
"scope": "SCOPE"}*/
if (datas.code
=== 0 ) {console.log
('成功')}}).catch
((error
) => {console.log
(error
)})},getUrlParam
(name
) { // 獲取url指定參數(shù)var reg
= new RegExp
('(^|&)' + name +
'=([^&]*)(&|$)') // 構(gòu)造一個含有目標(biāo)的正則表達式對象var r
= window.location.search.substr
(1).match
(reg
) // 匹配目標(biāo)參數(shù)
if (r
!= null
) return unescape
(r
[2])return null // 返回參數(shù)值
}}
}
</script
><style
lang="less" scoped
></style
>
微信h5靜默、非靜默授權(quán)獲取用戶openId的方法和步驟https://blog.csdn.net/qq_35430000/article/details/79299529
解決微信授權(quán)成功后點擊按返回鍵出現(xiàn)空白頁和報錯的問題https://blog.csdn.net/qq_35430000/article/details/79299529
總結(jié)
以上是生活随笔為你收集整理的微信—前端获取openId方法和步骤的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。