· 6 years ago · Aug 02, 2019, 04:58 PM
1<?php
2require_once('stripe-php/init.php');
3
4$stripe = [
5 "secret_key" => "xxx",
6 "publishable_key" => "xxx",
7];
8
9\Stripe\Stripe::setApiKey($stripe['secret_key']);
10
11header('Content-Type: application/json');
12# retrieve json from POST body
13$json_str = file_get_contents('php://input');
14$json_obj = json_decode($json_str);
15
16$intent = null;
17try {
18 if (isset($json_obj->payment_method_id)) {
19 # Create the PaymentIntent
20 $intent = \Stripe\PaymentIntent::create([
21 'payment_method' => $json_obj->payment_method_id,
22 'amount' => $json_obj->preciostripe,
23 'description' => $json_obj->description,
24 'currency' => 'eur',
25 'confirmation_method' => 'manual',
26 'confirm' => true,
27 ]);
28 }
29 if (isset($json_obj->payment_intent_id)) {
30 $intent = \Stripe\PaymentIntent::retrieve(
31 $json_obj->payment_intent_id
32 );
33 $intent->confirm();
34 }
35 generatePaymentResponse($intent);
36} catch (\Stripe\Error\Base $e) {
37 # Display error on client
38 echo json_encode([
39 'error' => $e->getMessage()
40 ]);
41}
42
43function generatePaymentResponse($intent) {
44 # Note that if your API version is before 2019-02-11, 'requires_action'
45 # appears as 'requires_source_action'. Ojo, cambiar tambien en script cliente
46 if ($intent->status == 'requires_source_action' &&
47 $intent->next_action->type == 'use_stripe_sdk') {
48 # Tell the client to handle the action
49 echo json_encode([
50 'requires_source_action' => true,
51 'payment_intent_client_secret' => $intent->client_secret
52 ]);
53 } else if ($intent->status == 'succeeded') {
54 # The payment didn’t need any additional actions and completed!
55 # Handle post-payment fulfillment
56 echo json_encode([
57 "success" => true
58 ]);
59 } else {
60 # Invalid status
61 http_response_code(500);
62 echo json_encode(['error' => 'Invalid PaymentIntent status']);
63 }
64}
65?>