微信首页登录html页面,H5页面接入微信授权登录和分享
前期準備
接入微信授權
分靜默授權和非靜默授權兩種
靜默授權: scope=snsapi_base,沒有彈窗,只能獲取用戶的openId。
非靜默授權: scope=snsapi_userinfo,有彈框彈出需要用戶手動點擊確認授權。可以獲取openId,用戶的頭像、昵稱等
授權步驟如下:
判斷URL有沒有code
有是已經授權,無是未授權
未授權,跳轉微信授權鏈接 這里采用靜默授權
https://open.weixin.qq.com/connect/oauth2/authorize?appid=${DefaultConfig.appId}&redirect_uri=${url}&response_type=code&scope=${DefaultConfig.loginWay}&state=#wechat_redirect
注意: redirect_uri是授權成功,跳轉的地址,微信會幫我們跳轉到該鏈接,并且通過?的形式拼接code
本地開發測試,在測試公眾號的網頁授權回調配置 當前電腦的IP就行了
function login() {
let url = encodeURIComponent(DefaultConfig.redirectUriWx); // 注意一定要encodeURIComponent
window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${DefaultConfig.appId}&redirect_uri=${url}&response_type=code&scope=${DefaultConfig.loginWay}&state=#wechat_redirect`
}
跳轉url.jpg
實現微信分享
1、后端需要實現對簽名的獲取
2、前端在頁面初始化完畢的時候加載微信sdk的配置就行了
// 請求后端拿到簽名
let wxConfig = await getWXSignature(encodeURIComponent(window.location.href.split('#')[0]))
let shareInfo = await getShareInfo()
// 更新配置
wx.config({
debug: false,
appId: DefaultConfig.appId,
timestamp: wxConfig.data.data.timestamp,
nonceStr: wxConfig.data.data.noncestr,
signature: wxConfig.data.data.signature,
jsApiList: [
'updateAppMessageShareData', // 分享給朋友
'updateTimelineShareData' // 朋友圈
]
});
wx.error(() => {
// console.log(66644)
})
wx.ready(function () { //需在用戶可能點擊分享按鈕前就先調用
wx.updateAppMessageShareData({
title: shareInfo.data.data.title, // 分享標題
desc: shareInfo.data.data.desc, // 分享描述
link: DefaultConfig.shareLink, // 分享鏈接,該鏈接域名或路徑必須與當前頁面對應的公眾號JS安全域名一致
imgUrl: shareInfo.data.data.imageUrl, // 分享圖標
success: function () {
}
})
wx.updateTimelineShareData({
title: shareInfo.data.data.title,
link: DefaultConfig.shareLink,
imgUrl: shareInfo.data.data.imageUrl,
success: function () {
}
})
});
在測試公眾號的網頁的js接口安全域名配置如下
域名.jpg
線上配置 貼圖
online.jpg
跳轉到小程序
頁面可投放到小程序(具體咋弄沒研究過)
項目有個購買鏈接,如果是微信分享打開就跳轉到H5購買頁,小程序打開就直接跳轉小程序購買頁
// 小程序環境
export function isMiniProgram() {
let win: any = window
return (navigator.userAgent.match(/micromessenger/i) && navigator.userAgent.match(/miniprogram/i)) || win.__wxjs_environment === 'miniprogram';
}
// iPhone環境
export function isIPhone() {
let userAgent = window.navigator.userAgent
return userAgent.includes('iPhone') && /MicroMessenger/i.test(userAgent)
}
// ==========================================
// 判斷是否是小程序環境
if (isMiniProgram()) {
// 具體地址和鏈接形式,找負責小程序的相關同志去要
let url = `/main/webview/index?link=${encodeURIComponent(購買鏈接)}`
// 跳轉主要是這個api
wx.miniProgram.navigateTo({url})
} else {
window.location.href = 購買鏈接
}
錯誤處理
63002,invalid signature
先把后端返回來的簽名復制到微信 JS 接口簽名校驗工具,看看后端生成的簽名是否正確
仔細檢查一下js接口安全域名是不是配對了
比如,不需要帶http https 、 測試開發賬號配置沒有加自己的端口號等錯誤
the permission value is offline verifying
表現是分享的鏈接 圖片都沒起效果
官網上說 access_token的有效期目前為2個小時,需定時刷新, 有可能是后端忘了刷新導致token失效
或者 后端提早刷新了導致前一個分享出錯(等2個小時就好了....)
總結
以上是生活随笔為你收集整理的微信首页登录html页面,H5页面接入微信授权登录和分享的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 火狐浏览器(69版)修改起始页,主页和新
- 下一篇: 阿里自然语言处理部总监分享:NLP技术的