결제 시스템을 Stripe로 연동했는데, 웹훅 이벤트가 간헐적으로 사라지거나 중복 처리되는 경험을 해봤을까. 대부분의 개발자들은 Stripe 대시보드에서 웹훅이 '전송됨'으로 표시되는데도 자신의 PHP 서버에서 받지 못하거나, 같은 이벤트를 여러 번 처리하는 문제를 겪으면서 헤맨다. 다만 정확한 원인과 해결책을 모르는 경우가 많다. 이번에는 Stripe Webhook의 동작 원리부터 PHP에서 Signature 검증하는 방법, 중복 이벤트 방지 로직까지 완벽하게 정리해서 소개하겠다.
Stripe 웹훅은 기본적으로 3가지 보안 요소를 제공한다. 첫째, 각 요청의 타임스탬프가 포함되어 있어서 시간 기반 공격을 방지할 수 있다. 둘째, 요청 본문과 타임스탬프를 조합해서 서명을 생성하므로 데이터 위변조를 감지할 수 있다. 셋째, Signing Secret을 사용해서 서명을 검증하므로 오직 Stripe만이 유효한 웹훅을 생성할 수 있다.
먼저 PHP 파일을 하나 만들어서 Stripe의 모든 웹훅을 받을 엔드포인트를 구성한다. 이 파일은 public 디렉토리에 위치해야 하고, HTTPS를 반드시 사용해야 한다.
<?php
// webhook.php - Stripe 웹훅 수신 엔드포인트
require 'vendor/autoload.php';
$endpoint_secret = 'whsec_test_your_signing_secret_here';
// 원본 요청 본문 가져오기 (Content-Type이 application/json일 때)
$input = @file_get_contents('php://input');
$sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'] ?? '';
// ✗ 잘못된 코드 예시
// 많은 개발자들이 이렇게 한다 - 검증 없이 바로 처리
$event = json_decode($input, true);
if ($event['type'] === 'payment_intent.succeeded') {
// 결제 처리...
}
echo json_encode(['status' => 'received']);
?>
위 코드는 웹훅 서명을 검증하지 않기 때문에 보안 위험이 있다. 누구나 위조된 웹훅을 보낼 수 있다.
Stripe에서 제공하는 공식 PHP 라이브러리(stripe-php)를 사용하면 자동으로 서명을 검증할 수 있다.
<?php
// webhook.php - 올바른 구현
require 'vendor/autoload.php';
$endpoint_secret = 'whsec_test_your_signing_secret_here';
$input = @file_get_contents('php://input');
$sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'] ?? '';
try {
// ✓ 올바른 코드 - Stripe에서 제공하는 메서드로 검증
$event = \Stripe\Webhook::constructEvent(
$input,
$sig_header,
$endpoint_secret
);
} catch (\UnexpectedValueException $e) {
// 잘못된 JSON 형식
http_response_code(400);
echo json_encode(['error' => 'Invalid payload']);
exit();
} catch (\Stripe\Exception\SignatureVerificationException $e) {
// 서명 검증 실패 - 위조되었거나 조작된 웹훅
http_response_code(403);
echo json_encode(['error' => 'Invalid signature']);
exit();
}
// 이제 이벤트를 안전하게 처리할 수 있다
switch ($event['type']) {
case 'payment_intent.succeeded':
handlePaymentSuccess($event['data']['object']);
break;
case 'payment_intent.payment_failed':
handlePaymentFailed($event['data']['object']);
break;
case 'charge.refunded':
handleRefund($event['data']['object']);
break;
default:
// 처리할 필요 없는 이벤트 타입
break;
}
http_response_code(200);
echo json_encode(['status' => 'received']);
?>
Stripe\Webhook::constructEvent()는 내부적으로 다음 순서로 작동한다. 첫째, 타임스탐프가 현재 시각에서 5분 이내인지 확인해서 재생 공격(Replay Attack)을 방지한다. 둘째, 요청 본문과 타임스탐프를 Signing Secret으로 HMAC-SHA256 서명한다. 셋째, 계산한 서명과 헤더의 서명을 비교해서 일치 여부를 판단한다.
만약 네트워크 지연이 심한 환경에서 5분이라는 기본 제한 시간이 너무 짧다면, 직접 검증 로직을 구성할 수 있다.
<?php
// 커스텀 타임스탐프 검증 (최대 10분까지 허용)
$input = @file_get_contents('php://input');
$sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'] ?? '';
$endpoint_secret = 'whsec_test_your_signing_secret_here';
// 헤더 파싱: "t=1614556800,v1=signature1,v1=signature2"
$timestamp = null;
$signatures = [];
foreach (explode(',', $sig_header) as $pair) {
list($key, $value) = explode('=', $pair, 2);
if ($key === 't') {
$timestamp = (int)$value;
} elseif ($key === 'v1') {
$signatures[] = $value;
}
}
// ✓ 타임스탐프 검증 (10분 허용)
$tolerance = 600; // 초 단위
if (time() - $timestamp > $tolerance) {
http_response_code(403);
echo json_encode(['error' => 'Timestamp too old']);
exit();
}
// 서명 계산
$signed_content = $timestamp . '.' . $input;
$expected_signature = hash_hmac('sha256', $signed_content, $endpoint_secret);
// 서명 비교 (타이밍 공격 방지를 위해 hash_equals 사용)
if (!in_array($expected_signature, $signatures) || !hash_equals($expected_signature, $signatures[0])) {
http_response_code(403);
echo json_encode(['error' => 'Invalid signature']);
exit();
}
echo json_encode(['status' => 'verified']);
?>
Stripe는 웹훅 전송을 재시도하므로, 같은 이벤트를 여러 번 받을 수 있다. 데이터베이스에서 중복을 체크하지 않으면 같은 결제를 여러 번 처리하거나 중복 환불이 발생할 수 있다.
<?php
// 중복 처리 방지 로직
$pdo = new PDO('mysql:host=localhost;dbname=myapp', 'user', 'password');
function processWebhook($event, $pdo) {
// ✓ 올바른 코드 - 이벤트 ID로 중복 체크
$event_id = $event['id'];
// 이미 처리된 이벤트인지 확인
$stmt = $pdo->prepare('SELECT id FROM stripe_events WHERE event_id = ?');
$stmt->execute([$event_id]);
if ($stmt->fetch()) {
// 이미 처리된 이벤트 - 조용히 성공 응답
http_response_code(200);
echo json_encode(['status' => 'already_processed']);
return;
}
// 트랜잭션으로 감싸서 원자성 보장
try {
$pdo->beginTransaction();
// 1. 먼저 이벤트 기록
$insertStmt = $pdo->prepare(
'INSERT INTO stripe_events (event_id, event_type, raw_data, created_at) VALUES (?, ?, ?, NOW())'
);
$insertStmt->execute([
$event_id,
$event['type'],
json_encode($event)
]);
// 2. 그 다음에 비즈니스 로직 처리
switch ($event['type']) {
case 'payment_intent.succeeded':
handlePaymentSuccess($event['data']['object'], $pdo);
break;
case 'charge.refunded':
handleRefund($event['data']['object'], $pdo);
break;
}
$pdo->commit();
http_response_code(200);
echo json_encode(['status' => 'processed']);
} catch (Exception $e) {
$pdo->rollBack();
http_response_code(500);
echo json_encode(['error' => 'Processing failed']);
error_log('Webhook processing error: ' . $e->getMessage());
}
}
function handlePaymentSuccess($payment_intent, $pdo) {
$customer_id = $payment_intent['customer'];
$amount = $payment_intent['amount'] / 100; // Stripe는 센트 단위
$currency = $payment_intent['currency'];
// 결제 기록 저장
$stmt = $pdo->prepare(
'INSERT INTO orders (customer_id, amount, currency, stripe_payment_id, status) VALUES (?, ?, ?, ?, ?)'
);
$stmt->execute([$customer_id, $amount, $currency, $payment_intent['id'], 'completed']);
// 추가: 메일 발송, 재고 감소 등
}
function handleRefund($charge, $pdo) {
$payment_id = $charge['payment_intent'];
// 주문 상태를 환불됨으로 변경
$stmt = $pdo->prepare('UPDATE orders SET status = ? WHERE stripe_payment_id = ?');
$stmt->execute(['refunded', $payment_id]);
}
?>
데이터베이스 테이블 스키마는 다음과 같이 구성한다.
-- stripe_events 테이블
CREATE TABLE stripe_events (
id INT PRIMARY KEY AUTO_INCREMENT,
event_id VARCHAR(255) UNIQUE NOT NULL,
event_type VARCHAR(100) NOT NULL,
raw_data LONGTEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_event_id (event_id),
INDEX idx_created_at (created_at)
);
-- orders 테이블
CREATE TABLE orders (
id INT PRIMARY KEY AUTO_INCREMENT,
customer_id VARCHAR(255),
amount DECIMAL(10, 2),
currency VARCHAR(3),
stripe_payment_id VARCHAR(255) UNIQUE,
status ENUM('pending', 'completed', 'refunded', 'failed'),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_stripe_payment_id (stripe_payment_id),
INDEX idx_customer_id (customer_id)
);
✗ 잘못된 코드: 웹훅 수신 직후 금방 응답
<?php
// 잘못된 패턴 - 처리가 오래 걸리면 타임아웃 발생
echo json_encode(['status' => 'received']);
flush();
// 오래 걸리는 처리 시작...
handlePaymentSuccess($payment_intent);
sendEmail($customer_email);
// Stripe는 이 과정 중에 타임아웃으로 판단할 수 있음
?>
✓ 올바른 코드: 먼저 처리한 후 응답
<?php
// 올바른 패턴 - 처리 완료 후 응답
try {
handlePaymentSuccess($payment_intent);
sendEmail($customer_email);
http_response_code(200);
echo json_encode(['status' => 'processed']);
} catch (Exception $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}
?>
✗ 주의: 타임스탐프 검증 없이 Signing Secret만 체크
공격자가 오래된 웹훅을 반복적으로 보낼 수 있다. 반드시 타임스탐프 범위를 확인해야 한다.
✗ 주의: 환경별 Signing Secret 혼동
Stripe는 테스트 모드와 라이브 모드가 다른 Signing Secret을 가진다. .env 파일에서 올바른 환경의 시크릿을 로드하는지 반드시 확인하자.
<?php
// .env 파일 (실제로는 git에 커밋하지 말 것)
STRIPE_MODE=live
STRIPE_WEBHOOK_SECRET_LIVE=whsec_live_...
STRIPE_WEBHOOK_SECRET_TEST=whsec_test_...
// webhook.php
$mode = getenv('STRIPE_MODE');
$endpoint_secret = getenv("STRIPE_WEBHOOK_SECRET_" . strtoupper($mode));
if (!$endpoint_secret) {
throw new Exception('Webhook secret not configured');
}
?>
Stripe Webhook은 결제 시스템의 핵심이다. 단순히 받기만 하는 것이 아니라 Signature 검증으로 위조를 방지하고, 중복 체크로 비즈니스 오류를 막아야 한다는 점을 절대 간과하지 말자. 이 글의 3가지 체크포인트(Signature 검증, 타임스탐프 범위, 중복 처리)를 모두 적용하면, 안정적이고 보안성 높은 결제 시스템을 구축할 수 있을 것이다.