Skip to content

Instantly share code, notes, and snippets.

@aderowbotham
Last active April 29, 2022 08:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aderowbotham/ede27a21edb92129d8917456bcf6481d to your computer and use it in GitHub Desktop.
Save aderowbotham/ede27a21edb92129d8917456bcf6481d to your computer and use it in GitHub Desktop.
PHP / Stripe payment
<?php
// uses "stripe/stripe-php": "6.37.0",
// this is in the body of an API controller function that my stripe form posts to
// frontend uses https://js.stripe.com/v3/
// **the js posts a body with `payment_method_id` or `payment_intent_id` depending on the step of the process**
// this is captured as a property of $input
function the_post_method()
{
$input = $this->getInput(); // gets the input JSON and converts to an object
$stripe_settings = $this->config->item('stripe_settings');
$secret_key = ($stripe_settings->mode === STRIPE_MODE_LIVE) ? $stripe_settings->live_secret_key : $stripe_settings->test_secret_key;
\Stripe\Stripe::setApiKey($secret_key);
try {
$statementDescriptor = 'ACME temp descriptor 123';
if(isset($input->payment_method_id))
{
$intent = \Stripe\PaymentIntent::create([
'payment_method' => $input->payment_method_id,
'amount' => round($orderData['grand_total'] * 100), // amount in pence
'currency' => 'gbp',
'confirmation_method' => 'manual',
'confirm' => true, //Set to true to attempt to confirm this PaymentIntent immediately
'statement_descriptor' => $statementDescriptor // add order number (need to get next order # first)
]);
}
if(isset($input->payment_intent_id))
{
$intent = \Stripe\PaymentIntent::retrieve($input->payment_intent_id);
$intent->confirm();
$invoice_id = '123';
\Stripe\PaymentIntent::update(
$input->payment_intent_id,
['metadata' => ['invoice_number' => 'INVOICE '.$invoice_id]]
);
}
$this->return_success_output_json($orderNumber, $orderData, $approval_user_id, $intent);
} catch (\Stripe\Error\Base $e) {
return $this->fail('The payment failed: ' . $e->getMessage(), 500);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment