简体   繁体   中英

Stripe checkout redirect with customer id

I am using Stripe checkout redirect (JS) to create payment URLs for a set of products, and it is working fine, but I am using this for a group of users that I do have already registered in a DB and Stripe and would like to use their customer_id to process the payment and avoid to add new customers entries to the Stripe dashboard. I thought I could use the clientReferenceId parameter in the request, but it doesn't work. Any ideas are really appreciated.

In my implementation I am capturing a button click event to fire the checkout redirect, and pulling the required parameters from the HTML.

Here is what Stripe documentation suggest:

$(document).ready(function(){
  let  stripe = Stripe('stripe_KEY');  

  let btn = $(".btn-bill");
  let price_id = $("#price_id");
  let email = $("#email");
  let cust_id = $("#cust_id");
  
  btn.click(function(evt){
      evt.preventDefault();
      stripe.redirectToCheckout({
        lineItems: [{
            price: price_id.text(), // Replace with the ID of your price
            quantity: 1,
          }],
          clientReferenceId : cust_id.text(), //Tried this with no luck
          mode: 'payment',
          locale: 'en',
          successUrl: 'http://example.com/sucess', // Replace with your own
          cancelUrl: 'http://example.com/cancel', // Replace with your own
          customerEmail: email.text(),
        }).then(function (result) {
          // If `redirectToCheckout` fails due to a browser or network
          // error, display the localized error message to your customer
          // using `result.error.message`.
        });
    });
  
});

Update: After digging into the documentation will try to create a session id and see if this works.

Just in case somebody wonders how to resolve this, had to change the JS script and add a backend processing session script to create the session id.

So, since the customer id is used, no need to create additional customer entries to your Stripe dashboard, the documentation states if the customer value is not defined, it creates a new customer object.

In JS:

$(document).ready(function(){
  let  stripe = Stripe('stripe_KEY');  

  let btn = $(".btn-bill");
  let price_id = $("#price_id");
  let cust_id = $("#cust_id");
  let cancelUrl = "http://example.com/cancel";
  
  let data = {
    "customer_id" : cust_id.text(),
    "cancel_url" : cancelUrl,
    "price_id" : price_id.text(),
  };
  
  let postData = JSON.stringify(data);
  
  btn.click(function(evt){
      evt.preventDefault();
      fetch("/create-session",{
        method: "POST",
        body: postData,
        headers: {
         "Content-type": "application/json",
         "Accept": "application/json"},
      })
     .then(function(response){
        return response.json();
      })
      .then(function(session){
        return stripe.redirectToCheckout({ sessionId: session.id });
      })
      .then(function(result) {
        // If `redirectToCheckout` fails due to a browser or network
        // error, you should display the localized error message to your
        // customer using `error.message`.
        if (result.error) {
          alert(result.error.message);
        }
      });
    });
});

and in the backend endpoint I'm using PHP and Stripe PHP library and the below function returns the session id

public function create_session() {
    $payload = file_get_contents("php://input");
    $json = json_decode($payload,true);
    $obj = json_decode(json_encode($json));
    
    try{
      $customer_id = $obj->customer_id;
      $price_id = $obj->price_id;
      $cancel_url = $obj->cancel_url;
      # Success URL can return a parameter to save or mark a bill as paid
      $success_url = "http://example.com/success";
      
      $stripe = new \Stripe\StripeClient(STRIPE_KEY);
      
      $session_id = $stripe->checkout->sessions->create([
        'success_url' => $success_url,
        'cancel_url' => $cancel_url,
        'payment_method_types' => ['card'],
        'line_items' => [
          [
            'price' => $price_id,
            'quantity' => 1,
          ],
        ],
        'mode' => 'payment',
        'locale' => 'en',
        'customer' => $customer_id,
      ]);
      
      $json = json_encode($session_id);
      
      http_response_code(200);
      header('Content-Type: application/json');
      echo $json;
      return;
    }
    catch (Exception $e) {
      $mess = array(
        "error" => "Exception thrown",
      );
      http_response_code(400);
      echo json_encode($mess);
      exit();
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM