3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

公式PHPライブラリでStripe決済を試してみる

Last updated at Posted at 2021-04-11

こんにちは。
めちゃくちゃ簡単に決済システムが構築できてしまうStripe。APIが豊富で、凝りたければいくらでも作り込めるのが魅力です(終わりなき旅になってしまいますが……)。

とりあえず触りだけ触ってきました。

ライブラリのインストール

https://github.com/stripe/stripe-php
PHP用ライブラリはここにあります。適当にダウンロードしてインストール。

お試し用コード

  //Stripe API
  $stripe = new MyStripeApi();
  $stripe->sub = $sub;

  $stripe_response = $stripe->getSubs();

$subには、Stripeで管理されている定期支払い(いわゆるサブスク)IDが入っているという前提です。次回詳しく説明します。

<?php
/*
Author: toyohama
Version: 0.1.3
*/

require_once(dirname(__FILE__) . '/'. 'stripe-php/init.php');

class MyStripeApi {

  public $sub = '';
  public function __construct() {
    \Stripe\Stripe::setApiKey("sk_test_xxxxxx.................");
  }
  public function getSubs(){
    if ( strlen( $this->sub ) <= 0 ) { return "ng"; }
    $StripeSubscription = \Stripe\Subscription::retrieve($this->sub);
    return $StripeSubscription;
  }
  public function doCancel(){
    if ( strlen( $this->sub ) <= 0 ) { return "ng"; }
    $StripeSubscription = \Stripe\Subscription::retrieve($this->sub);
    $StripeSubscription->cancel();
    return $StripeSubscription;
  }
}

stripe-php以下にまるっと置いてある前提です。
setApiKeyに、Stripe側で作っておいたシークレットキーをセットします。ベタ書きしていますが、本当はきちんとどっかで管理すべきです、当然ですが。
\Stripe\Subscription::retrieveで、現在の定期支払いの状態を取得できます。公式のこのあたりを見てもらうとわかりますが、めっちゃたくさん返ってきます。

上記のdoCancel()の中でやっていますが、この状態でcancel()を呼ぶと、その定期支払いをキャンセル(終了)できるようです。あっけなさすぎて逆に不安になるレベル……。なんらかの形で結果が取得できるとは思います(調べきれていない)。

$stripe = new \Stripe\StripeClient(
  'sk_test_4eC39HqLyjWDarjtT1zdp7dc'
);
$stripe->subscriptions->cancel(
  'sub_AgOem0qdyCowxn',
  []
);

公式に掲載されていたキャンセル処理がこちら。こっちのほうがすっきりしてますね。
他にも、updateやall、createといった操作ができるみたいです。お手軽すぎる。

まとめ

本当にさわりだけですが、自分のサイトやブログに自力でカスタマイズした決済機能をつけたい、というようなときに一番扱いやすいのではないでしょうか。

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?