PayPal을 연동하려는 개발자들이 흔히 겪는 문제가 있다. API 문서는 많지만 실제로 PHP에서 동작하는 완전한 예제를 찾기 어렵고, OAuth 토큰 발급 단계에서 막히거나 결제 승인 과정에서 401/403 인증 오류를 만난다. 더군다나 환불이나 거래 조회 같은 추가 기능까지 필요하면 각각의 엔드포인트를 일일이 찾아야 하는 번거로움이 있다.
이번에는 PayPal REST API를 PHP cURL로 연동하는 완벽한 방법을 정리했다. OAuth 2.0 기반 토큰 발급부터 결제 생성, 승인, 환불까지 모든 단계를 실제 코드와 함께 소개하고, 흔한 오류와 해결책도 함께 담았다.
PayPal REST API란 무엇인가
PayPal REST API는 PayPal 샌드박스 또는 라이브 환경에서 결제를 프로그래밍 방식으로 처리할 수 있게 해주는 서비스다. 가장 큰 특징은 OAuth 2.0 인증을 사용한다는 것이다. API 호출 전에 Client ID와 Client Secret을 사용해 접근 토큰(Access Token)을 먼저 받아야 하고, 이후 모든 요청에 이 토큰을 포함시켜야 한다.
결제 플로우는 단순하다. 먼저 결제 주문을 생성하고(CREATE), 사용자가 PayPal 로그인 화면을 통해 승인한 후(APPROVE), 최종적으로 결제를 실행(EXECUTE)하는 세 단계를 거친다. 토큰만 제대로 발급받으면 나머지는 HTTP 요청만으로 충분하다.
1단계. PayPal 샌드박스 계정 설정 및 인증 정보 발급받기
PayPal 개발자 대시보드에서 App 생성하면 Client ID와 Client Secret을 얻을 수 있다. 이 두 정보를 Base64로 인코딩해서 Authorization 헤더에 담아 토큰을 요청하는 방식이다.
필요한 정보
- Client ID: PayPal 앱 고유 식별자
- Client Secret: 토큰 발급용 비밀 키
- Sandbox URL: https://api-m.sandbox.paypal.com (테스트 환경)
- Live URL: https://api-m.paypal.com (실운영 환경)
2단계. OAuth 2.0 토큰 발급 받기
PayPal API를 사용하려면 먼저 액세스 토큰을 발급받아야 한다. 이 토큰은 1시간 동안 유효하므로, 필요할 때마다 새로 받거나 캐싱해서 재사용하는 게 좋다.
✗ 잘못된 코드: 토큰 없이 바로 결제 요청
<?php
$clientId = 'your_client_id';
$clientSecret = 'your_client_secret';
$ch = curl_init('https://api-m.sandbox.paypal.com/v1/oauth2/token');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=client_credentials');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
echo $response; // Authorization 헤더 없어서 401 Unauthorized 에러 발생
?>
✓ 올바른 코드: Basic Auth로 토큰 발급
<?php
$clientId = 'your_client_id';
$clientSecret = 'your_client_secret';
$sandboxUrl = 'https://api-m.sandbox.paypal.com';
// Basic Authentication 헤더 생성
$authHeader = 'Authorization: Basic ' . base64_encode($clientId . ':' . $clientSecret);
$ch = curl_init($sandboxUrl . '/v1/oauth2/token');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=client_credentials');
curl_setopt($ch, CURLOPT_HTTPHEADER, [$authHeader]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
$response = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($statusCode === 200) {
$tokenData = json_decode($response, true);
$accessToken = $tokenData['access_token'];
$expiresIn = $tokenData['expires_in']; // 보통 3600초(1시간)
echo "액세스 토큰: " . $accessToken;
} else {
echo "토큰 발급 실패: " . $response;
}
?>
결과
{
"scope": "https://api.paypal.com/v1/payments/.*",
"access_token": "A21AAJKz8e9...",
"token_type": "Bearer",
"app_id": "APP-...",
"expires_in": 3600
}
이 액세스 토큰을 이용해 이후의 모든 PayPal API 요청에 사용한다.
3단계. 결제 주문 생성하기
토큰을 획득한 후 실제 결제 주문을 생성한다. 이 단계에서는 상품 정보, 가격, 통화, 환불 URI 등을 지정한다.
✗ 잘못된 코드: intent 지정 누락
<?php
$accessToken = 'A21AAJKz8e9...';
$sandboxUrl = 'https://api-m.sandbox.paypal.com';
$orderData = [
'purchase_units' => [
[
'amount' => [
'currency_code' => 'USD',
'value' => '100.00'
],
'description' => 'Sample Product'
]
]
];
$ch = curl_init($sandboxUrl . '/v2/checkout/orders');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($orderData));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $accessToken,
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
echo $response; // intent가 없어서 400 Bad Request 발생
?>
✓ 올바른 코드: intent와 return URL 포함
<?php
$accessToken = 'A21AAJKz8e9...';
$sandboxUrl = 'https://api-m.sandbox.paypal.com';
$orderData = [
'intent' => 'CAPTURE', // CAPTURE 또는 AUTHORIZE
'purchase_units' => [
[
'amount' => [
'currency_code' => 'USD',
'value' => '100.00'
],
'description' => 'Sample Product'
]
],
'payment_source' => [
'paypal' => [
'experience_context' => [
'return_url' => 'https://yoursite.com/paypal/return.php',
'cancel_url' => 'https://yoursite.com/paypal/cancel.php'
]
]
]
];
$ch = curl_init($sandboxUrl . '/v2/checkout/orders');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($orderData));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $accessToken,
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
$response = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($statusCode === 201) {
$orderData = json_decode($response, true);
$orderId = $orderData['id'];
$approveLink = $orderData['links'][0]['href']; // 사용자를 이 URL로 리다이렉트
echo "주문 ID: " . $orderId;
echo "승인 링크: " . $approveLink;
} else {
echo "주문 생성 실패: " . $response;
}
?>
결과
{
"id": "5O190127TN364715T",
"status": "CREATED",
"links": [
{
"rel": "approve",
"href": "https://www.sandbox.paypal.com/checkoutnow?token=EC-5O190127TN364715T"
},
{
"rel": "self",
"href": "https://api-m.sandbox.paypal.com/v2/checkout/orders/5O190127TN364715T"
}
]
}
4단계. 결제 승인 처리 및 결제 실행
사용자가 PayPal 로그인 화면에서 승인한 후 돌아오면, 반환된 주문 ID로 최종 결제를 실행한다.
✓ 올바른 코드: 주문 승인 후 최종 결제 실행
<?php
// return.php에서 처리
$orderId = $_GET['token']; // PayPal에서 반환된 토큰(주문 ID)
$accessToken = 'A21AAJKz8e9...'; // 별도로 재발급받거나 세션에서 로드
$sandboxUrl = 'https://api-m.sandbox.paypal.com';
// 주문 정보 조회 (선택사항)
$ch = curl_init($sandboxUrl . '/v2/checkout/orders/' . $orderId);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $accessToken,
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$orderDetails = json_decode(curl_exec($ch), true);
curl_close($ch);
echo "주문 상태: " . $orderDetails['status']; // APPROVED 상태여야 함
// 최종 결제 실행 (CAPTURE)
$captureData = [];
$ch = curl_init($sandboxUrl . '/v2/checkout/orders/' . $orderId . '/capture');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($captureData));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $accessToken,
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
$response = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($statusCode === 201) {
$captureData = json_decode($response, true);
$status = $captureData['status'];
$captureId = $captureData['purchase_units'][0]['payments']['captures'][0]['id'];
if ($status === 'COMPLETED') {
echo "결제 성공! 거래 ID: " . $captureId;
// DB에 주문 저장
}
} else {
echo "결제 실행 실패: " . $response;
}
?>
5단계. 환불 처리하기
이미 실행된 거래를 환불해야 할 때는 Refund API를 사용한다. 거래 ID(Capture ID)가 필요하다.
✓ 올바른 코드: 거래 환불
<?php
$captureId = '3C679366HH908154H'; // 위의 결제 실행 단계에서 얻은 Capture ID
$accessToken = 'A21AAJKz8e9...';
$sandboxUrl = 'https://api-m.sandbox.paypal.com';
$refundData = [
'amount' => [
'currency_code' => 'USD',
'value' => '50.00' // 부분 환불. 전체 환불시 이 필드 생략 가능
],
'note_to_payer' => 'Refund for order #12345'
];
$ch = curl_init($sandboxUrl . '/v2/payments/captures/' . $captureId . '/refund');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($refundData));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $accessToken,
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
$response = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($statusCode === 201) {
$refundData = json_decode($response, true);
$refundId = $refundData['id'];
$refundStatus = $refundData['status'];
if ($refundStatus === 'SUCCESS') {
echo "환불 성공! 환불 ID: " . $refundId;
}
} else {
echo "환불 실패: " . $response;
}
?>
주의사항 및 흔한 실수
| 문제 | 원인 | 해결책 |
|---|---|---|
| 401 Unauthorized | Authorization 헤더 누락 또는 잘못된 토큰 | Base64 인코딩된 Client ID:Secret을 'Authorization: Basic' 형태로 정확히 전달 |
| 400 Bad Request | JSON 형식 오류 또는 필수 필드 누락 | intent, purchase_units, payment_source 필드 필수. JSON 유효성 검증 |
| 토큰 만료 후 API 호출 실패 | 1시간 유효한 토큰을 계속 사용 | expires_in 필드를 저장하고 필요시 새 토큰 발급. Redis 등으로 토큰 캐싱 |
| 환불 불가 (거래 ID 불일치) | 잘못된 Capture ID 사용 | 주문 조회 API로 정확한 Capture ID 확인 후 환불 요청 |
| SSL certificate error (cURL Error 60) | SSL 인증서 검증 문제 | CURLOPT_SSL_VERIFYPEER를 true로 유지하되, CA 인증서 경로 확인 |
실전 예제: 완전한 결제 플로우를 한 클래스로 구현
<?php
class PayPalGateway {
private $clientId;
private $clientSecret;
private $sandboxUrl = 'https://api-m.sandbox.paypal.com';
private $accessToken;
private $tokenExpiry;
public function __construct($clientId, $clientSecret) {
$this->clientId = $clientId;
$this->clientSecret = $clientSecret;
}
// 토큰 발급 및 캐싱
private function getAccessToken() {
if ($this->accessToken && time() < $this->tokenExpiry) {
return $this->accessToken;
}
$authHeader = 'Authorization: Basic ' . base64_encode($this->clientId . ':' . $this->clientSecret);
$ch = curl_init($this->sandboxUrl . '/v1/oauth2/token');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=client_credentials');
curl_setopt($ch, CURLOPT_HTTPHEADER, [$authHeader]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
$response = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($statusCode === 200) {
$tokenData = json_decode($response, true);
$this->accessToken = $tokenData['access_token'];
$this->tokenExpiry = time() + ($tokenData['expires_in'] - 60); // 60초 마진
return $this->accessToken;
}
throw new Exception('Failed to get access token: ' . $response);
}
// 주문 생성
public function createOrder($amount, $currency = 'USD', $description = '') {
$token = $this->getAccessToken();
$orderData = [
'intent' => 'CAPTURE',
'purchase_units' => [
[
'amount' => [
'currency_code' => $currency,
'value' => number_format($amount, 2, '.', '')
],
'description' => $description
]
],
'payment_source' => [
'paypal' => [
'experience_context' => [
'return_url' => 'https://yoursite.com/paypal/return.php',
'cancel_url' => 'https://yoursite.com/paypal/cancel.php'
]
]
]
];
$ch = curl_init($this->sandboxUrl . '/v2/checkout/orders');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($orderData));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $token,
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
$response = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($statusCode === 201) {
return json_decode($response, true);
}
throw new Exception('Failed to create order: ' . $response);
}
// 결제 실행
public function captureOrder($orderId) {
$token = $this->getAccessToken();
$ch = curl_init($this->sandboxUrl . '/v2/checkout/orders/' . $orderId . '/capture');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([]));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $token,
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
$response = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($statusCode === 201) {
return json_decode($response, true);
}
throw new Exception('Failed to capture order: ' . $response);
}
// 환불
public function refundCapture($captureId, $amount = null) {
$token = $this->getAccessToken();
$refundData = [];
if ($amount) {
$refundData['amount'] = [
'currency_code' => 'USD',
'value' => number_format($amount, 2, '.', '')
];
}
$ch = curl_init($this->sandboxUrl . '/v2/payments/captures/' . $captureId . '/refund');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($refundData));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $token,
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
$response = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($statusCode === 201) {
return json_decode($response, true);
}
throw new Exception('Failed to refund: ' . $response);
}
}
// 사용 예제
try {
$gateway = new PayPalGateway('YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET');
// 1. 주문 생성
$orderResult = $gateway->createOrder(100.00, 'USD', 'Premium Subscription');
$orderId = $orderResult['id'];
$approveUrl = $orderResult['links'][0]['href'];
// 사용자를 $approveUrl로 리다이렉트
// 2. 사용자 승인 후 결제 실행
$captureResult = $gateway->captureOrder($orderId);
$captureId = $captureResult['purchase_units'][0]['payments']['captures'][0]['id'];
// 3. 필요시 환불
// $gateway->refundCapture($captureId, 50.00);
} catch (Exception $e) {
echo "에러: " . $e->getMessage();
}
?>
마무리
PayPal REST API는 복잡해 보이지만 OAuth 토큰 발급 단계만 제대로 이해하면 나머지는 단순한 HTTP 요청일 뿐이다. 토큰을 캐싱하고, 각 엔드포인트의 필수 필드를 정확히 채우면 401/403 같은 인증 오류는 대부분 해결된다. 이 글의 PayPalGateway 클래스를 프로젝트에 맞게 커스터마이징하면, 복잡한 결제 처리도 간단하게 통합할 수 있을 것이다.