贝宝

获取你的 PayPal 凭证

要与 PayPal 集成,你需要通过在 PayPal 开发者门户 创建应用来获取 API 凭证。

请按照以下步骤操作:

  1. 在 PayPal 开发者门户创建一个账户
  2. 创建一个新应用,官方文档
  3. 在“其他功能”下配置 PayPal 登录
  4. 设置返回 URL(重定向 URL)
  5. 配置用户信息权限
  6. 记录你的客户端 ID 和客户端密钥
  • PayPal 有两个环境:沙盒环境(用于测试)和正式环境(用于生产)
  • 在开发者仪表板的“沙盒” → “账户”中创建沙盒测试账号以进行测试
  • 你不能使用真实的 PayPal 账户在沙盒模式下测试 - 必须使用生成的测试账户
  • PayPal 应用设置中的返回 URL 必须与你的重定向 URI 完全匹配
  • PayPal API 不支持 localhost。你需要为重定向 URL 使用公共域名,并在本地测试时使用 HTTPS。你可以使用 NGROK 或其他类似工具来实现。

确保在应用设置中配置“使用 PayPal 登录”:

  1. 在开发者仪表板中打开你的应用
  2. 在“其他功能”下勾选“使用 PayPal 登录”
  3. 点击“高级设置”
  4. 输入你的返回 URL
  5. 选择你想要访问的用户信息(电子邮件、名称等)
  6. 输入隐私政策和用户协议 URL
  • PayPal 在授权 URL 中不使用传统的 OAuth2 范围。相反,你可以直接在开发者控制台中配置权限
  • 对于正式应用,PayPal 必须审核并批准你的应用,才能上线,这通常需要几周时间

配置提供程序

要配置提供程序,你需要导入该提供程序并将其传递给身份验证实例的 socialProviders 选项。

auth.ts
import { betterAuth } from "better-auth"

export const auth = betterAuth({
    socialProviders: {
        paypal: { 
            clientId: process.env.PAYPAL_CLIENT_ID as string, 
            clientSecret: process.env.PAYPAL_CLIENT_SECRET as string, 
            environment: "sandbox", // or "live" for production //,
        }, 
    },
})

Options

The PayPal provider accepts the following options:

  • environment'sandbox' | 'live' - 要使用的 PayPal 环境(默认:'sandbox'
  • requestShippingAddressboolean - 是否请求送货地址信息(默认值:false
auth.ts
export const auth = betterAuth({
    socialProviders: {
        paypal: {
            clientId: process.env.PAYPAL_CLIENT_ID as string,
            clientSecret: process.env.PAYPAL_CLIENT_SECRET as string,
            environment: "live", // Use "live" for production
            requestShippingAddress: true, // Request address info
        },
    },
})

Sign In with PayPal

To sign in with PayPal, you can use the signIn.social function provided by the client. The signIn function takes an object with the following properties:

  • provider: The provider to use. It should be set to paypal.
auth-client.ts
import { createAuthClient } from "better-auth/client"
const authClient =  createAuthClient()

const signIn = async () => {
    const data = await authClient.signIn.social({
        provider: "paypal"
    })
}

Additional Options:

  • environment: PayPal environment to use.
    • Default: "sandbox"
    • Options: "sandbox" | "live"
  • requestShippingAddress: Whether to request shipping address information.
    • Default: false
  • scope: Additional scopes to request (combined with default permissions).
    • Default: Configured in PayPal Developer Dashboard
    • Note: PayPal doesn't use traditional OAuth2 scopes - permissions are set in the Dashboard For more details refer to the Scopes Reference
  • mapProfileToUser: Custom function to map PayPal profile data to user object.
  • getUserInfo: Custom function to retrieve user information. For more details refer to the User Reference
  • verifyIdToken: Custom ID token verification function.

On this page