Search code examples
stripe-payments

Create a Stripe charge with a valid payment method


I am trying to create a charge in Stripe java backend from a payment method. These payment methods come from stored cards in a Stripe customer.

This is my backend code:

public Charge chargeNewCard(String payment_id, double amount) throws
        EtAuthException {
    if (amount == 0) {
        throw new EtAuthException("Enter a valid amount");
    }
    amount = Math.ceil(amount * 100);
    try {
        ChargeCreateParams chargeCreateParams = ChargeCreateParams.builder()
                .setAmount((long) amount)
                .setCurrency("usd")
                .setSource(payment_id)
                .build();

        return Charge.create(chargeCreateParams);
    } catch (StripeException e) {
        throw new EtAuthException("chargeNewCard: " + e);
    }
}

The payment_id looks something like this "pm_XXXXXXXX".

I get the following error:

You must supply either a card, customer, PII data, bank account, or account legal entity to create a token. If you're making this request with a library, be sure to pass all of the required parameters for creating a token. If you're making this request manually, be sure your POST parameters begin with the token type. For example, a PII token would require `pii[personal_id_number]`, while an account token would require a parameter beginning with `account[legal_entity]`. 

According to the docs, the setSource() is "A payment source to be charged. This can be the ID of a card (i.e., credit or debit card), a bank account, a source, a token, or a connected account. For certain sources—namely, cards, bank accounts, and attached sources—you must also pass the ID of the associated customer."

Using a customerId (e.g cus_XXXXXX) doesn't help either. What should i do?


Solution

  • Payment Methods (pm_123 objects) are not compatible with legacy Charges API. You should use the Payment Intents API instead, where you can pass this as payment_method (API ref). Example in Java:

    PaymentIntentCreateParams params =
      PaymentIntentCreateParams.builder()
        .setCurrency("usd")
        .setAmount(1099)
        // In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default.
        .setAutomaticPaymentMethods(
        PaymentIntentCreateParams.AutomaticPaymentMethods.builder().setEnabled(true).build()
        )
        .setCustomer("cus_123")
        .setPaymentMethod("pm_456")
        .setReturnUrl("https://example.com/order/123/complete")
        .setConfirm(true)
        .build();
    
      PaymentIntent.create(params);