PHP code example of monkeyscloud / monkeyslegion-stripe
1. Go to this page and download the library: Download monkeyscloud/monkeyslegion-stripe library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
monkeyscloud / monkeyslegion-stripe example snippets
use MonkeysLegion\DI\ContainerBuilder;
use MonkeysLegion\Stripe\Provider\StripeServiceProvider;
// Create a new container builder instance
$containerBuilder = new ContainerBuilder();
// Register the Stripe service provider
StripeServiceProvider::register($containerBuilder);
// Build the container
$container = $containerBuilder->build();
// Globalize it
define('ML_CONTAINER', $container);
// Get Stripe services using class names
$stripeClient = ML_CONTAINER->get(\Stripe\StripeClient::class);
$stripeGateway = ML_CONTAINER->get(\MonkeysLegion\Stripe\Client\StripeGateway::class);
$checkoutSession = ML_CONTAINER->get(\MonkeysLegion\Stripe\Client\CheckoutSession::class);
$subscription = ML_CONTAINER->get(\MonkeysLegion\Stripe\Client\Subscription::class);
$product = ML_CONTAINER->get(\MonkeysLegion\Stripe\Client\Product::class);
$setupIntentService = ML_CONTAINER->get(\MonkeysLegion\Stripe\Client\SetupIntentService::class);
$webhookController = ML_CONTAINER->get(\MonkeysLegion\Stripe\Webhook\WebhookController::class);
// Switch to test mode (default)
$stripeGateway->setTestMode(true); // Uses STRIPE_TEST_KEY
$checkoutSession->setTestMode(true); // Uses STRIPE_TEST_KEY
$subscription->setTestMode(true); // Uses STRIPE_TEST_KEY
// Switch to live mode for production
$stripeGateway->setTestMode(false); // Uses STRIPE_SECRET_KEY
$checkoutSession->setTestMode(false); // Uses STRIPE_SECRET_KEY
$subscription->setTestMode(false); // Uses STRIPE_SECRET_KEY
// You may use this approach if you prefer
$isProduction = ($_ENV['APP_ENV'] ?? 'dev') === 'prod';
$stripeGateway->setTestMode(!$isProduction);
// Get the gateway service
$stripeGateway = $container->get(\MonkeysLegion\Stripe\Client\StripeGateway::class);
// Create a payment intent
$paymentIntent = $stripeGateway->createPaymentIntent(
2000, // amount in cents
'usd', // currency
true // enable automatic payment methods
);
// Retrieve a payment intent
$paymentIntent = $stripeGateway->retrievePaymentIntent('pi_1234567890');
// Confirm a payment intent
$confirmedPayment = $stripeGateway->confirmPaymentIntent('pi_1234567890', [
'payment_method' => 'pm_card_visa'
]);
// Cancel a payment intent
$cancelledPayment = $stripeGateway->cancelPaymentIntent('pi_1234567890');
// Capture a payment intent (for manual capture)
$capturedPayment = $stripeGateway->capturePaymentIntent('pi_1234567890');
// Refund a payment intent
$refund = $stripeGateway->refundPaymentIntent('pi_1234567890', [
'amount' => 1000 // partial refund
]);
// Update a payment intent
$updatedPayment = $stripeGateway->updatePaymentIntent('pi_1234567890', [
'description' => 'Updated payment description'
]);
// List payment intents
$paymentIntents = $stripeGateway->listPaymentIntent([
'limit' => 10,
'customer' => 'cus_1234567890'
]);
// Search payment intents
$searchResults = $stripeGateway->searchPaymentIntent([
'query' => 'status:\'succeeded\' AND metadata[\'order_id\']:\'12345\''
]);
// Increment authorization
$incrementedPayment = $stripeGateway->incrementAuthorization('pi_1234567890', 500);
// Check if payment intent is valid
$isValid = $stripeGateway->isValidPaymentIntent('pi_1234567890');
// Get the checkout service
$checkoutSession = $container->get(\MonkeysLegion\Stripe\Client\CheckoutSession::class);
// Create a checkout session
$session = $checkoutSession->createCheckoutSession([
'mode' => 'payment',
'line_items' => [
[
'price_data' => [
'currency' => 'usd',
'product_data' => [
'name' => 'Premium Plan'
],
'unit_amount' => 2000,
],
'quantity' => 1,
],
],
'success_url' => 'https://example.com/success?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => 'https://example.com/cancel',
]);
// Retrieve a checkout session
$session = $checkoutSession->retrieveCheckoutSession('cs_1234567890');
// List checkout sessions
$sessions = $checkoutSession->listCheckoutSessions([
'limit' => 10
]);
// Expire a checkout session
$expiredSession = $checkoutSession->expireCheckoutSession('cs_1234567890');
// List line items from a session
$lineItems = $checkoutSession->listLineItems('cs_1234567890');
// Get checkout URL directly
$checkoutUrl = $checkoutSession->getCheckoutUrl([
'mode' => 'payment',
'line_items' => [/* ... */],
'success_url' => 'https://example.com/success',
'cancel_url' => 'https://example.com/cancel',
]);
// Validate checkout session
$isValid = $checkoutSession->isValidCheckoutSession('cs_1234567890');
// Check if session is expired
$isExpired = $checkoutSession->isExpiredCheckoutSession('cs_1234567890');
// Get the subscription service
$subscription = $container->get(\MonkeysLegion\Stripe\Client\Subscription::class);
// Create a subscription
$newSubscription = $subscription->createSubscription(
'cus_1234567890', // customer ID
'price_1234567890', // price ID
[
'trial_period_days' => 7,
'metadata' => ['plan' => 'premium']
]
);
// Retrieve a subscription
$subscription = $subscription->retrieveSubscription('sub_1234567890');
// Update a subscription
$updatedSubscription = $subscription->updateSubscription('sub_1234567890', [
'metadata' => ['updated' => 'true'],
'proration_behavior' => 'create_prorations'
]);
// Cancel a subscription
$cancelledSubscription = $subscription->cancelSubscription('sub_1234567890', [
'at_period_end' => true
]);
// List customer subscriptions
$subscriptions = $subscription->listSubscriptions('cus_1234567890', [
'status' => 'active',
'limit' => 10
]);
// Resume a subscription
$resumedSubscription = $subscription->resumeSubscription('sub_1234567890');
// Search subscriptions
$searchResults = $subscription->searchSubscriptions([
'query' => 'status:\'active\' AND metadata[\'plan\']:\'premium\''
]);
// Get the product service
$product = $container->get(\MonkeysLegion\Stripe\Client\Product::class);
// Create a product
$newProduct = $product->createProduct([
'name' => 'Premium Software License',
'description' => 'Annual software license with premium features',
'metadata' => ['category' => 'software']
]);
// Retrieve a product
$product = $product->retrieveProduct('prod_1234567890');
// Update a product
$updatedProduct = $product->updateProduct('prod_1234567890', [
'name' => 'Updated Premium License',
'description' => 'Updated description'
]);
// Delete a product
$deletedProduct = $product->deleteProduct('prod_1234567890');
// List products
$products = $product->listProducts([
'active' => true,
'limit' => 10
]);
// Search products
$searchResults = $product->searchProducts(
'metadata[\'category\']:\'software\'',
['limit' => 20]
);
// Get the webhook controller
$webhookController = ML_CONTAINER->get(\MonkeysLegion\Stripe\Webhook\WebhookController::class);
// Handle incoming webhook
$payload = file_get_contents('php://input');
$sigHeader = $_SERVER['HTTP_STRIPE_SIGNATURE'] ?? '';
$result = $webhookController->handle($payload, $sigHeader, function($event) {
return ['status' => 'success', 'event' => $event['type']];
});
// Complete webhook endpoint example
function handleWebhook() {
// This should be at your app.php
$containerBuilder = new ContainerBuilder();
StripeServiceProvider::register($containerBuilder);
$container = $containerBuilder->build();
define('ML_CONTAINER', $container);
//
$webhookController = ML_CONTAINER->get(\MonkeysLegion\Stripe\Webhook\WebhookController::class);
$payload = file_get_contents('php://input');
$sigHeader = $_SERVER['HTTP_STRIPE_SIGNATURE'] ?? '';
try {
$result = $webhookController->handle($payload, $sigHeader, function ($event) {
// Your event handling logic here
return processStripeEvent($event);
});
http_response_code(200);
echo json_encode($result);
} catch (\Throwable $e) {
$code = $e->getCode();
// Ensure we don't return invalid HTTP codes
if ($code < 100 || $code >= 600) $code = 500
http_response_code($code);
echo json_encode(['error' => $e->getMessage()]);
}
}
// Production mode (APP_ENV=prod):
// - Retries: Rate limits, API connection errors, server errors (5xx)
// - No Retry: Card errors, invalid requests, authentication errors
// - Uses exponential backoff: 60s, 120s, 180s
// Development mode (APP_ENV=dev):
// - No retries for any errors (fail fast for debugging)
// - Immediate error reporting
// In your app configuration
return [
'webhook_default_ttl' => 86400, // 24 hours (in seconds) // ...other config
];
bash
# Install the package
composer php vendor/bin/ml stripe:install
# Set up your Stripe keys interactively
php vendor/bin/key-helper set
# Validate your configuration
php vendor/bin/key-helper validate
# Test webhook signature verification
php vendor/bin/key-helper webhook:test
bash
# Display current key values
php vendor/bin/key-helper show secret
php vendor/bin/key-helper show webhook
php vendor/bin/key-helper show webhook_test
# Show keys for specific environment
php vendor/bin/key-helper --stage=prod show secret
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.