修復Java多商戶外貿版V1.1版本Google登錄問題
替換如下代碼:
import Vue from 'vue'
export default Vue.directive('google-signin-button', {
bind: function(el, binding, vnode) {
CheckComponentMethods()
// 獲取 clientId 和回調方法
const clientId = binding.value
const onSuccess = vnode.context.OnGoogleAuthSuccess
const onFailure = vnode.context.OnGoogleAuthFail
// 創建 Google 登錄按鈕配置
const buttonConfig = {
type: 'standard', // 或 'icon',取決于你的設計需求
shape: 'rectangular', // 或 'circular'
theme: 'outline', // 或 'filled_blue', 'filled_black'
size: 'large', // 或 'medium', 'large'
width: 256,
text: 'signin_with', // 或 'sign_in_with', 'continue_with'
logo_alignment: 'center'
}
// 為自定義按鈕添加點擊事件
el.addEventListener('click', function() {
// 初始化 Google 登錄
InitializeGoogleLogin(clientId, onSuccess, onFailure, buttonConfig, el)
})
// 檢查組件方法
function CheckComponentMethods() {
if (!vnode.context.OnGoogleAuthSuccess) {
throw new Error('The method OnGoogleAuthSuccess must be defined on the component')
}
if (!vnode.context.OnGoogleAuthFail) {
throw new Error('The method OnGoogleAuthFail must be defined on the component')
}
}
}
})
// 初始化 Google 登錄
function InitializeGoogleLogin(clientId, onSuccess, onFailure, buttonConfig, parentElement) {
// 檢查是否已經存在 Google 身份服務腳本
if (document.getElementById('google-identity-script')) {
// 如果腳本已存在,直接初始化 Google 登錄配置
google.accounts.id.initialize({
client_id: clientId,
callback: handleCredentialResponse
})
// 渲染 Google 登錄按鈕到指定的父元素
google.accounts.id.renderButton(
parentElement,
buttonConfig
)
// 允許自動登錄(可選)
google.accounts.id.prompt()
} else {
// 創建 Google 身份服務腳本
const googleIdentityScript = document.createElement('script')
googleIdentityScript.id = 'google-identity-script'
googleIdentityScript.src = 'https://accounts.google.com/gsi/client'
googleIdentityScript.async = true
googleIdentityScript.defer = true
document.head.appendChild(googleIdentityScript)
// 腳本加載完成后初始化登錄
googleIdentityScript.onload = function() {
// 初始化 Google 登錄配置
google.accounts.id.initialize({
client_id: clientId,
callback: handleCredentialResponse
})
// 渲染 Google 登錄按鈕到指定的父元素
google.accounts.id.renderButton(
parentElement,
buttonConfig
)
// 允許自動登錄(可選)
google.accounts.id.prompt()
}
}
// 處理登錄回調
function handleCredentialResponse(response) {
try {
// 驗證 JWT 令牌(建議在后端進行驗證)
const userCredential = response.credential
onSuccess(userCredential)
} catch (error) {
onFailure(error)
}
}
}