跳过内容

入门

  1. 安装包

    终端窗口
    bun add @capgo/capacitor-social-login
  2. 同步本地项目

    终端窗口
    bunx cap sync
  3. 在应用启动时初始化

    import { SocialLogin } from '@capgo/capacitor-social-login';
    await SocialLogin.initialize({
    google: {
    webClientId: 'your-google-web-client-id',
    iOSServerClientId: 'your-google-server-client-id',
    mode: 'online',
    },
    apple: {
    clientId: 'your-apple-service-id',
    useProperTokenExchange: true,
    useBroadcastChannel: true,
    },
    facebook: {
    appId: 'your-facebook-app-id',
    },
    twitter: {
    clientId: 'your-twitter-client-id',
    redirectUrl: 'myapp://oauth/twitter',
    },
    oauth2: {
    github: {
    appId: 'your-github-client-id',
    authorizationBaseUrl: 'https://github.com/login/oauth/authorize',
    accessTokenEndpoint: 'https://github.com/login/oauth/access_token',
    redirectUrl: 'myapp://oauth/github',
    scope: 'read:user user:email',
    pkceEnabled: true,
    },
    },
    });

核心流程示例

核心流程示例

登录

登录
await SocialLogin.login({
provider: 'google',
options: { scopes: ['profile', 'email'] },
});
await SocialLogin.login({
provider: 'oauth2',
options: {
providerId: 'github',
scope: 'read:user user:email',
},
});

会话检查

会话检查
const status = await SocialLogin.isLoggedIn({ provider: 'google' });
await SocialLogin.logout({ provider: 'google' });

授权码和刷新

授权码和刷新
// For providers that support this mode
const authCodeResult = await SocialLogin.getAuthorizationCode({ provider: 'google' });
await SocialLogin.refresh({ provider: 'google', options: {} as never });

高级辅助函数

高级辅助函数
const jwt = await SocialLogin.decodeIdToken({
idToken: 'eyJhbGciOi...',
});
const { date } = await SocialLogin.getAccessTokenExpirationDate({
accessTokenExpirationDate: Date.now() + 3600 * 1000,
});
const expired = await SocialLogin.isAccessTokenExpired({
accessTokenExpirationDate: Date.now() + 1000,
});
const active = await SocialLogin.isRefreshTokenAvailable({ refreshToken: 'a-token' });

供应商特定说明

供应商特定说明

Google 离线模式

返回

google.mode: 'offline' 在此模式下,登出,isLoggedIn,getAuthorizationCode,和refresh不可用。 serverAuthCode 仅作为后端令牌交换的输入使用。如果您需要在应用中调用,请使用

advanced helpers serverAuthCode provider-specific notes SocialLogin.refresh() Google offline mode google.mode: 'online' 而不是。

苹果

Apple

设置 useProperTokenExchange: true 用于严格令牌处理和 useBroadcastChannel: true 用于 Android 简化的设置。

OAuth2 网页重定向流

Apple

用于网页流程,页面导航。 OAuth2LoginOptions.flow: 'redirect' __CAPGO_KEEP_0__中的提供者配置

您可以禁用未使用的提供者以减少本机二进制文件:

import type { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
appId: 'com.example.app',
appName: 'My App',
webDir: 'dist',
plugins: {
SocialLogin: {
providers: {
google: true,
facebook: true,
apple: true,
twitter: false,
},
},
},
};