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 防護
}
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。
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();
}
}
CURLOPT_SSL_VERIFYPEER 並配置有效 CA 憑證路徑。以上類別已在實際項目中驗證可用,涵蓋從授權跳轉到獲取用戶資料的完整閉環。可根據項目需求擴展錯誤重試、日誌記錄、多語言支援等功能。