# Atualizações do status do pagamento Monitore e verifique o status dos pagamento para poder responder a pagamentos bem-sucedidos e malsucedidos. O *PaymentIntents* (The Payment Intents API tracks the lifecycle of a customer checkout flow and triggers additional authentication steps when required by regulatory mandates, custom Radar fraud rules, or redirect-based payment methods) é atualizado como resposta a ações realizadas pelo cliente ou pela forma de pagamento. Sua integração pode examinar o PaymentIntent para determinar o status da forma de pagamento e permitir que você tome medidas comerciais ou responda a situações que precisem de mais intervenção. Você também pode usar o Stripe Dashboard para configurar sua conta para enviar e-mail sobre o status do pagamento, como pagamentos bem-sucedidos. Altere suas [notificações por e-mail](https://docs.stripe.com/get-started/account/teams.md#email-notifications) nas [configurações do usuário](https://dashboard.stripe.com/settings/user). ## Payment statuses and PaymentIntent statuses The [Payments](https://dashboard.stripe.com/payments) page in the Dashboard shows a payment status for each payment, which you can use to filter the list. This status summarizes the payment but doesn’t include the additional details provided by the PaymentIntent [status](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-status). A PaymentIntent’s `status` tracks the status of a payment and indicates when a payment requires further processing or customer actions. A payment that uses a PaymentIntent might require a payment method, confirmation, or other action to succeed. In the Dashboard, these states map to **Incomplete**. To understand a payment’s incomplete status, click the payment and use [Workbench Inspector](https://docs.stripe.com/workbench/overview.md#inspector) to see the PaymentIntent’s details in JSON. Search for `status` to see the exact value. The following table maps each PaymentIntent `status` to the payment statuses in the Dashboard. Edge cases such as expired attempts and specific decline codes can affect this mapping. Use the API or Workbench Inspector to get the authoritative state. | PaymentIntent `status` | Payment status | Descrição | | ------------------------- | ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `requires_payment_method` | **Incomplete** | Typically occurs if there’s no [latest_charge](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-latest_charge) or the intent hasn’t progressed past collection. Depending on the payment method, amounts, and errors, the payment status can also be **Partially paid**, **Waiting on funding**, or **Failed**. | | `requires_confirmation` | **Incomplete** | Occurs after your customer provides payment information and is ready to confirm. Most integrations skip this state because they submit payment method information when the payment is confirmed. | | `requires_action` | **Incomplete** | Occurs when the payment requires additional actions, such as authenticating with [3D Secure](https://docs.stripe.com/payments/3d-secure.md). The payment status in the Dashboard can also be **Partially paid**, **Waiting on funding**, or **Failed** under certain authentication or error conditions. | | `processing` | **Pending** | Occurs when required actions are complete and the payment uses an *asynchronous payment method* (Asynchronous payment methods can take up to several days to confirm whether the payment has been successful. During this time, the payment can't be guaranteed), such as bank debits. These payment methods can take up to a few days to process. | | `requires_capture` | **Uncaptured** or **Partial capture** | Occurs if your flow uses [separate capture](https://docs.stripe.com/payments/place-a-hold-on-a-payment-method.md). If any amount is received toward the intent, the status is **Partial capture**. If no amount is received, the status is **Uncaptured**. | | `succeeded` | **Succeeded** | A PaymentIntent with a `succeeded` status means the corresponding payment flow is complete. The funds are in your account and you can fulfill the order. If the payment attempt fails (for example, due to a decline), the PaymentIntent’s status returns to `requires_payment_method` so the payment can be retried. Subsequent refunds, disputes, and outcomes are reflected on the Charge. These might change what you see in the Dashboard, even though the PaymentIntent remains `succeeded`. | | `canceled` | **Canceled** | Occurs when the payment is canceled. If the intent was canceled as part of a failed invoice flow and the latest charge failed, the status might show **Failed**. | ## Handle next actions Some payment methods require additional steps, such as authentication, to complete the payment process. Stripe.js handles these automatically when confirming the PaymentIntent, but if you have an advanced integration, you can handle these manually. The PaymentIntent’s [next_action](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action) property exposes the next step that your integration must handle to complete the payment. Available next actions vary by payment method. For a full list, see the [API reference](https://docs.stripe.com/api.md#payment_intent_object-next_action-type). Learn how to [handle a payment method’s required next actions](https://docs.stripe.com/payments/payment-methods/overview.md). ## Verificar o status do PaymentIntent no cliente Ao concluir um pagamento no cliente com a função [confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment), você pode inspecionar o PaymentIntent retornado para determinar seu status atual: ```javascript (async () => { const {paymentIntent, error} = await stripe.confirmPayment({ elements, confirmParams: { return_url: 'https://example.com/order/complete', }, redirect: 'if_required', }); if (error) { // Handle error here } else if (paymentIntent && paymentIntent.status === 'succeeded') { // Handle successful payment here } })(); ``` Os seguintes são os possíveis resultados do uso da função `confirmPayment`: | **Evento** | **O que ocorreu** | **Integração esperada** | | ---------------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------- | | Resolve com um PaymentIntent | O cliente concluiu o pagamento na página de checkout | Informe ao cliente que o pagamento foi bem-sucedido | | Resolve com um erro | O pagamento do cliente falhou na sua página de checkout | Exiba uma mensagem de erro e solicite que o cliente tente fazer o pagamento novamente | A promessa retornada por `confirmPayment` é resolvida quando o processo de pagamento é concluído ou falha com um erro. Quando é concluída com sucesso e retorna um PaymentIntent, o status é sempre `succeeded` (ou `requires_capture`, se estiver configurado para [captura posterior](https://docs.stripe.com/payments/place-a-hold-on-a-payment-method.md)). Quando o pagamento exige uma etapa adicional, como autenticação, a promessa não é resolvida até que essa etapa seja concluída ou expire por tempo limite. ## Verificar o status do PaymentIntent no cliente sem usar confirmPayment Para verificar o status de um PaymentIntent sem usar a função `confirmPayment`, recupere-o de forma independente usando a função [retrievePaymentIntent](https://docs.stripe.com/js/payment_intents/retrieve_payment_intent) e fornecendo o *client secret* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer)). ```javascript (async () => { const {paymentIntent} = await stripe.retrievePaymentIntent(clientSecret); if (paymentIntent && paymentIntent.status === 'succeeded') { // Handle successful payment here } else { // Handle unsuccessful, processing, or canceled payments and API errors here } })(); ``` Veja a seguir alguns [status possíveis](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-status) do PaymentIntent após uma confirmação: | **O que ocorreu** | **Status esperado do PaymentIntent** | | ------------------------------------------------------- | ------------------------------------ | | O cliente concluiu o pagamento na página de checkout | `succeeded` | | O cliente não concluiu o checkout | `requires_action` | | O pagamento do cliente falhou na sua página de checkout | `requires_payment_method` | [Leia mais sobre os status de PaymentIntent](https://docs.stripe.com/payments/paymentintents/lifecycle.md). ## Monitorar um PaymentIntent com webhooks A Stripe pode enviar eventos de *webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) para o seu servidor para notificar quando o status de um PaymentIntent muda, que você pode usar para finalidades como determinar quando executar mercadorias e serviços. Não tente gerenciar a *execução* (Fulfillment is the process of providing the goods or services purchased by a customer, typically after payment is collected) do pedido no lado do cliente porque ele pode sair da página após concluir o pagamento, mas antes do início do processo de execução. Em vez de executar o pedido no lado do cliente, use webhooks para monitorar o evento `payment_intent.succeeded` e processar a execução de forma assíncrona. > É tecnicamente possível usar sondagens em vez de webhooks para monitorar alterações causadas por operações assíncronas (recuperar repetidamente um PaymentIntent para verificar seu status), mas fazer isso é muito menos confiável e pode causar problemas de limitação de taxa. A Stripe [limita a taxa](https://docs.stripe.com/testing.md#rate-limits) das solicitações da API . Portanto, tome cuidado se decidir usar sondagens. Para gerenciar um evento de webhook, crie uma rota no servidor e configure um endpoint de webhook correspondente [no Dashboard](https://dashboard.stripe.com/account/webhooks). A Stripe envia o evento `payment_intent.succeeded` quando o pagamento é bem-sucedido, e o evento `payment_intent.payment_failed` quando o pagamento falha. O conteúdo do webhook inclui o objeto PaymentIntent. O exemplo abaixo mostra como gerenciar ambos os eventos: #### Ruby ```ruby require 'sinatra' require 'stripe' post '/webhook' do payload = request.body.read sig_header = request.env['HTTP_STRIPE_SIGNATURE'] event = nil begin event = Stripe::Webhook.construct_event( payload, sig_header, endpoint_secret ) rescue JSON::ParserError => e # Invalid payload status 400 return rescue Stripe::SignatureVerificationError => e # Invalid signature status 400 return end case event['type'] when 'payment_intent.succeeded' intent = event['data']['object'] puts "Succeeded:", intent['id'] # Fulfill the customer's purchase when 'payment_intent.payment_failed' intent = event['data']['object'] error_message = intent['last_payment_error'] && intent['last_payment_error']['message'] puts "Failed:", intent['id'], error_message # Notify the customer that payment failed end status 200 end ``` Quando o pagamento não é bem-sucedido, você pode obter mais detalhes inspecionando a propriedade `last_payment_error` do PaymentIntent. É possível notificar o cliente que o pagamento não foi concluído e recomendar que ele tente outra forma de pagamento. Reutilize o mesmo PaymentIntent para continuar a rastrear a compra do cliente. ### Gerenciar eventos de webhook específicos A lista a seguir descreve como gerenciar eventos de webhook: | Evento | Descrição | Próximas etapas | | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | | `processing` | O pagamento do cliente foi enviado com sucesso para a Stripe. Aplicável apenas a formas de pagamento com [confirmação de sucesso atrasada](https://docs.stripe.com/payments/payment-methods.md#payment-notification). | Esperar a conclusão ou falha do pagamento iniciado. | | `succeeded` | O pagamento do cliente foi confirmado. | Execute o pedido de mercadorias ou serviços. | | `amount_capturable_updated` | O pagamento do cliente foi autorizado e está pronto para captura. | Capturar os fundos disponíveis para pagamento | | `payment_failed` | O pagamento do cliente foi recusado pela bandeira do cartão ou expirou por outros motivos… | Entre em contato com o cliente por e-mail ou notificação push e solicite que ele forneça outra forma de pagamento | Para testar webhooks localmente, você pode usar o [Stripe CLI](https://docs.stripe.com/stripe-cli.md). Após instalá-lo, você poderá encaminhar eventos ao seu servidor: ```bash stripe listen --forward-to localhost:4242/webhook Ready! Your webhook signing secret is '{{WEBHOOK_SIGNING_SECRET}}' (^C to quit) ``` Saiba mais sobre [configurar webhooks](https://docs.stripe.com/webhooks.md). ## Identificar cobranças em um PaymentIntent Quando você tenta receber um pagamento de um cliente, o PaymentIntent cria uma [Charge](https://docs.stripe.com/api/charges.md). Para ver o ID da cobrança mais recente, inspecione a propriedade [latest_charge](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-latest_charge) do PaymentIntent: #### Ruby ```ruby # Don't put any keys in code. See https://docs.stripe.com/keys-best-practices. # Find your keys at https://dashboard.stripe.com/apikeys. client = Stripe::StripeClient.new('<>') intent = client.v1.payment_intents.retrieve('{{PAYMENT_INTENT_ID}}') latest_charge = intent.latest_charge ``` Para ver todas as cobranças associadas a um PaymentIntent, incluindo as cobranças malsucedidas, [liste todas as cobranças](https://docs.stripe.com/api/charges/list.md#list_charges-payment_intent) e especifique o parâmetro `payment_intent​`. ```curl curl -G https://api.stripe.com/v1/charges \ -u "<>:" \ -d "payment_intent={{PAYMENTINTENT_ID}}" ```