Set up future payments
Learn how to save payment details in a Checkout session and charge your customers later.
To collect customer payment details that you can reuse later, use Checkout’s setup mode. Setup mode uses the Setup Intents API to create Payment Methods.
Confira nosso exemplo completo e funcional no GitHub.
Configurar a StripeLado do servidor
Primeiro, você precisa de uma conta Stripe. Inscreva-se aqui.
Use nossas bibliotecas oficiais para acessar a API da Stripe no seu aplicativo:
Criar uma sessão de checkoutLado do clienteLado do servidor
Adicione um botão de checkout ao seu site para invocar um endpoint do lado do servidor e criar uma Sessão do Checkout.
<html> <head> <title>Checkout</title> </head> <body> <form action="/create-checkout-session" method="POST"> <button type="submit">Checkout</button> </form> </body> </html>
To create a setup mode Session, use the mode parameter with a value of setup when creating the Session. You can optionally specify the customer parameter to automatically attach the created payment method to an existing customer. Checkout uses Dynamic payment methods by default, which requires you to pass the currency parameter when using setup mode.
Append the {CHECKOUT_ template variable to the success_ to get access to the Session ID after your customer successfully completes a Checkout Session. After creating the Checkout Session, redirect your customer to the URL returned in the response.
formas de pagamento
Por padrão, a Stripe habilita cartões e outras formas de pagamento comuns. É possível ativar ou desativar formas de pagamento individuais no Stripe Dashboard. No Checkout, a Stripe avalia a moeda e as restrições e apresenta dinamicamente as formas de pagamento aceitas ao cliente.
Para ver como as formas de pagamento aparecem para os clientes, informe um ID de transação ou defina um valor e moeda de pedido no Dashboard.
Você pode ativar Apple Pay e Google Pay nas configurações de formas de pagamento. Por padrão, o Apple Pay fica ativado, e o Google Pay, desativado. No entanto, em alguns casos, a Stripe remove-os mesmo quando estão ativados. Removemos o Google Pay se você ativar o imposto automático sem coletar um endereço de entrega.
As páginas hospedadas na Stripe do Checkout não precisam de mudanças na integração para habilitar Apple Pay ou Google Pay. A Stripe trata esses pagamentos da mesma forma que os outros pagamentos com cartão.
Acessar a sessão do CheckoutLado do servidor
Depois que o cliente finaliza a sessão do Checkout, você precisa acessar o objeto Session, o que pode ser feito de duas formas:
- Asynchronously: Handle
checkout.webhooks, which contain a Session object. Learn more about setting up webhooks.session. completed - Synchronously: Obtain the Session ID from the
success_when a user redirects back to your site. Use the Session ID to retrieve the Session object.url
A melhor opção depende de sua tolerância a abandono de sessão, porque nem sempre o cliente chega a success_ depois de concluir o pagamento. É possível que o cliente feche a guia do navegador antes do redirecionamento. Gerenciar webhooks impede que sua integração sofra esse tipo de abandono de sessão.
After you have retrieved the Session object, get the value of the setup_ key, which is the ID for the SetupIntent created during the Checkout Session. A SetupIntent is an object used to set up the customer’s bank account information for future payments.
Exemplo de conteúdo de checkout.:
{ "id": "evt_1Ep24XHssDVaQm2PpwS19Yt0", "object": "event", "api_version": "2019-03-14", "created": 1561420781, "data": { "object": { "id": "cs_test_MlZAaTXUMHjWZ7DcXjusJnDU4MxPalbtL5eYrmS2GKxqscDtpJq8QM0k", "object": "checkout.session", "billing_address_collection": null, "client_reference_id": null, "customer": "", "customer_email": null, "display_items": [], "mode": "setup", "setup_intent": "seti_1EzVO3HssDVaQm2PJjXHmLlM", "submit_type": null, "subscription": null, "success_url": "https://example.com/success" } }, "livemode": false, "pending_webhooks": 1, "request": { "id": null, "idempotency_key": null }, "type": "checkout.session.completed" }
Registre o ID de setup_ para a próxima etapa.
Acessar o SetupIntentLado do servidor
Using the setup_ ID, retrieve the SetupIntent object. The returned object contains a payment_ ID that you can attach to a customer in the next step.
Nota
If you’re requesting this information synchronously from the Stripe API (as opposed to handling webhooks), you can combine the previous step with this step by expanding the SetupIntent object in the request to the /v1/checkout/session endpoint. Doing this prevents you from having to make two network requests to access the newly created PaymentMethod ID.
Charge the payment method laterLado do servidor
If you didn’t create the Checkout Session with an existing customer, use the ID of the PaymentMethod to attach the PaymentMethod to a Customer. After you attach the PaymentMethod to a customer, you can make an off-session payment using a PaymentIntent:
- Set customer to the ID of the Customer and payment_method to the ID of the PaymentMethod.
- Set off_session to
trueto indicate that the customer isn’t in your checkout flow during a payment attempt and can’t fulfill an authentication request made by a partner, such as a card issuer, bank, or other payment institution. If, during your checkout flow, a partner requests authentication, Stripe requests exemptions using customer information from a previous on-session transaction. If the conditions for exemption aren’t met, the PaymentIntent might throw an error. - Set the value of the PaymentIntent’s confirm property to
true, which causes confirmation to occur immediately when you create the PaymentIntent.
When a payment attempt fails, the request also fails with a 402 HTTP status code and the status of the PaymentIntent is requires_payment_method. Notify your customer to return to your application (for example, by sending an email or in-app notification) and direct your customer to a new Checkout Session to select another payment method.