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