Posted at

PHPでStripeからのWebhooksを受けつける


composer.json

{

"require": {
"stripe/stripe-php": "^6.29"
}
}

<?php

\Stripe\Stripe::setApiKey(getenv('STRIPE_SECRET_KEY'));
\Stripe\Stripe::setClientId(getenv('STRIPE_CLIENT_ID'));

//
// Webhook の署名を確認する
// https://stripe.com/docs/webhooks/signatures#verify-official-libraries
//
$endpoint_secret = 'whsec_...';

$payload = @file_get_contents('php://input');
$sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
$event = null;

try {
$event = \Stripe\Webhook::constructEvent(
$payload, $sig_header, $endpoint_secret
);
} catch(\UnexpectedValueException $e) {
// Invalid payload
http_response_code(400); // PHP 5.4 or greater
exit();
} catch(\Stripe\Error\SignatureVerification $e) {
// Invalid signature
http_response_code(400); // PHP 5.4 or greater
exit();
}

//
// $eventに対しての処理を行う
//

$event_json = json_decode($payload);

$event_id = $event_json->id;
try {
$event = \Stripe\Event::retrieve($event_id);
} catch(\Stripe\Error\InvalidRequest $e) {
// Invalid payload
http_response_code(400);
exit();
} catch(\Stripe\Error $e) {
// Invalid payload
http_response_code(400);
exit();
}

if ($event->type == 'customer.created') {
}

if ($event->type == 'customer.subscription.deleted') {
}

if ($event->type == 'customer.subscription.updated') {
}

if ($event->type == 'invoice.payment_succeeded') {
}

http_response_code(200);