Processing payment with stripe using php

Please friends am highly tucked in here with stripe payments, and i need assistance, i just want to use stripe.js to load the form and send the payment to stripe but get the response from php to know what other functions to run if payment succeeds, also i want to add more fields to the form. But so far i only got the forms to load but don’t know how else to get the callback and get its response in php or should i use php form to collect cards and then process or charge it, am just scared of handling cards details in my form, i prefer to use the stripe.js but complete transactions via php

Below are my codes.

// HTML
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Accept a card payment</title>
    <meta name="description" content="A demo of a card payment on Stripe" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <link rel="stylesheet" href="global.css" />
	<script src="js/jquery-3.4.1.js"></script>
	<script src="js/page.js"></script>
    <script src="https://js.stripe.com/v3/"></script>
    <script src="https://polyfill.io/v3/polyfill.min.js?version=3.52.1&features=fetch"></script>
    
  </head>

  <body>
    <!-- Display a payment form -->
    <form id="payment-form" action="create.php">
      <div id="card-element"><!--Stripe.js injects the Card Element--></div>
      <button id="submit">
        <div class="spinner hidden" id="spinner"></div>
        <span id="button-text">Pay now</span>
      </button>
      <p id="card-error" role="alert"></p>
      <p class="result-message hidden">
        Payment succeeded, see the result in your
        <a href="" target="_blank">Stripe dashboard.</a> Refresh the page to pay again.
      </p>
    </form>
  </body>
  
</html>


// JS
$(document).ready(function() {


	// A reference to Stripe.js initialized with a fake API key.
// Sign in to see examples pre-filled with your key.
var stripe = Stripe("pk_test_MYPUBLICKEYGOESHERE");


// Create an instance of Elements
var elements = stripe.elements();

// Custom styling can be passed to options when creating an Element.
// (Note that this demo uses a wider set of styles than the guide below.)
var style = {
base: {
  color: '#32325d',
  lineHeight: '24px',
  fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
  fontSmoothing: 'antialiased',
  fontSize: '16px',
  '::placeholder': {
    color: '#aab7c4'
  }
},
invalid: {
  color: '#fa755a',
  iconColor: '#fa755a'
}
};

// Create an instance of the card Element
var card = elements.create('card', {style: style});

// Add an instance of the card Element into the `card-element` <div>
card.mount('#card-element');

});


// PHP 
require 'vendor/autoload.php';

// This is a sample test API key. Sign in to see examples pre-filled with your key.
\Stripe\Stripe::setApiKey('sk_test_SECRETKEYGOESHERE');


function calculateOrderAmount(array $items): int {
  // Replace this constant with a calculation of the order's amount
  // Calculate the order total on the server to prevent
  // customers from directly manipulating the amount on the client
  return 1400;
}

header('Content-Type: application/json');

try {
  // retrieve JSON from POST body
  $json_str = file_get_contents('php://input');
  $json_obj = json_decode($json_str);

  $paymentIntent = \Stripe\PaymentIntent::create([
    'amount' => calculateOrderAmount($json_obj->items),
    'currency' => 'usd',
  ]);

  $output = [
    'clientSecret' => $paymentIntent->client_secret,
  ];

  print_r($output);
} catch (Error $e) {
  http_response_code(500);
  echo json_encode(['error' => $e->getMessage()]);
}

But so far i dont know where else to head to, the sample on stripe docs has an erorr, if i copied it exactly from the site the form stripe.js wont load via java. please i need help

Well lets start from the beginning here with the demo working. This is going to help you at least get familiar with the process. I see your code here has the form, then the JS and the PHP. I assume you are naming each file as named in the stripe demo. So you have client.js, create.php and checkout.php?

If you have these three files, are they all together in the same web root folder?

If that is ok, what is the error you are seeing say?

yes they are together in the same root.

Here are my errors and problems.

  1. if i copy the entire code from the stripe demo of custom flow the stripe card form won’t load into the #form_elements div

  2. now if the form submits and calls the create.php the json output error is thrown, i have tried to get the json decoded in php array so i can work with it.

but then i think am missing two important aspects of the function and thats the createtoken and confirm token

This is the error message am getting when the create.php file is called after the form has been submitted.

Is that just from the line where you print_r($output) without JSON-encoding it?

thanks okay, so i need to encode it into json ànd then decode back as to use it in php as array? i was thinking stripe sent the response in json already.

If that print_r() output is the first thing that your code sends back, then the Ajax calling code is taking that as the first response from the PHP code, trying to JSON-decode it, and failing. So yes, that might be causing the issue.

I don’t know anything about Stripe, but it seems that your error message is caused by trying to JSON-decode something that isn’t encoded, and that line seems a decent fit.

1 Like

thanks alot that was the problem.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.