Reputation: 351
I have a need to add a card to a pre-existing customer. Here's what I did:
card_token = request.POST('stripeToken')
customer = stripe.Customer.retrieve('cus_xxxxxxxxxx')
customer.Cards.create(card=card_token)
It is # 3 that I'm having trouble because it looks like the customer doesn't have method Cards, but I've seen people done it elsewhere.
How should I achieve this?
Upvotes: 34
Views: 32367
Reputation: 8727
2019 Update: Things have changed a bit with Strong Customer Authentication (SCA) requirements in Europe; you'll now probably want to use the Setup Intents API to collect card details upfront for future payments.
This new API is both PCI and SCA compliant. You can learn more here
or check out this sample code on GitHub: https://github.com/stripe-samples/saving-card-without-payment.
You can also do this entirely with Checkout now as well!
Upvotes: 6
Reputation: 1250
Example (customerId - cus_xxxxxxxxxx):
Stripe.apiKey = stripeApiKey;
Customer customer = Customer.retrieve(customerId);
Map<String, Object> cardParams = new HashMap<String, Object>();
cardParams.put("number", "4242424242424242");
cardParams.put("exp_month", "12");
cardParams.put("exp_year", "2018");
cardParams.put("cvc", "314");
Map<String, Object> tokenParams = new HashMap<String, Object>();
tokenParams.put("card", cardParams);
Token cardToken = Token.create(tokenParams);
Map<String, Object> sourceParams = new HashMap<String, Object>();
sourceParams.put("source", cardToken.getId()); //?
Card source = (Card) customer.getSources().create(sourceParams);
logger.info("Card created: " + source.toString());
Upvotes: -1
Reputation: 25552
If you are on the 2015-02-18
API version or later then the cards
attribute has been changed to sources
as you can see in the changelog
The documentation on the Create Card API shows the following code now:
customer = stripe.Customer.retrieve('cus_xxxxxxxxxx')
customer.sources.create(card=card_token)
You can find your API version in the API keys settings in the dashboard and you can also use the Stripe-Version
header to force your API request to an older API version so that cards
still work as explained in the Versioning documentation:
stripe.api_version = '2015-01-26'
Upvotes: 30