Home > Blockchain >  Stripe PHP SDK - creating customer & Charge
Stripe PHP SDK - creating customer & Charge

Time:01-20

is anyone familiar with the stripe sdk? I am trying to create a customer and then create a charge against the customer. The creating a customer bit works fine but its not creating a charge... can someone point me in the right direction please.... public function onCharge() {

$stripe = new \Stripe\StripeClient(env('STRIPE_SECRET'));

$user = Auth::getUser();

$course = CourseMeta::where('id', $this->param('id'))->first();

$customer = $stripe->customers->create([
    'description' => $user->name,
    'email' => $user->email,
    'payment_method' => 'pm_card_visa',
]);

$charge = $stripe->charges->create([
  'amount' => $course->price,
  'currency' => 'usd',
  'source' => $customer->token,
  'description' => $course->course->name,
  'customer' => $customer,
]);

Session::flash('success', 'Payment successful!');
      
return back();

}

CodePudding user response:

Is this line your actual code or have you edited it?

'payment_method' => 'pm_card_visa',

To charge a card later you need to add a card token to the customer.

This looks like you are applying an incorrect static string, rather than the one time unique token returned by stripe.

Try this after creating the customer.

$stripe->customers->createSource(
  'cus_KzSew4AQXyTNTG',
  ['source' => $request->token_from_js]
);

https://stripe.com/docs/api/cards/create

CodePudding user response:

your code looks OK for me. It's just the payment method that you passed in is a test method, you only use it for the convenience of testing.

And also Charge is an old API, you should look at the new Payment Intent API if you are new to Stripe. Here's a flow that I'd recommend

  1. Create a customer object with name and email
$customer = $stripe->customers->create([
  'name' => 'John',
  'email' => '[email protected]',
  'description' => 'My First Test Customer (created for API docs)',
]);
  1. Create a Payment Intent object with the customer that you just created
$paymentIntent = $stripe->paymentIntents->create([
  'amount' => 2000,
  'currency' => 'usd',
  'payment_method_types' => ['card'],
  'customer' => $customer->id
]);
  1. Return the $paymentIntent->client_secret to your frontend webpage, and use it to render the payments element so that you can collect the payment details from your customer

  2. Once your customer has finished the payment details, call stripe.confirmPayment at frontend to confirm the payment

For the complete integration guide, please take a look at this doc

  •  Tags:  
  • Related