WordPressでは、「プラグインディレクトリごとにvendorディレクトリが作成される」などの理由でComposerを利用したSDKやライブラリの追加を避ける事があります。
「WooCommerce Stripe Payment Gateway」プラグインなどでは、利用するAPIが限られていることもあり、SDKを利用せずにStripe APIを呼び出しています。
今回はこのようなSDKを使わないAPI呼び出し方法を、簡単に紹介します。
wp_remote_requestでStripe APIを呼び出す
SDKを利用しない場合、WordPressの関数でStripe APIを呼び出します。
例えばStripe Checkoutのセッションを開始するには、次のようなコードを書きます。
<?php
$parsed_args = wp_parse_args( [
'method' => 'POST',
'headers' => [
'Authorization' => 'Bearer sk_xxx',
],
'body' => [
'success_url' => 'http://localhost:8881/',
'cancel_url' => 'http://localhost:8881/',
'mode' => 'subscription',
'line_items' => [
[
'price' => 'price_xxx',
'quantity' => 1,
],
],
],
] );
$response = \wp_remote_request(
'https://api.stripe.com/v1/checkout/sessions',
$parsed_args
);
if ( \is_wp_error( $response ) ) {
return $response;
}
$body = \json_decode( \wp_remote_retrieve_body( $response ), true );
汎用関数・クラスを作成する
複数のAPIを利用する場合は、API呼び出し部分とレスポンスのパースをクラスや関数にまとめることもできます。
<?php
class WP_Stripe {
private $api_key;
public function __construct( string $api_key ) {
$this->api_key = $api_key;
}
public function call_stripe_api( string $path, $method, $body ) {
$url = 'https://api.stripe.com/v1' . $path;
$headers = [
'Authorization' => 'Bearer ' . $this->api_key,
];
$parsed_args = wp_parse_args( [
'method' => strtoupper( $method ),
'headers' => $headers,
'body' => $body,
] );
$response = \wp_remote_request( $url, $parsed_args );
if ( \is_wp_error( $response ) ) {
return $response;
}
$body = \json_decode( \wp_remote_retrieve_body( $response ), true );
return $body;
}
}
次の例では、同じくStripe Checkoutのセッションを作成し、成功した場合にリダイレクトを実施します。
<?php
function sb_create_new_checkout_session() {
$client = new WP_Stripe(\STRIPE_SECRET_API_KEY);
$session = $client->call_stripe_api(
'/checkout/sessions',
'post',
[
'success_url' => 'http://localhost:8881/',
'cancel_url' => 'http://localhost:8881/',
'mode' => 'subscription',
'line_items' => [
[
'price' => 'price_xxxx',
'quantity' => 1,
],
],
]
);
if ( \is_wp_error( $session ) ) {
return $session;
}
if ( ! $session[ 'url' ] ) {
return new \WP_REST_Response([
'error' => 'Failed to get the Checkout URL'
], 400);
}
\wp_redirect( $session[ 'url' ] );
\exit;
}
function sb_register_stripe_billing_routes() {
$API_ROUTE = 'stripe-billing/v1';
register_rest_route(
$API_ROUTE,
'checkout',
[
'methods' => \WP_REST_Server::CREATABLE,
'callback' => 'sb_create_new_checkout_session',
'permission_callback' => '__return_true'
]
);
}
add_action( 'rest_api_init', 'sb_register_stripe_billing_routes' );
StripeのWebhook用APIをWordPressで用意する方法
SDKを使わずにStripe Webhookを処理するWP APIエンドポイントを追加する方法を、次の記事で紹介しています。
CheckoutやCustomer Portalなど、Stripe APIを利用する場面が限られているケースでは、SDKを使わない方法も検討してみましょう。
参考URL