Stripe Integration With JS And PHP

Today we will learn the Stripe Integration With JS and PHP.

The Stripe.js render the UI element to accept the customer card details. It hits the endpoint URL and sends the payment request to the API. The API keys are used for authentication before the payment.

Step-1: Open your Stripe account and get the API keys.

  1. Publishable key
  2. Secret key

Step-2: Create a payment page and render the Stripe element to get the card details.
Insert the below HTML code to the file.

<div id="card-element">
  <!-- A Stripe Element will be inserted here. -->
</div>
<div id="stripeToken"></div>
<div id="card-errors" style="color: #f00;"></div>
<div class="pay-btn">
  <input type="submit" class="stripebtn" data-price="25" value="Pay $25">
</div>
<div id="card-success" style="color: #008000;"></div>

Step-3: Insert the Stripe js in the <head> tag.

<script src="https://js.stripe.com/v3/"></script>

Step-4: Now let’s render the Stripe element with the jQuery.
Insert below jQuery code to the js file.
Replace the publishable_key variable with your Publishable key.

var publishable_key = 'pk_test_************************************************';
var stripe = Stripe( publishable_key );
var elements = stripe.elements();
var style = {  
  base: {
    fontSize: '16px',
    '::placeholder': {
      color: '#545454',
    },
    color: '#000000',
    iconColor: '#545454',
  },
  invalid: {
    color: '#ff0000', 
    iconColor: '#ff0000'
  }
};
var card = elements.create('card', {style: style});

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

With this code, stripe fields will be added to your HTML element.

Step-5: Let’s insert the click action on the pay button click.
Insert below jQuery code to the js file.

jQuery(document).on('click', '.stripebtn', function(){
    
  var price = jQuery(this).data('price');
  
  stripe.createToken(card).then(function(result) {
    if (result.error) {
      var errorElement = document.getElementById('card-errors');
      errorElement.textContent = result.error.message;
    } else {
      jQuery('input[name="stripeToken"]').remove();
      stripeTokenHandler(result.token);
      
      jQuery.ajax({
        url: 'pay-stripe.php',
        type: "post",
        dataType: 'json',
        data: {
          token: jQuery('input[name="stripeToken"]').val(),
          price: price,
        },
        success: function(data){
          var clientSecret = data.client_secret;
          stripe.confirmCardPayment( clientSecret, {
            payment_method: {
              card: card,
            }
          }).then(function(result) {
            if (result.error) {
              jQuery( '#card-errors' ).text( result.error.message );
            } else {
              if (result.paymentIntent.status === 'succeeded') {
                var token_id = result.paymentIntent.id;
                jQuery( 'input[name="stripeToken"]' ).val( token_id );	
                jQuery( '#card-success' ).html('Payment successful.');
              }
            }
          });
        },
      });
    }
  });
});
function stripeTokenHandler(token) {
  var form = document.getElementById('stripeToken');
  var hiddenInput = document.createElement('input');
  hiddenInput.setAttribute('type', 'hidden');
  hiddenInput.setAttribute('name', 'stripeToken');
  hiddenInput.setAttribute('value', token.id);
  form.appendChild(hiddenInput);
}

Step-6: Let’s insert the PHP action for payment.
Insert action file “pay-stripe.php” with the below code.
Replace the “secret_key” variable with your Secret key.

$price = $_REQUEST[ 'price' ];

$secret_key = 'sk_test_***************************************************';

$chargebody = http_build_query(array(
  'amount'		=> $price * 100,
  'currency'		=> 'usd',	
  'payment_method_types'		=> array(
    'card',
  ),
)); 

$charge_url = 'https://api.stripe.com/v1/payment_intents';
$headers = array( 'Authorization: Bearer '.$secret_key );

$curl       = curl_init();
curl_setopt( $curl, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $curl, CURLOPT_URL, $charge_url );
curl_setopt( $curl, CURLOPT_POSTFIELDS, $chargebody );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, false );
$charge_response = curl_exec( $curl );
curl_close( $curl );

$charge_array = json_decode( $charge_response, true );	

if( $charge_array['id']!='' ) {
  echo json_encode( array( 'message'=>'Success', 'client_secret' => $charge_array['client_secret'] ) ); 
}

Well done, Now you can pay with the stripe from the website.

Please check the below video for the output.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories