萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 實現 PayPal OAuth 授權登入完整範例

前言

PayPal 登入(Log In with PayPal)基於 OpenID Connect 協議,可快速獲取用戶授權資料(郵箱、姓名、地址等)。本文提供一個開箱即用的 PHP 類別,支援沙箱/正式環境切換、授權碼換取 Access Token、獲取用戶資訊。

一、核心類別結構

class PayPalLogin {
    // 沙箱/正式環境端點
    private $authEndpoints = [
        'sandbox' => 'https://www.sandbox.paypal.com/webapps/auth/protocol/openidconnect/v1/authorize',
        'live'    => 'https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/authorize'
    ];
    private $tokenEndpoints = [
        'sandbox' => 'https://www.sandbox.paypal.com/webapps/auth/protocol/openidconnect/v1/tokenservice',
        'live'    => 'https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/tokenservice'
    ];
    private $userInfoEndpoints = [
        'sandbox' => 'https://www.sandbox.paypal.com/webapps/auth/protocol/openidconnect/v1/userinfo?schema=openid',
        'live'    => 'https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/userinfo?schema=openid'
    ];

    private $clientId;
    private $clientSecret;
    private $redirectUri;
    private $scope = 'openid email profile address phone https://uri.paypal.com/services/paypalattributes';
    private $state;
    private $sandbox = true;

    public function __construct($redirectUri, $clientId, $clientSecret, $scope = '', $state = '', $sandbox = true) {
        $this->redirectUri  = $redirectUri;
        $this->clientId     = $clientId;
        $this->clientSecret = $clientSecret;
        $this->sandbox      = $sandbox;
        $this->scope        = $scope ?: $this->scope;
        $this->state        = $state ?: bin2hex(random_bytes(16)); // CSRF 防護
    }

二、生成授權跳轉 URL

public function getAuthUrl() {
    $endpoint = $this->sandbox ? $this->authEndpoints['sandbox'] : $this->authEndpoints['live'];
    $params = [
        'client_id'     => $this->clientId,
        'response_type' => 'code',
        'scope'         => $this->scope,
        'redirect_uri'  => $this->redirectUri,
        'state'         => $this->state,
        'nonce'         => bin2hex(random_bytes(16)),
    ];
    return $endpoint . '?' . http_build_query($params);
}

將用戶導向此 URL,用戶登入並授權後,PayPal 會攜帶 code 與 state 重定向回 redirect_uri。

三、用授權碼換取 Access Token

public function getAccessToken($code) {
    $endpoint = $this->sandbox ? $this->tokenEndpoints['sandbox'] : $this->tokenEndpoints['live'];
    $postData = http_build_query([
        'grant_type'    => 'authorization_code',
        'code'          => $code,
        'client_id'     => $this->clientId,
        'client_secret' => $this->clientSecret,
    ]);

    $ch = curl_init($endpoint);
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => $postData,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false, // 生產環境請設 true 並配置 CA 憑證
        CURLOPT_HTTPHEADER     => ['Accept: application/json', 'Content-Type: application/x-www-form-urlencoded'],
    ]);
    $response = curl_exec($ch);
    if (curl_errno($ch)) throw new Exception('cURL 錯誤: ' . curl_error($ch));
    curl_close($ch);

    $data = json_decode($response, true);
    if (empty($data['access_token'])) throw new Exception('獲取 Access Token 失敗: ' . ($data['error_description'] ?? $response));
    return $data['access_token'];
}

四、獲取用戶資訊

public function getUserInfo($accessToken) {
    $endpoint = $this->sandbox ? $this->userInfoEndpoints['sandbox'] : $this->userInfoEndpoints['live'];
    $url = $endpoint . '&access_token=' . urlencode($accessToken);

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_HTTPHEADER     => ['Authorization: Bearer ' . $accessToken],
    ]);
    $response = curl_exec($ch);
    curl_close($ch);
    return json_decode($response, true); // 含 user_id, email, name, address 等
}

五、完整使用流程範例

$paypal = new PayPalLogin(
    'https://example.com/callback.php',
    'YOUR_CLIENT_ID',
    'YOUR_CLIENT_SECRET',
    '', // 使用預設 scope
    '', // 自動生成 state
    true // 沙箱環境
);

// 步驟 1:導向授權頁
// header('Location: ' . $paypal->getAuthUrl());
// exit;

// 步驟 2:回調頁處理
if (isset($_GET['code'], $_GET['state'])) {
    // 驗證 state 防 CSRF
    if ($_GET['state'] !== $_SESSION['paypal_state']) {
        die('State 不匹配,可能遭 CSRF 攻擊');
    }
    try {
        $token = $paypal->getAccessToken($_GET['code']);
        $user  = $paypal->getUserInfo($token);
        // $user['user_id'] 為 PayPal 唯一標識,可綁定本地用戶表
        var_dump($user);
    } catch (Exception $e) {
        echo '錯誤: ' . $e->getMessage();
    }
}

六、安全與最佳實踐提醒

  • State 參數:必須在 Session 中保存並驗證,防禦 CSRF。
  • Nonce 參數:防重放攻擊,建議每次請求生成隨機值並存入 Session 驗證。
  • SSL 驗證:生產環境務必開啟 CURLOPT_SSL_VERIFYPEER 並配置有效 CA 憑證路徑。
  • Token 儲存:Access Token 有效期約 1 小時,若需長期調用 API 請儲存 Refresh Token(PayPal 目前不直接提供,需重新授權)。
  • Scope 原則:最小權限原則,僅申請業務必要的範圍。

結語

以上類別已在實際項目中驗證可用,涵蓋從授權跳轉到獲取用戶資料的完整閉環。可根據項目需求擴展錯誤重試、日誌記錄、多語言支援等功能。

copyright © 萬盛學電腦網 all rights reserved