ViktorasssIT
ViktorasssIT

Reputation: 387

Laravel 7 cashier stripe monthly subscription setup

Need help with setting up a monthly subscription with stripe.

First I pass $intent variable to the view where the form is located:

public function checkoutForm()
{
    $user = auth()->user();

    $intent = $user->createSetupIntent();

    return view('app.payments.form', compact('intent'));
}

My HTML form:

<form action="{{route('app.payments.checkout')}}" method="POST" id="payment-form">
  @csrf
  <div class="form-row">
    <div>
      <label class="form-label">Email</label>
      <input id="email" name="email" class="form-control">
    </div>
    <div>
      <label class="form-label">Card holder name</label>
      <input id="card-holder-name" name="card-holder-name" class="form-control">
    </div>
  </div>
  <div class="form-row">
    <label for="card-element form-label">
      Credit or debit card
    </label>
    <div id="card-element">
      <!-- A Stripe Element will be inserted here. -->
    </div>
    <!-- Used to display form errors. -->
    <div id="card-errors" role="alert"></div>
  </div>
  <button id="card-button" class="btn btn-success w-auto" data-secret="{{ $intent- 
>client_secret }}">Submit Payment</button>
</form>

My javascript:

let stripe = Stripe('pk_test_51HOeq6DJMeDFu');
let elements = stripe.elements();

let card = elements.create('card', {
hidePostalCode: true,
});

// Add an instance of the card Element into the `card-element` <div>.
card.mount('#card-element');
// Handle real-time validation errors from the card Element.
card.on('change', function (event) {
let displayError = document.getElementById('card-errors');
if (event.error) {
 displayError.textContent = event.error.message;
} else {
 displayError.textContent = '';
}
});

// Handle form submission.
let form = document.getElementById('payment-form');
form.addEventListener('submit', function (event) {
  event.preventDefault();

  let options = {
    name: document.getElementById('card-holder-name').value,
    email: document.getElementById('email').value,
}

stripe.createToken(card, options).then(function (result) {
if (result.error) {
  // Inform the user if there was an error.
  let errorElement = document.getElementById('card-errors');
  errorElement.textContent = result.error.message;
 } else {
  // Send the token to your server.
  stripeTokenHandler(result.token);
 }
 });
 });

// Submit the form with the token ID.
function stripeTokenHandler(token) {
  // Insert the token ID into the form so it gets submitted to the server
 let form = document.getElementById('payment-form');
  let hiddenInput = document.createElement('input');
  hiddenInput.setAttribute('type', 'hidden');
  hiddenInput.setAttribute('name', 'stripeToken');
  hiddenInput.setAttribute('value', token.id);
  form.appendChild(hiddenInput);

  // Submit the form
  form.submit();
}

Then I pass back data to backend, first I created a plan which I want to charge the user

    public function postCheckout(Request $request)
{

    $user = auth()->user();

    \Stripe\Stripe::setApiKey("sk_test_51HOeq6D");

    \Stripe\Plan::create(array(
        "amount" => 20,
        "interval" => "month",
        "product" => array(
            "name" => "Monthly subscription"
        ),
        "currency" => "usd",
        "id" => "Connectplus"
    ));

    try {
        $user->newSubscription('Connectplus', '20')->create($paymentMethod???);
    } catch (\Exception $e) {
        dd($e->getMessage());
    }
}

The requests sends back the stripeToken, the validation works fine, but I want to create a monthly subscription for a user.

But I don't understand how to identify the $paymentMethod variable, could anyone help me with this?

Upvotes: 0

Views: 283

Answers (1)

Kamlesh Paul
Kamlesh Paul

Reputation: 12391

you need to get from $request

$paymentMethod = $request->payment_method;

in frontend

cardButton.addEventListener('click', async (e) => {
    let clientSecret = cardButton.dataset.secret;
    const { setupIntent, error } = await stripe.confirmCardSetup(
        clientSecret, {
            payment_method: {
                card: cardElement,
                billing_details: { name: cardHolderName.value }
            }
        }
);

 let {payment_method} = setupIntent;

it create payment_method which u can get in server

Upvotes: 0

Related Questions