【stripe】webhookでデータ取得【PHP】
webhookで受信したデータから特定の情報を取り出す覚書
PHPでの書き方
//customer_id を使ってメールアドレスを取得
$customer = \Stripe\Customer::retrieve($customer_id);
$customer_email = $customer->email;
stripe
webhookで受信したデータから特定の情報を取り出す覚書
PHPでの書き方
//customer_id を使ってメールアドレスを取得
$customer = \Stripe\Customer::retrieve($customer_id);
$customer_email = $customer->email;
stripe で webhook の動作テストとして、サブスクリプションの支払いエラーを出す手順
1.stripe の dashboard をテストモードにして顧客を作成。
2.顧客のクレジットカード番号は以下のものを登録
4000 0000 0000 0341
3.この顧客でサブスクリプションを作成
charge.failed イベントが発生する。charge.failed をリッスンしておけば webhook で通知が受け取れる。
カテゴリー:stripe
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);
?>
//////////////////////////////////////////////////////////
stripeでカード情報を更新してデフォルトに設定する
JCBカードは洗い替えに対応していないので更新を促す必要がある。
カード番号更新フォームに作り方。
https://stripe.com/jp/blog/smarter-saved-cards
//カード情報を更新してデフォルト 方法1
//////////////////////////////////////////////////
\Stripe\Customer::update($stripe_cus_id, [
'source' => $token, ← 顧客からフォームを通してカードを番号を入力してもらって取得
]);
//////////////////////////////////////////////////
リファレンス
https://stripe.com/docs/saving-cards
//カード情報を更新してデフォルト 方法2
//すでに登録されているカード情報に追加して、二枚目のカードとして新しいカードを登録する場合
//////////////////////////////////////////////////
//まず登録
$card = \Stripe\Customer::createSource(
$stripe_cus_id,
[
'source' => $token,
]);
//新しいカードをデフォルトに切り替える
$customer = \Stripe\Customer::retrieve($stripe_cus_id);
$customer->default_source=$card['id'];
//$customer->save();
//////////////////////////////////////////////////
1.stripe のダッシュボードで定額商品を作成。ここで作られる プランid がスクリプトで必要になる。
プランid の他にも id がつくられるので間違えやすい。plan_ から始まるものが正解。 prod_ から始まるものは違う。
参考:
Stripe サブスクリプション実装の際に必要なidについて
2.php スクリプトを記述
//購入画面(order.html)
--------------------------------------------------
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>購入画面</title>
<!-- 購入ボタンのCSS -->
<style type="text/css">
.stripe-button-el {
width: 350px;
max-width: 100%;
}
.stripe-button-el span {
font-size: 18px;
padding-top: 15px;
min-height: 60px!important;
}
</style>
</head>
<body>
<form action="charge_subsc.php" method="POST">
<?php //data-key は公開キー ?>
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="公開キー"
data-name="サブスクプラン"
data-description="◯◯◯◯◯◯◯"
data-locale="auto"
data-amount="400"
data-currency="jpy"
data-label="お申し込みする">
</script>
</form>
</body>
</html>
--------------------------------------------------
//購入画面からデータを投げる先(charge_subsc.php)
--------------------------------------------------
<?php
// ダウンロードしたStripeのPHPライブラリのinit.phpを読み込む
//require_once('/home/hoge/stripe-php/init.php'); //手動でダウンロードした場合は init.php になるらしい
require_once('/var/hoge/vendor/autoload.php');
// APIのシークレットキー
\Stripe\Stripe::setApiKey('秘密キー');
try
{
$customer = \Stripe\Customer::create(array(
'email' => $_POST['stripeEmail'],
'source' => $_POST['stripeToken'],
));
$subscription = \Stripe\Subscription::create(array(
'customer' => $customer->id,
'items' => array(array('plan' => '1で作ったプランのid')),
));
//データベース操作など stripe とは関係ない処理
//必要に応じてデータベースに保存する
$customer_id = $customer->id;
$subscription_id = $subscription->id;
$last4 = $customer->sources->data[0]->last4; //カード番号下四桁
$exp_month = $customer->sources->data[0]->exp_month; //カード有効月
$exp_year = $customer->sources->data[0]->exp_year; //カード有効年
$card_exp_date = $exp_month . "/" . $exp_year;
header('Location: thankyou.html');
exit;
}
catch(Exception $e)
{
// header('Location:oops.html');
echo "error:" . $e->getMessage();
error_log("unable to sign up customer:" . $_POST['stripeEmail'].
", error:" . $e->getMessage());
}
// サンキューページへリダイレクト
exit;
?>
--------------------------------------------------
これでできるはず。
ちなみにキャンセルはこれ
--------------------------------------------------
//サブスクリプションをキャンセル
$subscription = \Stripe\Subscription::retrieve($stripe_subsc_id);
$subscription->cancel();
--------------------------------------------------
メインで参考にしたページ
https://teratail.com/questions/118633
前提
php で composer が使える状態である
composer の導入はこちら
1.ComposerでStripeライブラリをインストールする
2.ファイルの設置
メインで参考にしたページ
https://qiita.com/p_s_m_t/items/a69dfbc75804fe86ad9c
ファイル内でライブラリをロードするときの注意点
ComposerでStripeライブラリをインストールした場合
-------------------------------------------------
require_once('/stripe_test/vendor/autoload.php');
-------------------------------------------------
Composerを使わず、手動でStripeライブラリをダウンロードしてサーバーに置いた場合
-------------------------------------------------
require_once('/stripe_test/stripe-php/init.php');
-------------------------------------------------
デフォルトのファイル名が違うので間違えないように
カテゴリー:CentOS, PHP, stripe, さくらインターネット