You cannot create a charge with a PaymentMethod. Use the Payment Intents API instead

Viewed 1923

Part of client code for getting token from stripe and send it to backend

const cardElement = elements.getElement(CardElement);
const {error, paymentMethod} = await stripe.createPaymentMethod({
   type: 'card',
   card: cardElement,
});

    try {
      const { id } = paymentMethod;
      console.log(id)
      const response = await axios.post(
        "https://localhost:44325/api/Payment",
        {
          token: id,
        }
      );

  
    } catch (error) {
      console.log("CheckoutForm.js 28 | ", error);
    }
  } 

Backend

public async Task Test(string token)
        {
            StripeConfiguration.ApiKey = "SecretKey";
        var options = new ChargeCreateOptions()
        {
            Amount = 12345,
            Currency = "usd",

            Description = "Donation from me",
            Source = token
        };
        var service = new ChargeService();

        try
        {
            var charge = service.Create(options);
        }
        catch (StripeException e)
        {

        }
    }

And I get You cannot create a charge with a PaymentMethod. Use the Payment Intents API instead. How I can send to stripe payment with token from client?

2 Answers

Charges API (/v1/charges) on Stripe works with Tokens, Cards (attached tokens) and Sources.

PaymentIntents API (/v1/payment_intents) works with PaymentMethods (and technically also with legacy attached tokens (aka Card objects) and Sources but these latter two aren't relevant to your use-case).

Your integration is creating a PaymentMethod object. But you backend is creating a Charge, which don't work together.

You need to create a PaymentIntent, create it and pass the confirm: true param to create the payment on it too. https://stripe.com/docs/api/payment_intents/create

Just in case if you still wanna use your charge API on server side and not PaymentIntents, cause it's asynchronous (webhook based).

Then in that case on client side you can use stripe elements along with stripe.createToken method. Just pass any of stripe card element to this method and it'll generate a token for you, send this token on server side to create charge.

stripe.createToken

Related