I used test token to chose what type of card I want. Got the token name from stripe-docs.
import com.stripe.Stripe;
import com.stripe.exception.StripeException;
import com.stripe.model.Card;
import com.stripe.model.Customer;
import java.util.HashMap;
import java.util.Map;
public class StripeExample {
public static void main(String[] args) throws StripeException {
final String API_KEY = System.getenv("STRIPE_API_KEY");
assert API_KEY != null : "API_KEY SHOULD NOT BE NULL";
Stripe.apiKey = API_KEY;
// Retrieve the existing customer by ID
Customer customer = Customer.retrieve(customerID);
// Use a Stripe test token instead of raw card details
String testToken = "tok_visa"; // Simulates a Visa card
// Attach the test card to the customer
Map<String, Object> sourceParams = new HashMap<>();
sourceParams.put("source", testToken);
Card card = (Card) customer.getSources().create(sourceParams);
System.out.println("Card added successfully: " + card.getId());
}
}
I get
null
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "com.stripe.model.PaymentSourceCollection.create(java.util.Map)" because the return value of "com.stripe.model.Customer.getSources()" is null
at org.example.Application.main(Application.java:82)
I tried to add a card but insted of getting the card ID I get that the sources of the customer are null
You can list a customer's payment methods, sources, or tokens using this API instead : https://docs.stripe.com/api/payment_methods/customer_list?lang=java
Customer customer = Customer.retrieve(customerID);
CustomerListPaymentMethodsParams params =
CustomerListPaymentMethodsParams.builder().setLimit(3L).build();
PaymentMethodCollection paymentMethods = customer.listPaymentMethods(params);
Note though that Tokens are considered deprecated at this point. You really shouldn't be using them anymore. Instead, you should switch to the latest APIs like PaymentIntents, SetupIntents, and PaymentMethods. I recommend referring to the online payment guides that Stripe has on their site to choose an appropriate integration flow that meets your needs : https://docs.stripe.com/payments/online-payments
Some other guides that may be helpful :