Google APIs
Google APIs 是一个用于集成 Google 服务的工具包,目前支持 Google OAuth2 认证和 reCAPTCHA 验证。
特性
- 支持 Google OAuth2 认证
- 支持 reCAPTCHA 验证
- 提供完整的 TypeScript 类型支持
- 基于官方的 Google APIs 客户端库
安装
npm install @kazura/googleapis
使用方法
Google OAuth2
import { GoogleOAuth2 } from '@kazura/googleapis'
// 创建 OAuth2 客户端
const oauth2 = new GoogleOAuth2({
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
redirectUri: 'your-redirect-uri',
})
// 生成认证 URL
const authUrl = oauth2.generateAuthUrl({
scope: ['profile', 'email'],
access_type: 'offline',
})
// 获取用户信息
const userInfo = await oauth2.getUserInfo({
code: 'authorization-code',
})
Google reCAPTCHA
import { GoogleCaptcha } from '@kazura/googleapis'
// 创建 reCAPTCHA 验证器
const captcha = new GoogleCaptcha('your-secret-key')
// 验证 token
const result = await captcha.verify('user-response-token', 'user-ip-address')
if (result.success) {
console.log('验证成功')
} else {
console.log('验证失败:', result['error-codes'])
}
API 参考
GoogleOAuth2
构造函数
constructor(options: OAuth2ClientOptions)
参数:
options
: OAuth2 客户端配置clientId
: 客户端 IDclientSecret
: 客户端密钥redirectUri
: 重定向 URI
方法
generateAuthUrl
generateAuthUrl(opts?: GenerateAuthUrlOpts): string
生成 OAuth2 认证 URL。
参数:
opts
: 认证 URL 生成选项scope
: 请求的权限范围access_type
: 访问类型prompt
: 提示类型- 其他选项...
返回值:
- 认证 URL 字符串
getUserInfo
async getUserInfo(options: GetTokenOptions): Promise<UserInfo>
获取用户信息。
参数:
options
: 获取令牌的选项code
: 授权码redirect_uri
: 重定向 URI
返回值:
- 用户信息对象
GoogleCaptcha
构造函数
constructor(secret: string)
参数:
secret
: reCAPTCHA 密钥
方法
verify
async verify(token: string, remoteip?: string): Promise<VerifyResponse>
验证 reCAPTCHA token。
参数:
token
: 用户响应 tokenremoteip
: 用户 IP 地址(可选)
返回值:
- 验证响应对象
success
: 是否验证成功challenge_ts
: 挑战时间戳hostname
: 主机名error-codes
: 错误代码数组(如果验证失败)