Stripe foreign bank card payment function Guide (Java)
brief introduction
The purpose of writing this article is ~ ~ no purpose. There are many online payment codes for stripe bank card, which are well written, but they are too many and too complicated to be systematic. Therefore, combined with the practical application in the project, I summarized some commonly used methods, hoping to give you some help.
Of course, my guide is not very complete, and I will continue to supplement it if I have the opportunity in the future.
Stripe payment steps
Open stripe account
This is the most important step. You don't need to read the content behind the account~~
After the account is opened, we need to obtain the key. The stripe key is divided into online environment key and test environment key. We can apply for the test key because we only do the test. All the things discussed below are mainly based on the test environment
There are two types of keys:
Publishable key (pk_test): used when the front end implements the stripe interface
Key (sk_test): used when the backend implements the stripe method
Because it is a test and all payments are operated by my background, I only need to use sk_test is enough. The same is true for online environment
So far, all preparations are ready, and we begin to realize the bank card payment function.
Stripe Api core functions
The following is some information provided by the official documents. Because the official documents are in pure English, it's more troublesome to find them. Just record some documents used
StripeApi documentation
The Stripe interface returns an error code document
Stripe test bank card number
If the test account does not want to see the above documents, you can use the following one
General payment succeeded 4242 4242 4242 4242
There are many core functions of stripe payment, including but not limited to Token, Card, Customers, PaymentIntent, PaymentMethod, Source and Charge
Because the business logic is not so extensive, I don't cover it all. All the following only explain the core functions I use
Customers
As the name suggests, customber is a user. All users who need to pay with a bank card need to create their own independent account on stripe, and it is best to be unique with your business users. Of course, this is based on the actual situation. You can be not unique if you want to do so.
Create Customers
Stripe.apiKey = your key; //The parameters when creating a customer are easy to identify later. See the api for specific parameters. It is recommended that the description parameter be passed here. The value here will be displayed on the stripe platform for later observation Map<String, Object> params = new HashMap<>(); params.put( "description", "My First Test Customer (created for API docs)" ); Customer customer = Customer.create(params); //Unique identification of the stripe platform Customers String customerId = customer.getId();
Tokens
Token is a process used by Stripe to collect sensitive card or bank account information. When the user fills in the card number, expiration date, CVC and other information of the bank card, Stripe will generate a token containing these information, so as to ensure that no sensitive card data interacts with our own server during transmission and reduce the loss rate of real information of customers. Our own server can get the token and pay.
The Token cannot be stored and used multiple times. To store the information of the card for later use, you can create a user. Add card information to the user.
Create bank card number related Token
Stripe.apiKey = your key; Map<String, Object> card = new HashMap<>(); card.put("number", "4242424242424242"); card.put("exp_month", 2); card.put("exp_year", 2022); card.put("cvc", "314"); Map<String, Object> params = new HashMap<>(); params.put("card", card); Token token = Token.create(params); //It can be used when creating a bank card later. There is no need to fill in the bank card related information in the parameter transfer process String tokenId = token.getId();
Cards
You can store multiple cards on one customer and charge that customer. You can also store multiple debit cards on the recipient for later transfer to these debit cards.
Create Card and bind with Customers
When Customers bind a Card for the first time, if the binding is successful, this Card will become the default Card for payment.
Stripe.apiKey = your key; Map<String, Object> retrieveParams = new HashMap<>(); List<String> expandList = new ArrayList<>(); expandList.add("sources"); retrieveParams.put("expand", expandList); Customer customer = Customer.retrieve( "Customers corresponding id", retrieveParams, null ); Map<String, Object> params = new HashMap<>(); params.put("source", "Bank card tokenId"); Card card = (Card) customer.getSources().create(params); //It is recommended to save the card number String cardId = card.getId();
Modify the default payment Card of Customers
If Customers have multiple cards, you need to change the default Card for payment.
Stripe.apiKey = your key; Map<String, Object> retrieveParams = new HashMap<>(); List<String> expandList = new ArrayList<>(); expandList.add("sources"); retrieveParams.put("expand", expandList); Customer customer = Customer.retrieve("Customers corresponding id", retrieveParams,null); Map<String, Object> params = new HashMap<>(); params.put("default_source", "Need to be set as default Card of Id"); customer.update(params);
Modify Card
Only one parameter can be modified to modify the Card. If other parameters are written, the method will report an error
Stripe.apiKey = your key; Map<String, Object> retrieveParams = new HashMap<>(); List<String> expandList = new ArrayList<>(); expandList.add("sources"); retrieveParams.put("expand", expandList); Customer customer = Customer.retrieve( "Customers corresponding id", retrieveParams, null ); Card card = customer.getSources().retrieve( "Need modification Card of Id" ); //modify parameters Map<String, Object> params = new HashMap<>(); params.put("name", "Jenny Rosen"); Card updatedCard = (Card) card.update(params);
Delete Card
If the default Card is deleted, the system will find the last added Card in chronological order by default and set it as the default Card.
Stripe.apiKey = your key; Map<String, Object> retrieveParams = new HashMap<>(); List<String> expandList = new ArrayList<>(); expandList.add("sources"); retrieveParams.put("expand", expandList); Customer customer = Customer.retrieve( "Customers corresponding id", retrieveParams, null ); Card card = customer.getSources().retrieve( "Need to delete Card of Id" ); Card deletedCard = (Card) card.delete();
Charges
To Charge a credit or debit card, create a Charge object. You can retrieve and refund individual fees and list all fees. The fee is identified by a unique random ID.
PS: there are many ways to pay for stripe, such as directly deducting fees from the default card, or calling back to monitor the deduction of fees. Because the deduction operations are in the background and there is no interaction with the front end, I directly use the default card deduction method
Map<String, Object> params = new HashMap<>(); //Amount, actual amount * 100, minimum payment amount is 0.5 params.put("amount", 2000); //Monetary unit, in figures, bank card deduction fee, currency conversion, stripe internal self conversion, we don't need to care params.put("currency", "aud"); params.put("customer", "Customers corresponding id"); params.put( "description", "My First Test Charge (created for API docs)" ); //Whether to capture the cost immediately. The default is true. If it is false, the fee will be authorized (or pre authorized) and need to be captured later. Uncapped fees will expire within 7 days. params.put("capture", true); Charge charge = Charge.create(params); //Payment status can be obtained in real time if ("succeeded".equals(charge.getStatus())) { //After the transaction is successful, we need to update our order table and modify business parameters, which are omitted here return true; } else { return false; }
Webhook Endpoints
Configure the Webhook endpoint through the API to notify you of events that occur in your Stripe account or associated account.
Self use Java tool class
This tool class is only operated according to the actual business, which may be different from your payment scenarios. It can be modified according to the understanding of api documents. The following is for reference only.
<dependency> <groupId>com.stripe</groupId> <artifactId>stripe-java</artifactId> <version>${stripe.version}</version> </dependency>
/** * stripe Payment instruments * * @author zhouquan * @date 2021-01-26 13:44:00 */ @Component public class StripePayUtils { private static final String key = "your key"; /** * Create initial user * @param description Description - user number * @return * @throws StripeException */ public String createStripeCustomNoCard(String description) throws StripeException { Stripe.apiKey = key; Map<String, Object> params = new HashMap<>(); params.put( "description", description); Customer customer = Customer.create(params); return customer.getId(); } /** * Update user bound bank card * @param stripeMemberId Customer stripeId * @param cardParam Bank card parameters * @return * @throws StripeException */ public String updateStripeCustomWithCard(String stripeMemberId, Map<String, Object> cardParam) throws StripeException { Stripe.apiKey = key; //Create a bank card Token and borrow stripe to verify whether the bank card information is correct String cardTokenId = createCardToken(cardParam); Map<String, Object> retrieveParams = new HashMap<>(); List<String> expandList = new ArrayList<>(); expandList.add("sources"); retrieveParams.put("expand", expandList); Customer customer = Customer.retrieve(stripeMemberId, retrieveParams,null); Map<String, Object> params = new HashMap<>(); params.put("source", cardTokenId); Card card = (Card) customer.getSources().create(params); return card.getId(); } /** * Modify default payment bank card * @param stripeMemberId Customer stripeId * @param stripeCardId Bank card stripeId * @throws StripeException */ public void updateStripeDefaultCard(String stripeMemberId, String stripeCardId) throws StripeException { Stripe.apiKey = key; Map<String, Object> retrieveParams = new HashMap<>(); List<String> expandList = new ArrayList<>(); expandList.add("sources"); retrieveParams.put("expand", expandList); Customer customer = Customer.retrieve(stripeMemberId, retrieveParams,null); Map<String, Object> params = new HashMap<>(); params.put("default_source", stripeCardId); customer.update(params); } /** * Delete user bound bank card * @param stripeMemberId Customer stripeId * @param cardId Bank card stripeId * @return * @throws StripeException */ public void deleteCard(String stripeMemberId, String cardId) throws StripeException { Stripe.apiKey = key; Map<String, Object> retrieveParams = new HashMap<>(); List<String> expandList = new ArrayList<>(); expandList.add("sources"); retrieveParams.put("expand", expandList); Customer customer = Customer.retrieve( stripeMemberId, retrieveParams, null ); Card card = (Card) customer.getSources().retrieve(cardId); Card deletedCard = (Card) card.delete(); } /** * Generate card token (identification card right or wrong) * @param cardParam number Card number exp_month validity month exp_year validity year cvc security code * @return * @throws StripeException */ public String createCardToken(Map<String, Object> cardParam) throws StripeException { Stripe.apiKey = key; //Generate card token Map<String, Object> params = new HashMap<>(); params.put("card", cardParam); Token token = Token.create(params); return token.getId(); } /** * Modify bank card information * @param stripeMemberId Customer stripeId * @param stripeCardId Bank card stripeId * @param params Parameters to be modified * @throws StripeException */ public void updateCard(String stripeMemberId, String stripeCardId,Map<String, Object> params) throws StripeException { Stripe.apiKey = key; Map<String, Object> retrieveParams = new HashMap<>(); List<String> expandList = new ArrayList<>(); expandList.add("sources"); retrieveParams.put("expand", expandList); Customer customer = Customer.retrieve(stripeMemberId, retrieveParams,null); Card card = (Card) customer.getSources().retrieve(stripeCardId); card.update(params); } /** * Synchronous payment * @param stripeMemberId Customer stripeId * @param money Actual payment amount * @param moneyType Monetary unit * @param description Order description * @return * @throws StripeException */ public boolean charge(String stripeMemberId, BigDecimal money, String moneyType, String description) throws StripeException { Stripe.apiKey = key; //Initiate payment Map<String, Object> payParams = new HashMap<>(); //1 yuan = 100 payParams.put("amount", money.multiply(new BigDecimal(100)).longValue()); payParams.put("currency", moneyType); payParams.put("description", description); payParams.put("customer", stripeMemberId); payParams.put("capture", true); Charge charge = Charge.create(payParams); System.err.println(charge.toString()); //charge payment is a synchronous notification if ("succeeded".equals(charge.getStatus())) { //After the transaction is successful, we need to update our order table and modify business parameters, which are omitted here return true; } else { return false; } } /** * Capture the error status code returned by the stripe platform * @param code */ public void catchError(String code){ switch (code){ case "account_number_invalid": //Incorrect bank card number throw new RRException(null, ErrorPromptEnum.BANK_STRIPE_account_number_invalid.getValue()); case "balance_insufficient": //Insufficient account balance throw new RRException(null, ErrorPromptEnum.BANK_STRIPE_balance_insufficient.getValue()); case "bank_account_declined": //The bank account provided has not been verified or is not supported and cannot be used for charging throw new RRException(null, ErrorPromptEnum.BANK_STRIPE_bank_account_declined.getValue()); case "bank_account_exists": //Account already exists throw new RRException(null, ErrorPromptEnum.BANK_STRIPE_bank_account_exists.getValue()); case "bank_account_unusable": //The bank account provided cannot be used for payment. You must use a different bank account. throw new RRException(null, ErrorPromptEnum.BANK_STRIPE_bank_account_unusable.getValue()); case "expired_card": //Card expired throw new RRException(null, ErrorPromptEnum.BANK_STRIPE_expired_card.getValue()); case "incorrect_cvc": //The security code of the card is incorrect throw new RRException(null, ErrorPromptEnum.BANK_STRIPE_incorrect_cvc.getValue()); case "incorrect_number": //Incorrect card number throw new RRException(null, ErrorPromptEnum.BANK_STRIPE_incorrect_number.getValue()); case "incorrect_zip": //The zip code of the card is incorrect throw new RRException(null, ErrorPromptEnum.BANK_STRIPE_incorrect_zip.getValue()); case "instant_payouts_unsupported": //This card does not support instant payment throw new RRException(null, ErrorPromptEnum.BANK_STRIPE_instant_payouts_unsupported.getValue()); case "invalid_cvc": //The security code of the card is invalid throw new RRException(null, ErrorPromptEnum.BANK_STRIPE_invalid_cvc.getValue()); case "invalid_expiry_month": //The validity period of the card is incorrect throw new RRException(null, ErrorPromptEnum.BANK_STRIPE_invalid_expiry_month.getValue()); case "invalid_expiry_year": //The validity period of the card is incorrect throw new RRException(null, ErrorPromptEnum.BANK_STRIPE_invalid_expiry_year.getValue()); case "invalid_number": //Invalid card number throw new RRException(null, ErrorPromptEnum.BANK_STRIPE_invalid_number.getValue()); default: //System abnormality throw new RRException(code, ErrorPromptEnum.BANK_STRIPE_error.getValue()); } } }
ending
The above is a preliminary exploration of stripeApi. It is not very comprehensive. Many functions are not used. To thoroughly understand this payment, there is a long way to go~~~