【PHP】stripeのwebhook設定

stripeのwebhook設定手順

参考ページ
https://stripe.com/docs/webhooks/setup
https://qiita.com/hirocueki2/items/9dc1eea6836e3f293f47

1.dashboard の「開発者」から webhook の設定をする

エンドポイントの例
https://example.com/stripe_test/webhook_test.php?action=stripehook

2.PHPファイルをサーバーに置く

PHPファイルの例
//////////////////////////////////////////////////////////
<?php

// ダウンロードしたStripeのPHPライブラリのinit.phpを読み込む
//require_once(‘/home/hoge/stripe-php/init.php’); //手動でダウンロードした場合は init.php になるらしい
require_once(‘/var/ruigo_stripe_composer/vendor/autoload.php’);

// APIのシークレットキー

// Set your secret key: remember to change this to your live secret key in production
// See your keys here: https://dashboard.stripe.com/account/apikeys
\Stripe\Stripe::setApiKey(‘秘密キー’);

// You can find your endpoint’s secret in your webhook settings
$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);
exit();
} catch(\Stripe\Error\SignatureVerification $e) {
// Invalid signature
http_response_code(400);
exit();
}

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

$event_json = json_decode($payload);

$event_id = $event_json->id;

//dashboard からのテスト送信だと id が 00000 になるのでエラーが返る
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’) {
}

echo “aa”; //このページからのレスポンス。stripe のダッシュボードで確認できる
http_response_code(200);

?>
//////////////////////////////////////////////////////////

タイトルとURLをコピーしました