# Accept a payment with Amazon Pay Learn how to set up your integration with Amazon Pay. # Checkout > This is a Checkout for when payment-ui is checkout. View the full page at https://docs.stripe.com/payments/amazon-pay/accept-a-payment?payment-ui=checkout. > A Stripe pode apresentar automaticamente as formas de pagamento relevantes aos seus clientes avaliando moedas, restrições de formas de pagamento e outros parâmetros. > > - Siga o guia [Aceitar um pagamento](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=checkout&ui=stripe-hosted) para elaborar uma integração de checkout que usa [formas de pagamento dinâmicas](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). - Se você não quiser usar o formas de pagamento dinâmico, siga as etapas abaixo para configurar manualmente as formas de pagamento em sua integração de checkout. Amazon Pay is a [single-use](https://docs.stripe.com/payments/payment-methods.md#usage) payment method where customers are required to [authenticate](https://docs.stripe.com/payments/payment-methods.md#customer-actions) their payment. Customers are redirected from your website or app, authorize the payment with Amazon, then return to your website or app. You get [immediate notification](https://docs.stripe.com/payments/payment-methods.md#payment-notification) of whether the payment succeeded or failed. ## Determine compatibility To support Amazon Pay payments, a Checkout Session must satisfy all of the following conditions: - *Prices* (Prices define how much and how often to charge for products. This includes how much the product costs, what currency to use, and the interval if the price is for subscriptions) for all line items must be in the same currency. - If you have line items in different currencies, create separate Checkout Sessions for each currency. ## Accept a payment > Crie uma integração para [aceitar um pagamento](https://docs.stripe.com/payments/accept-a-payment.md?integration=checkout) com o Checkout antes de usar este guia. This guides you through enabling Amazon Pay and shows the differences between accepting payments using dynamic payment methods and manually configuring payment methods. ### Enable Amazon Pay as a payment method Ao criar uma [sessão do Checkout](https://docs.stripe.com/api/checkout/sessions.md), é preciso: 1. Add `amazon_pay` to the list of `payment_method_types`. 1. Make sure all `line_items` use the same currency. #### Stripe-hosted page ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d "line_items[0][price_data][currency]=usd" \ -d "line_items[0][price_data][product_data][name]=T-shirt" \ -d "line_items[0][price_data][unit_amount]=2000" \ -d "line_items[0][quantity]=1" \ -d mode=payment \ -d "payment_method_types[0]=card" \ -d "payment_method_types[1]=amazon_pay" \ --data-urlencode "success_url=https://example.com/success" ``` #### Embedded form ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d "line_items[0][price_data][currency]=usd" \ -d "line_items[0][price_data][product_data][name]=T-shirt" \ -d "line_items[0][price_data][unit_amount]=2000" \ -d "line_items[0][quantity]=1" \ -d mode=payment \ -d "payment_method_types[0]=card" \ -d "payment_method_types[1]=amazon_pay" \ --data-urlencode "return_url=https://example.com/return" \ -d ui_mode=embedded_page ``` ### Executar pedidos After accepting a payment, learn how to [fulfill orders](https://docs.stripe.com/checkout/fulfillment.md). ## Test your integration When testing your Checkout integration, select Amazon Pay as the payment method and click the **Pay** button. ![](https://b.stripecdn.com/docs-statics-srv/assets/merchant_checkout_amazon_pay_visible.4ee046f5f5cb1d06c4661de229ca6fcd.png) ## See also - [More about Amazon Pay](https://docs.stripe.com/payments/amazon-pay.md) - [Checkout fulfillment](https://docs.stripe.com/checkout/fulfillment.md) - [Customizing Checkout](https://docs.stripe.com/payments/checkout/customization.md) # Elements > This is a Elements for when payment-ui is elements. View the full page at https://docs.stripe.com/payments/amazon-pay/accept-a-payment?payment-ui=elements. This guide describes how to embed a custom Stripe payment form in your website or application using the [Payment Element](https://docs.stripe.com/payments/payment-element.md). The Payment Element allows you to support Amazon Pay and other payment methods automatically. For more configurations and customizations, refer to the [Accept a Payment](https://docs.stripe.com/payments/accept-a-payment.md) integration guide. ## Set up Stripe [Server-side] Primeiro, você precisa de uma conta Stripe. [Inscreva-se agora](https://dashboard.stripe.com/register). Use nossas bibliotecas oficiais para acessar a API da Stripe no seu aplicativo: #### Ruby ```bash # Available as a gem sudo gem install stripe ``` ```ruby # If you use bundler, you can add this line to your Gemfile gem 'stripe' ``` ## Create a PaymentIntent [Server-side] A [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) is an object that represents your intent to collect payment from a customer and tracks the lifecycle of the payment process through each stage. #### Gerencie formas de pagamento no Dashboard Você pode gerenciar formas de pagamento no [Dashboard](https://dashboard.stripe.com/settings/payment_methods). A Stripe processa a devolução de formas de pagamento qualificadas com base em fatores como valor, moeda e fluxo de pagamento da transação. Create a PaymentIntent on your server with an amount and currency. Before creating the PaymentIntent, make sure to turn **Amazon Pay** on in the [payment methods settings](https://dashboard.stripe.com/settings/payment_methods) page. > Always decide how much to charge on the server side, a trusted environment, as opposed to the client. This prevents customers from being able to choose their own prices. ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=usd \ -d "automatic_payment_methods[enabled]=true" ``` #### List payment methods manually If you don’t want to use the Dashboard or you want to manually specify payment methods, you can list them using the `payment_method_types` attribute. Create a PaymentIntent on your server with an amount, currency, and a list of payment methods. > Always decide how much to charge on the server side, a trusted environment, as opposed to the client. This prevents customers from being able to choose their own prices. ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=usd \ -d "payment_method_types[]=amazon_pay" ``` ### Recuperar o segredo do cliente O PaymentIntent inclui um *segredo do cliente* (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)) que o lado do cliente usa para concluir com segurança o processo de pagamento. Você pode usar abordagens diferentes para enviar a senha do cliente ao lado do cliente. #### Aplicativo de página única Recupere o segredo do cliente de um endpoint do servidor usando a função `fetch` do navegador. Essa abordagem é melhor quando o lado do cliente é um aplicativo com uma única página, principalmente se criado com uma estrutura de front-end moderna como o React. Crie o endpoint do servidor que envia o segredo do cliente: #### Ruby ```ruby get '/secret' do intent = # ... Create or retrieve the PaymentIntent {client_secret: intent.client_secret}.to_json end ``` Em seguida, obtenha o segredo do cliente com JavaScript no lado do cliente: ```javascript (async () => { const response = await fetch('/secret'); const {client_secret: clientSecret} = await response.json(); // Render the form using the clientSecret })(); ``` #### Renderização do lado do servidor Passe o segredo do cliente do servidor ao cliente. Essa abordagem funciona melhor quando o aplicativo gera conteúdo estático no servidor antes de enviá-lo ao navegador. Adicione o [client_secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) ao formulário de checkout. No código do lado do servidor, recupere o segredo do cliente do PaymentIntent: #### Ruby ```erb
``` ```ruby get '/checkout' do @intent = # ... Fetch or create the PaymentIntent erb :checkout end ``` ## Collect payment details [Client-side] Colete dados de pagamento no cliente com o [Payment Element](https://docs.stripe.com/payments/payment-element.md). O Payment Element é um componente de IU que simplifica a coleta de dados de pagamento para diversas formas de pagamento. O Payment Element contém um iframe que envia dados de pagamento com segurança à Stripe por uma conexão HTTPS. Evite colocar o Payment Element dentro de outro iframe porque algumas formas de pagamento exigem o redirecionamento para outra página para confirmação do pagamento. Se você optar por usar um iframe e quiser aceitar Apple Pay ou Google Pay, o iframe deve ter o atributo [permitir](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attr-allowpaymentrequest) definido como igual a `"pagamento *"`. O endereço da página de Checkout deve começar com `https://` rather em vez de `http://` for para que sua integração funcione corretamente. Você pode testar sua integração sem usar HTTPS, mas lembre-se de [habilitá-lo](https://docs.stripe.com/security/guide.md#tls) quando estiver pronto para aceitar pagamentos em tempo real. #### HTML + JS ### Configurar o Stripe.js O Payment Element está automaticamente disponível como um recurso do Stripe.js. Inclua o script Stripe.js em sua página de checkout adicionando-o ao `head` do arquivo HTML. Sempre carregue Stripe.js diretamente de js.stripe.com para manter a conformidade com PCI. Não inclua o script em um pacote nem hospede pessoalmente uma cópia dele. ```html Checkout ``` Crie uma instância de Stripe com o seguinte JavaScript em sua página de checkout: ```javascript // Set your publishable key: remember to change this to your live publishable key in production // See your keys here: https://dashboard.stripe.com/apikeys const stripe = Stripe('<>'); ``` ### Adicione o Element Pagamento à sua página de pagamentos O Payment Element precisa de um lugar para residir na sua página de pagamentos. Crie um node DOM vazio (contêiner) com um ID único no seu formulário de pagamento: ```html
``` Quando o formulário anterior for carregado, crie uma instância do Payment Element e monte-a no nó DOM do contêiner. Passe o [segredo do cliente](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) da etapa anterior em `options` quando criar a instância do [Elements](https://docs.stripe.com/js/elements_object/create): Administre cuidadosamente o segredo do cliente, pois ele pode finalizar a cobrança. Não registre em log, incorpore em URLs nem exponha esse segredo a ninguém, exceto para o próprio cliente. ```javascript const options = { clientSecret: '{{CLIENT_SECRET}}', // Fully customizable with appearance API. appearance: {/*...*/}, }; // Set up Stripe.js and Elements to use in checkout form, passing the client secret obtained in a previous stepconst elements = stripe.elements(options); // Optional: Autofill user's saved payment methods. If the customer's // email is known when the page is loaded, you can pass the email // to the linkAuthenticationElement on mount: // // linkAuthenticationElement.mount("#link-authentication-element", { // defaultValues: { // email: 'jenny.rosen@example.com', // } // }) // Create and mount the Payment Element const paymentElementOptions = { layout: 'accordion'}; const paymentElement = elements.create('payment', paymentElementOptions); paymentElement.mount('#payment-element'); ``` #### React ### Configurar o Stripe.js Instale o [React Stripe.js](https://www.npmjs.com/package/@stripe/react-stripe-js) e o [carregador Stripe.js](https://www.npmjs.com/package/@stripe/stripe-js) do registro público npm: ```bash npm install --save @stripe/react-stripe-js @stripe/stripe-js ``` ### Adicione e configure o provedor do Elements à sua página de pagamento Para usar o componente Payment Element, encapsule o componente da página de checkout em um [provedor do Elements](https://docs.stripe.com/sdks/stripejs-react.md#elements-provider). Chame `loadStripe` com sua chave publicável e passe a `Promise` retornada para o provedor `Elements`. Além disso, passe o [segredo do cliente](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) da etapa anterior como `options` ao fornecedor do `Elements`. ```jsx import React from 'react'; import ReactDOM from 'react-dom'; import {Elements} from '@stripe/react-stripe-js'; import {loadStripe} from '@stripe/stripe-js'; import CheckoutForm from './CheckoutForm'; // Make sure to call `loadStripe` outside of a component’s render to avoid // recreating the `Stripe` object on every render. const stripePromise = loadStripe('<>'); function App() { const options = { // passing the client secret obtained in step 3 clientSecret: '{{CLIENT_SECRET}}', // Fully customizable with appearance API. appearance: {/*...*/}, }; return ( ); }; ReactDOM.render(, document.getElementById('root')); ``` ### Adicione o componente do Element Pagamento Use o componente `PaymentElement` para criar seu formulário: ```jsx import React from 'react'; import {PaymentElement} from '@stripe/react-stripe-js'; const CheckoutForm = () => { return (
// Optional: Autofill user's saved payment methods. If the customer's // email is known when the page is loaded, you can pass the email // to the linkAuthenticationElement // // ); }; export default CheckoutForm; ``` ## Enviar o pagamento para a Stripe [Client-side] Use [stripe.confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment) para concluir o pagamento utilizando os detalhes do Payment Element. Forneça um [return_url](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-return_url) a essa função para indicar para onde a Stripe deve redirecionar o usuário após a conclusão do pagamento. Seu usuário pode ser redirecionado primeiro para um site intermediário, como uma página de autorização bancária, antes de ser redirecionado para o `return_url`. Os pagamentos com cartão são redirecionados imediatamente para o `return_url` quando um pagamento é finalizado. #### HTML + JS ```javascript const form = document.getElementById('payment-form'); form.addEventListener('submit', async (event) => { event.preventDefault(); const {error} = await stripe.confirmPayment({ //`Elements` instance that was used to create the Payment Element elements, confirmParams: { return_url: 'https://example.com/order/123/complete', }, }); if (error) { // This point will only be reached if there is an immediate error when // confirming the payment. Show error to your customer (for example, payment // details incomplete) const messageContainer = document.querySelector('#error-message'); messageContainer.textContent = error.message; } else { // Your customer will be redirected to your `return_url`. For some payment // methods like iDEAL, your customer will be redirected to an intermediate // site first to authorize the payment, then redirected to the `return_url`. } }); ``` #### React Para chamar [stripe.confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment) do seu componente de formulário de pagamento, use os hooks [useStripe](https://docs.stripe.com/sdks/stripejs-react.md#usestripe-hook) e [useElements](https://docs.stripe.com/sdks/stripejs-react.md#useelements-hook). Se preferir componentes de classe tradicionais em vez de hooks, use um [ElementsConsumer](https://docs.stripe.com/sdks/stripejs-react.md#elements-consumer). ```jsx import React, {useState} from 'react'; import {useStripe, useElements, PaymentElement} from '@stripe/react-stripe-js'; const CheckoutForm = () => { const stripe = useStripe(); const elements = useElements(); const [errorMessage, setErrorMessage] = useState(null); const handleSubmit = async (event) => { // We don't want to let default form submission happen here, // which would refresh the page. event.preventDefault(); if (!stripe || !elements) { // Stripe.js hasn't yet loaded. // Make sure to disable form submission until Stripe.js has loaded. return; } const {error} = await stripe.confirmPayment({ //`Elements` instance that was used to create the Payment Element elements, confirmParams: { return_url: 'https://example.com/order/123/complete', }, }); if (error) { // This point will only be reached if there is an immediate error when // confirming the payment. Show error to your customer (for example, payment // details incomplete) setErrorMessage(error.message); } else { // Your customer will be redirected to your `return_url`. For some payment // methods like iDEAL, your customer will be redirected to an intermediate // site first to authorize the payment, then redirected to the `return_url`. } }; return (
{/* Show error message to your customers */} {errorMessage &&
{errorMessage}
} ); }; export default CheckoutForm; ``` Verifique se o `return_url` corresponde a uma página no seu site que fornece o status do pagamento. Quando a Stripe redireciona o cliente para o `return_url`, nós fornecemos os seguintes parâmetros de consulta de URL: | Parâmetro | Descrição | | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- | | `payment_intent` | O identificador único do `PaymentIntent`. | | `payment_intent_client_secret` | O [segredo do cliente](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) do objeto `PaymentIntent`. | > Se você tiver ferramentas que rastreiam a sessão do cliente no navegador, pode ser necessário adicionar o domínio `stripe.com` à lista de exclusão de referenciadores. Os redirecionamentos fazem com que algumas ferramentas criem novas sessões, o que impede que você rastreie a sessão completa. Use um dos parâmetros de consulta para recuperar o PaymentIntent. Inspecione o [status do PaymentIntent](https://docs.stripe.com/payments/paymentintents/lifecycle.md) para decidir o que mostrar aos clientes. Você também pode anexar seus próprios parâmetros de consulta ao fornecer o `return_url`, que persiste durante o processo de redirecionamento. #### HTML + JS ```javascript // Initialize Stripe.js using your publishable key const stripe = Stripe('<>'); // Retrieve the "payment_intent_client_secret" query parameter appended to // your return_url by Stripe.js const clientSecret = new URLSearchParams(window.location.search).get( 'payment_intent_client_secret' ); // Retrieve the PaymentIntent stripe.retrievePaymentIntent(clientSecret).then(({paymentIntent}) => { const message = document.querySelector('#message') // Inspect the PaymentIntent `status` to indicate the status of the payment // to your customer. // // Some payment methods will [immediately succeed or fail][0] upon // confirmation, while others will first enter a `processing` state. // // [0]: https://stripe.com/docs/payments/payment-methods#payment-notification switch (paymentIntent.status) { case 'succeeded': message.innerText = 'Success! Payment received.'; break; case 'processing': message.innerText = "Payment processing. We'll update you when payment is received."; break; case 'requires_payment_method': message.innerText = 'Payment failed. Please try another payment method.'; // Redirect your user back to your payment page to attempt collecting // payment again break; default: message.innerText = 'Something went wrong.'; break; } }); ``` #### React ```jsx import React, {useState, useEffect} from 'react'; import {useStripe} from '@stripe/react-stripe-js'; const PaymentStatus = () => { const stripe = useStripe(); const [message, setMessage] = useState(null); useEffect(() => { if (!stripe) { return; } // Retrieve the "payment_intent_client_secret" query parameter appended to // your return_url by Stripe.js const clientSecret = new URLSearchParams(window.location.search).get( 'payment_intent_client_secret' ); // Retrieve the PaymentIntent stripe .retrievePaymentIntent(clientSecret) .then(({paymentIntent}) => { // Inspect the PaymentIntent `status` to indicate the status of the payment // to your customer. // // Some payment methods will [immediately succeed or fail][0] upon // confirmation, while others will first enter a `processing` state. // // [0]: https://stripe.com/docs/payments/payment-methods#payment-notification switch (paymentIntent.status) { case 'succeeded': setMessage('Success! Payment received.'); break; case 'processing': setMessage("Payment processing. We'll update you when payment is received."); break; case 'requires_payment_method': // Redirect your user back to your payment page to attempt collecting // payment again setMessage('Payment failed. Please try another payment method.'); break; default: setMessage('Something went wrong.'); break; } }); }, [stripe]); return message; }; export default PaymentStatus; ``` ## Redirect and authenticate transactions Customers can authenticate Amazon Pay transactions in the browser. After calling `confirmPayment`, customers are redirected to Amazon Pay’s website to confirm their payment. When confirmation is complete, customers are redirected to the `return_url`. ## Optional: Separar autorização e captura You can separate authorization and capture to create a charge now, but capture funds later. Stripe cancels the PaymentIntent and sends a [payment_intent.canceled](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.canceled) event if the payment isn’t captured during the 7-day window. If you know that you can’t capture the payment, we recommend [canceling the PaymentIntent](https://docs.stripe.com/refunds.md#cancel-payment) instead of waiting for the 7-day window to elapse. ### 1. Tell Stripe to authorize only To indicate that you want separate authorization and capture, set [capture_method](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-capture_method) to `manual` when creating the PaymentIntent. This parameter instructs Stripe to only authorize the amount on the customer’s Amazon Pay account. ``` curl https://api.stripe.com/v1/payment_intents \ -u sk_test123: \ -d amount=6000 \ -d confirm=true \ -d currency=usd \ -d "payment_method_types[]"=amazon_pay \ -d "payment_method_data[type]"=amazon_pay \ -d capture_method=manual \ --data-urlencode return_url="https://www.example.com/checkout/done" ``` ### 2. Capture the funds After the authorization succeeds, the [PaymentIntent status](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-status) transitions to `requires_capture`. To capture the authorized funds, make a PaymentIntent [capture request](https://docs.stripe.com/api/payment_intents/capture.md). ```curl curl -X POST https://api.stripe.com/v1/payment_intents/{PAYMENT_INTENT_ID}/capture \ -u "<>:" ``` The total authorized amount is captured by default. You can also specify `amount_to_capture` which can be less or equal to the total. ### (Optional) Cancelar a autorização If you need to cancel an authorization, you can [cancel the PaymentIntent](https://docs.stripe.com/api/payment_intents/cancel.md). ## Optional: Handle post-payment events Stripe envia um evento [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.succeeded) quando o pagamento é concluído. Use o Dashboard, um *webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) personalizado ou uma solução de parceiros para receber esses eventos e executar ações, como enviar um e-mail de confirmação de pedido ao cliente, registrar a venda em um banco de dados ou iniciar um fluxo de entrega. Escute esses eventos em vez de aguardar um retorno de chamada do cliente. No cliente, o consumidor pode fechar a janela do navegador ou sair do aplicativo antes da execução do retorno de chamada, o que permite que clientes mal-intencionados manipulem a resposta. Configurar a integração para escutar eventos assíncronos também ajuda a aceitar mais formas de pagamento no futuro. Conheça as [diferenças entre todas as formas de pagamento aceitas](https://stripe.com/payments/payment-methods-guide). - **Tratar eventos manualmente no Dashboard** Use o Dashboard para [visualizar seus pagamentos de teste no Dashboard](https://dashboard.stripe.com/test/payments), enviar recibos por e-mail, lidar com repasses ou tentar novamente pagamentos que falharam. - **Crie um webhook personalizado** [Build a custom webhook](https://docs.stripe.com/webhooks/handling-payment-events.md#build-your-own-webhook) handler to listen for events and build custom asynchronous payment flows. Test and debug your webhook integration locally with the Stripe CLI. - **Integrar um aplicativo pré-criado** Lide com eventos comuns da empresa, como [automação](https://stripe.partners/?f_category=automation) ou [marketing e vendas](https://stripe.partners/?f_category=marketing-and-sales), integrando um aplicativo de parceiros. ## Test your integration To test your integration, choose Amazon Pay as the payment method and tap **Pay**. In a sandbox, this redirects you to a test payment page where you can approve or decline the payment. In live mode, tapping **Pay** redirects you to the Amazon Pay website—you don’t have the option to approve or decline the payment with Amazon Pay. ## Failed payments If Amazon Pay declines the transaction for any reason, the [PaymentMethod](https://docs.stripe.com/api/payment_methods/object.md) is detached and the [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) object’s status automatically transitions to `requires_payment_method`. Other than a payment being declined, if an Amazon Pay [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) has a status of `requires_action`, customers must complete the payment within 10 minutes after they’re redirected to Amazon. If no action is taken after 10 minutes, the [PaymentMethod](https://docs.stripe.com/api/payment_methods/object.md) is detached and the [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) object’s status automatically transitions to `requires_payment_method`. When this happens, the Payment Element renders error messages and instructs your customer to retry using a different payment method. ## Error codes The following table details common error codes and recommended actions: | Error Code | Recommended Action | | --------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `payment_intent_invalid_currency` | Enter the appropriate currency. Amazon Pay only supports `usd`. | | `missing_required_parameter` | Check the error message for more information about the required parameter. | | `payment_intent_payment_attempt_failed` | This code can appear in the [last_payment_error.code](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-last_payment_error-code) field of a PaymentIntent. Check the error message for a detailed failure reason and suggestion on error handling. | | `payment_intent_redirect_confirmation_without_return_url` | Provide a `return_url` when confirming a PaymentIntent with Amazon Pay. | # Direct API > This is a Direct API for when payment-ui is direct-api. View the full page at https://docs.stripe.com/payments/amazon-pay/accept-a-payment?payment-ui=direct-api. Amazon Pay is a [single-use](https://docs.stripe.com/payments/payment-methods.md#usage) payment method where customers are required to [authenticate](https://docs.stripe.com/payments/payment-methods.md#customer-actions) their payment. Customers are redirected from your website or app, authorize the payment with Amazon, then return to your website or app. You get [immediate notification](https://docs.stripe.com/payments/payment-methods.md#payment-notification) of whether the payment succeeded or failed. ## Set up Stripe [Server-side] [Create a Stripe account](https://dashboard.stripe.com/register) if you don’t already have one. Use nossas bibliotecas oficiais para acessar a API da Stripe no seu aplicativo: #### Ruby ```bash # Available as a gem sudo gem install stripe ``` ```ruby # If you use bundler, you can add this line to your Gemfile gem 'stripe' ``` ## Create a PaymentIntent [Server-side] A [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) is an object that represents your intent to collect payment from your customer and tracks the lifecycle of the payment process. Create a `PaymentIntent` on your server and specify the amount to collect and a [supported currency](https://docs.stripe.com/payments/amazon-pay.md#supported-currencies). If you have an existing [Payment Intents](https://docs.stripe.com/payments/payment-intents.md) integration, add `amazon_pay` to the list of [payment method types](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_types). ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d "payment_method_types[]=amazon_pay" \ -d amount=1099 \ -d currency=usd ``` O `PaymentIntent` contém um *segredo do cliente* (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)). Envie o segredo do cliente ao seu cliente para concluir com segurança o processo de pagamento em vez de passar todo o objeto `PaymentIntent`. ### Recuperar o segredo do cliente O PaymentIntent inclui um *segredo do cliente* (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)) que o lado do cliente usa para concluir com segurança o processo de pagamento. Você pode usar abordagens diferentes para enviar a senha do cliente ao lado do cliente. #### Aplicativo de página única Recupere o segredo do cliente de um endpoint do servidor usando a função `fetch` do navegador. Essa abordagem é melhor quando o lado do cliente é um aplicativo com uma única página, principalmente se criado com uma estrutura de front-end moderna como o React. Crie o endpoint do servidor que envia o segredo do cliente: #### Ruby ```ruby get '/secret' do intent = # ... Create or retrieve the PaymentIntent {client_secret: intent.client_secret}.to_json end ``` Em seguida, obtenha o segredo do cliente com JavaScript no lado do cliente: ```javascript (async () => { const response = await fetch('/secret'); const {client_secret: clientSecret} = await response.json(); // Render the form using the clientSecret })(); ``` #### Renderização do lado do servidor Passe o segredo do cliente do servidor ao cliente. Essa abordagem funciona melhor quando o aplicativo gera conteúdo estático no servidor antes de enviá-lo ao navegador. Adicione o [client_secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) ao formulário de checkout. No código do lado do servidor, recupere o segredo do cliente do PaymentIntent: #### Ruby ```erb
``` ```ruby get '/checkout' do @intent = # ... Fetch or create the PaymentIntent erb :checkout end ``` ## Redirect to Amazon Pay [Client-side] When a customer clicks to pay with Amazon Pay, use Stripe.js to submit the payment to Stripe. [Stripe.js](https://docs.stripe.com/payments/elements.md) is the foundational JavaScript library for building payment flows. It automatically handles complexities like the redirect described below, and enables you to extend your integration to other payment methods. Include the Stripe.js script on your checkout page by adding it to the `head` of your HTML file. ```html Checkout ``` Crie uma instância de Stripe.js com o JavaScript a seguir em sua página de checkout. ```javascript // Set your publishable key. Remember to change this to your live publishable key in production! // See your keys here: https://dashboard.stripe.com/apikeys const stripe = Stripe('<>'); ``` Use the [client secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) of the `PaymentIntent` and call `stripe.confirmPayment` to handle the Amazon Pay redirect. Add a `return_url` to determine where Stripe redirects the customer after they complete the payment. ```javascript const form = document.getElementById('payment-form'); form.addEventListener('submit', async function(event) { event.preventDefault(); // Set the clientSecret of the PaymentIntent const { error } = await stripe.confirmPayment({ clientSecret: clientSecret, confirmParams: { payment_method_data: { type: 'amazon_pay', }, // Return URL where the customer should be redirected after the authorization return_url: `${window.location.href}`, }, }); if (error) { // Inform the customer that there was an error. const errorElement = document.getElementById('error-message'); errorElement.textContent = result.error.message; } }); ``` The `return_url` corresponds to a page on your website that displays the result of the payment. You can determine what to display by [verifying the status](https://docs.stripe.com/payments/payment-intents/verifying-status.md#checking-status) of the `PaymentIntent`. To verify the status, the Stripe redirect to the `return_url` includes the following URL query parameters. You can also append your own query parameters to the `return_url`. They persist throughout the redirect process. | Parameter | Description | | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- | | `payment_intent` | O identificador único do `PaymentIntent`. | | `payment_intent_client_secret` | O [segredo do cliente](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) do objeto `PaymentIntent`. | ## Optional: Handle post-payment events Stripe sends a [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.succeeded) event when the payment completes. Use the Dashboard, a custom *webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests), or a partner solution to receive these events and run actions, like sending an order confirmation email to your customer, logging the sale in a database, or starting a shipping workflow. Listen for these events rather than waiting on a callback from the client. On the client, the customer could close the browser window or quit the app before the callback executes, and malicious clients could manipulate the response. Setting up your integration to listen for asynchronous events also helps you accept more payment methods in the future. Learn about the [differences between all supported payment methods](https://stripe.com/payments/payment-methods-guide). ### Receber eventos e tomar providências comerciais Há algumas opções para receber eventos e tomar providências comerciais. #### Manualmente Use o Stripe Dashboard para ver todos os pagamentos da Stripe, enviar recibos por e-mail, lidar com repasses ou tentar novamente pagamentos com falha. - [Veja os pagamentos de teste no Dashboard](https://dashboard.stripe.com/test/payments) #### Programação personalizada Crie um gerenciador de webhooks para ouvir eventos e criar fluxos personalizados de pagamentos assíncronos. Teste e depure a integração do webhook localmente usando a Stripe CLI. - [Build a custom webhook](https://docs.stripe.com/webhooks/handling-payment-events.md#build-your-own-webhook) #### Aplicativos pré-integrados Handle common business events, like [automation](https://stripe.partners/?f_category=automation) or [marketing and sales](https://stripe.partners/?f_category=marketing-and-sales), by integrating a partner application. ## Supported currencies You can create Amazon Pay payments in any of the supported currencies, regardless of the country your business operates in with the exception of the US. | Country | Currency | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | | Austria, Belgium, Cyprus, Denmark, France, Germany, Hungary, Ireland, Italy, Luxembourg, Netherlands, Portugal, Spain, Sweden, Switzerland, United Kingdom, United States | `aud`, `gbp`, `dkk`, `eur`, `hkd`, `jpy`, `nzd`, `nok`, `zar`, `sek`, `chf`, `usd` | # iOS > This is a iOS for when payment-ui is mobile and platform is ios. View the full page at https://docs.stripe.com/payments/amazon-pay/accept-a-payment?payment-ui=mobile&platform=ios. We recommend you use the [Mobile Payment Element](https://docs.stripe.com/payments/accept-a-payment.md?=ios), an embeddable payment form, to add Amazon Pay and other payment methods to your integration with the least amount of effort. Amazon Pay is a [single-use](https://docs.stripe.com/payments/payment-methods.md#usage) payment method where customers are required to [authenticate](https://docs.stripe.com/payments/payment-methods.md#customer-actions) their payment. Customers are redirected from your app, authorize the payment with Amazon, then return to your app. You get [immediate notification](https://docs.stripe.com/payments/payment-methods.md#payment-notification) of whether the payment succeeded or failed. ## Configurar a Stripe [Lado do servidor] [Lado do cliente] Primeiro, você precisa de uma conta Stripe. [Inscreva-se aqui](https://dashboard.stripe.com/register). ### Lado do servidor Esta integração exige que os endpoints do seu servidor se comuniquem com a API Stripe. Use as bibliotecas oficiais para acessar a API Stripe do seu servidor: #### Ruby ```bash # Available as a gem sudo gem install stripe ``` ```ruby # If you use bundler, you can add this line to your Gemfile gem 'stripe' ``` ### Lado do cliente O [SDK da Stripe para iOS](https://github.com/stripe/stripe-ios) é de código aberto, [totalmente documentado](https://stripe.dev/stripe-ios/index.html) e compatível com aplicativos que aceitam iOS 13 ou versões mais recentes. #### Gerenciador de pacotes Swift Para instalar o SDK, siga estas etapas: 1. No Xcode, selecione **Arquivo** > **Adicionar dependências de pacote…** e insira `https://github.com/stripe/stripe-ios-spm` como URL do repositório. 1. Selecione o número da última versão da nossa [página de lançamentos](https://github.com/stripe/stripe-ios/releases). 1. Adicione o produto **StripePaymentsUI** ao [alvo do seu aplicativo](https://developer.apple.com/documentation/swift_packages/adding_package_dependencies_to_your_app). #### CocoaPods 1. Se ainda não o fez, instale a versão mais recente do [CocoaPods](https://guides.cocoapods.org/using/getting-started.html). 1. Se não tiver um [Podfile](https://guides.cocoapods.org/syntax/podfile.html), execute o seguinte comando para criar um: ```bash pod init ``` 1. Adicione esta linha ao seu `Podfile`: ```podfile pod 'StripePaymentsUI' ``` 1. Execute o seguinte comando: ```bash pod install ``` 1. Não se esqueça de usar o arquivo `.xcworkspace` para abrir seu projeto em Xcode, em vez do arquivo `.xcodeproj`, daqui em diante. 1. No futuro, para atualizar para a versão mais recente do SDK, execute: ```bash pod update StripePaymentsUI ``` #### Carthage 1. Se ainda não o fez, instale a versão mais recente do [Carthage](https://github.com/Carthage/Carthage#installing-carthage). 1. Adicione esta linha ao seu `Cartfile`: ```cartfile github "stripe/stripe-ios" ``` 1. Siga as [instruções de instalação do Carthage](https://github.com/Carthage/Carthage#if-youre-building-for-ios-tvos-or-watchos). Certifique-se de integrar todas as estruturas necessárias listadas [here](https://github.com/stripe/stripe-ios/tree/master/StripePaymentsUI/README.md#manual-linking). 1. No futuro, para atualizar para a versão mais recente do SDK, execute o seguinte comando: ```bash carthage update stripe-ios --platform ios ``` #### Estrutura manual 1. Vá até a nossa [página de lançamentos do GitHub](https://github.com/stripe/stripe-ios/releases/latest) e baixe e descompacte o **Stripe.xcframework.zip**. 1. Arraste **StripePaymentsUI.xcframework** até a seção **Embedded Binaries** das configurações **General** no seu projeto Xcode. Certifique-se de selecionar **Copy items if needed**. 1. Repita a etapa 2 para todas as estruturas necessárias listadas [here](https://github.com/stripe/stripe-ios/tree/master/StripePaymentsUI/README.md#manual-linking). 1. No futuro, para atualizar para a versão mais recente do nosso SDK, repita as etapas 1 a 3. > Para obter mais informações sobre a versão mais recente e as versões anteriores do SDK, consulte a página [Lançamentos](https://github.com/stripe/stripe-ios/releases) no GitHub. Para receber notificações quando um novo lançamento for publicado, [assista aos lançamentos](https://help.github.com/en/articles/watching-and-unwatching-releases-for-a-repository#watching-releases-for-a-repository) do repositório. Configure o SDK com sua [chave publicável da Stripe](https://dashboard.stripe.com/test/apikeys) na inicialização do aplicativo. Isso permite que seu aplicativo faça solicitações à API da Stripe . #### Swift ```swift import UIKitimportStripePaymentsUI @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {StripeAPI.defaultPublishableKey = "<>" // do any other necessary launch configuration return true } } ``` > Use suas [chaves de teste](https://docs.stripe.com/keys.md#obtain-api-keys) enquanto testa e desenvolve, e suas chaves de [modo de produção](https://docs.stripe.com/keys.md#test-live-modes) quando publicar seu aplicativo. ## Create a PaymentIntent [Server-side] [Client-side] ### Server-side A [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) is an object that represents your intent to collect payment from a customer and tracks the lifecycle of the payment process through each stage. #### Gerenciar formas de pagamento no Dashboard You can manage payment methods in the [Dashboard](https://dashboard.stripe.com/settings/payment_methods). Stripe handles the return of eligible payment methods based on factors such as the transaction’s amount, currency, and payment flow. Create a PaymentIntent on your server with an amount and currency. Before creating the PaymentIntent, make sure to turn **Amazon Pay** on in the [payment methods settings](https://dashboard.stripe.com/settings/payment_methods) page. > Always decide how much to charge on the server-side, a trusted environment, as opposed to the client. This prevents customers from being able to choose their own prices. ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=usd \ -d "automatic_payment_methods[enabled]=true" ``` #### List payment methods manually If you don’t want to use the Dashboard or you want to manually specify payment methods, you can list them using the `payment_method_types` attribute. Create a PaymentIntent on your server with an amount, currency, and a list of payment methods. > Always decide how much to charge on the server-side, a trusted environment, as opposed to the client. This prevents customers from being able to choose their own prices. ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=usd \ -d "payment_method_types[]=amazon_pay" ``` ### Client-side No cliente, solicite um PaymentIntent a partir do seu servidor e armazene o *segredo de cliente* (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)). #### Swift ```swift class CheckoutViewController: UIViewController { var paymentIntentClientSecret: String? // ...continued from previous step override func viewDidLoad() { // ...continued from previous step startCheckout() } func startCheckout() { // Request a PaymentIntent from your server and store its client secret // Click View full sample to see a complete implementation } } ``` ## Enviar o pagamento para a Stripe [Client-side] When a customer taps to pay with Amazon Pay, confirm the `PaymentIntent` to complete the payment. Configure an `STPPaymentIntentParams` object with the `PaymentIntent` [client secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret). The client secret is different from your API keys that authenticate Stripe API requests. Handle it carefully because it can complete the charge. Don’t log it, embed it in URLs, or expose it to anyone but the customer. ### Configurar um URL de retorno The iOS SDK presents a webview in your app to complete the Amazon Pay payment. When authentication is finished, the webview can automatically dismiss itself instead of having your customer close it. To enable this behavior, configure a custom URL scheme or universal link and set up your app delegate to forward the URL to the SDK. #### Swift ```swift // This method handles opening custom URL schemes (for example, "your-app://stripe-redirect") func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { let stripeHandled = StripeAPI.handleURLCallback(with: url) if (stripeHandled) { return true } else { // This was not a Stripe url – handle the URL normally as you would } return false } // This method handles opening universal link URLs (for example, "https://example.com/stripe_ios_callback") func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { if userActivity.activityType == NSUserActivityTypeBrowsingWeb { if let url = userActivity.webpageURL { let stripeHandled = StripeAPI.handleURLCallback(with: url) if (stripeHandled) { return true } else { // This was not a Stripe url – handle the URL normally as you would } } } return false } ``` Pass the URL as the `return_url` when you confirm the PaymentIntent. After webview-based authentication finishes, Stripe redirects the user to the `return_url`. ### Confirm the Amazon Pay payment Complete the payment by calling `STPPaymentHandler.confirmPayment`. This presents a webview where the customer can complete the payment with Amazon Pay. After completion, Stripe calls the completion block with the result of the payment. #### Swift ```swift let paymentIntentParams = STPPaymentIntentParams(clientSecret: paymentIntentClientSecret) // Amazon Pay doesn't require additional parameters so we only need to pass the initialized // STPPaymentMethodAmazonPayParams instance to STPPaymentMethodParams let amazonPay = STPPaymentMethodAmazonPayParams() let paymentMethodParams = STPPaymentMethodParams(amazonPay: amazonPay, billingDetails: nil, metadata: nil) paymentIntentParams.paymentMethodParams = paymentMethodParams paymentIntentParams.returnURL = "payments-example://stripe-redirect" STPPaymentHandler.shared().confirmPayment(paymentIntentParams, with: self) { (handlerStatus, paymentIntent, error) in switch handlerStatus { case .succeeded: // Payment succeeded // ... case .canceled: // Payment canceled // ... case .failed: // Payment failed // ... @unknown default: fatalError() } } ``` ## Optional: Handle post-payment events Stripe envia um evento [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.succeeded) quando o pagamento é concluído. Use o Dashboard, um *webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) personalizado ou uma solução de parceiros para receber esses eventos e executar ações, como enviar um e-mail de confirmação de pedido ao cliente, registrar a venda em um banco de dados ou iniciar um fluxo de entrega. Escute esses eventos em vez de aguardar um retorno de chamada do cliente. No cliente, o consumidor pode fechar a janela do navegador ou sair do aplicativo antes da execução do retorno de chamada, o que permite que clientes mal-intencionados manipulem a resposta. Configurar a integração para escutar eventos assíncronos também ajuda a aceitar mais formas de pagamento no futuro. Conheça as [diferenças entre todas as formas de pagamento aceitas](https://stripe.com/payments/payment-methods-guide). - **Tratar eventos manualmente no Dashboard** Use o Dashboard para [visualizar seus pagamentos de teste no Dashboard](https://dashboard.stripe.com/test/payments), enviar recibos por e-mail, lidar com repasses ou tentar novamente pagamentos que falharam. - **Crie um webhook personalizado** [Build a custom webhook](https://docs.stripe.com/webhooks/handling-payment-events.md#build-your-own-webhook) handler to listen for events and build custom asynchronous payment flows. Test and debug your webhook integration locally with the Stripe CLI. - **Integrar um aplicativo pré-criado** Lide com eventos comuns da empresa, como [automação](https://stripe.partners/?f_category=automation) ou [marketing e vendas](https://stripe.partners/?f_category=marketing-and-sales), integrando um aplicativo de parceiros. # Android > This is a Android for when payment-ui is mobile and platform is android. View the full page at https://docs.stripe.com/payments/amazon-pay/accept-a-payment?payment-ui=mobile&platform=android. We recommend you use the [Mobile Payment Element](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=android), an embeddable payment form, to add Amazon Pay and other payment methods to your integration with the least amount of effort. Amazon Pay is a [single-use](https://docs.stripe.com/payments/payment-methods.md#usage) payment method where customers are required to [authenticate](https://docs.stripe.com/payments/payment-methods.md#customer-actions) their payment. Customers are redirected from your app, authorize the payment with Amazon, then return to your app. You get [immediate notification](https://docs.stripe.com/payments/payment-methods.md#payment-notification) of whether the payment succeeded or failed. ## Configurar a Stripe [Lado do servidor] [Lado do cliente] Primeiro, você precisa de uma conta Stripe. [Inscreva-se aqui](https://dashboard.stripe.com/register). ### Lado do servidor Esta integração exige que os endpoints do seu servidor se comuniquem com a API Stripe. Use as bibliotecas oficiais para acessar a API Stripe do seu servidor: #### Ruby ```bash # Available as a gem sudo gem install stripe ``` ```ruby # If you use bundler, you can add this line to your Gemfile gem 'stripe' ``` ### Lado do cliente O [SDK da Stripe para Android](https://github.com/stripe/stripe-android) é de código aberto e [totalmente documentado](https://stripe.dev/stripe-android/). Para instalar o SDK, adicione `stripe-android` ao bloco `dependencies` do arquivo [app/build.gradle](https://developer.android.com/studio/build/dependencies): #### Kotlin ```kotlin plugins { id("com.android.application") } android { ... } dependencies { // ... // Stripe Android SDK implementation("com.stripe:stripe-android:23.2.0") // Include the financial connections SDK to support US bank account as a payment method implementation("com.stripe:financial-connections:23.2.0") } ``` > Veja mais informações sobre o último lançamento de SDK e as versões anteriores na página [Lançamentos](https://github.com/stripe/stripe-android/releases) no GitHub. Para receber notificações quando um novo lançamento for publicado, [assista aos lançamentos do repositório](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/configuring-notifications#configuring-your-watch-settings-for-an-individual-repository). Configure o SDK com sua [chave publicável](https://dashboard.stripe.com/apikeys) da Stripe, de modo que seja possível fazer solicitações à API Stripe, como em sua subcategoria `Application`: #### Kotlin ```kotlin import com.stripe.android.PaymentConfiguration class MyApp : Application() { override fun onCreate() { super.onCreate() PaymentConfiguration.init( applicationContext, "<>" ) } } ``` > Use suas [chaves de teste](https://docs.stripe.com/keys.md#obtain-api-keys) enquanto testa e desenvolve, e suas chaves de [modo de produção](https://docs.stripe.com/keys.md#test-live-modes) quando publicar seu aplicativo. Nossas amostras de código também usam [OkHttp](https://github.com/square/okhttp) e [GSON](https://github.com/google/gson) para fazer solicitações HTTP a um servidor. ## Create a PaymentIntent [Server-side] [Client-side] ### Server-side A [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) is an object that represents your intent to collect payment from a customer and tracks the lifecycle of the payment process through each stage. #### Gerenciar formas de pagamento no Dashboard You can manage payment methods in the [Dashboard](https://dashboard.stripe.com/settings/payment_methods). Stripe handles the return of eligible payment methods based on factors such as the transaction’s amount, currency, and payment flow. Create a PaymentIntent on your server with an amount and currency. Before creating the PaymentIntent, make sure to turn **Amazon Pay** on in the [payment methods settings](https://dashboard.stripe.com/settings/payment_methods) page. > Always decide how much to charge on the server-side, a trusted environment, as opposed to the client. This prevents customers from being able to choose their own prices. ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=usd \ -d "automatic_payment_methods[enabled]=true" ``` #### List payment methods manually If you don’t want to use the Dashboard or you want to manually specify payment methods, you can list them using the `payment_method_types` attribute. Create a PaymentIntent on your server with an amount, currency, and a list of payment methods. > Always decide how much to charge on the server-side, a trusted environment, as opposed to the client. This prevents customers from being able to choose their own prices. ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=usd \ -d "payment_method_types[]=amazon_pay" ``` ### Client-side No cliente, solicite um PaymentIntent a partir do seu servidor e armazene o *segredo de cliente* (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)). #### Kotlin ```kotlin class CheckoutActivity : AppCompatActivity() { private lateinit var paymentIntentClientSecret: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // ... startCheckout() } private fun startCheckout() { // Request a PaymentIntent from your server and store its client secret in paymentIntentClientSecret // Click View full sample to see a complete implementation } } ``` ## Enviar o pagamento para a Stripe [Client-side] When a customer taps to pay with Amazon Pay, confirm the `PaymentIntent` to complete the payment. Configure a `ConfirmPaymentIntentParams` object with the `PaymentIntent` [client secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret). The client secret is different from your API keys that authenticate Stripe API requests. Handle it carefully because it can complete the charge. Don’t log it, embed it in URLs, or expose it to anyone but the customer. ### Confirm Amazon Pay payment Complete the payment by calling [PaymentLauncher confirm](https://stripe.dev/stripe-android/payments-core/com.stripe.android.payments.paymentlauncher/-payment-launcher/confirm.html). This redirects the customer to Amazon, where they can complete the payment with Amazon Pay. After completion, Stripe calls the `PaymentResultCallback` you set with the result of the payment. #### Kotlin ```kotlin class CheckoutActivity : AppCompatActivity() { // ... private val paymentLauncher: PaymentLauncher by lazy { val paymentConfiguration = PaymentConfiguration.getInstance(applicationContext) PaymentLauncher.create( activity = this, publishableKey = paymentConfiguration.publishableKey, stripeAccountId = paymentConfiguration.stripeAccountId, callback = ::onPaymentResult, ) } // … private fun startCheckout() { // ... val amazonPayParams = PaymentMethodCreateParams.createAmazonPay() val confirmParams = ConfirmPaymentIntentParams .createWithPaymentMethodCreateParams( paymentMethodCreateParams = amazonPayParams, clientSecret = paymentIntentClientSecret, ) paymentLauncher.confirm(confirmParams) } private fun onPaymentResult(paymentResult: PaymentResult) { // Handle the payment result… } } ``` ## Optional: Handle post-payment events Stripe envia um evento [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.succeeded) quando o pagamento é concluído. Use o Dashboard, um *webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) personalizado ou uma solução de parceiros para receber esses eventos e executar ações, como enviar um e-mail de confirmação de pedido ao cliente, registrar a venda em um banco de dados ou iniciar um fluxo de entrega. Escute esses eventos em vez de aguardar um retorno de chamada do cliente. No cliente, o consumidor pode fechar a janela do navegador ou sair do aplicativo antes da execução do retorno de chamada, o que permite que clientes mal-intencionados manipulem a resposta. Configurar a integração para escutar eventos assíncronos também ajuda a aceitar mais formas de pagamento no futuro. Conheça as [diferenças entre todas as formas de pagamento aceitas](https://stripe.com/payments/payment-methods-guide). - **Tratar eventos manualmente no Dashboard** Use o Dashboard para [visualizar seus pagamentos de teste no Dashboard](https://dashboard.stripe.com/test/payments), enviar recibos por e-mail, lidar com repasses ou tentar novamente pagamentos que falharam. - **Crie um webhook personalizado** [Build a custom webhook](https://docs.stripe.com/webhooks/handling-payment-events.md#build-your-own-webhook) handler to listen for events and build custom asynchronous payment flows. Test and debug your webhook integration locally with the Stripe CLI. - **Integrar um aplicativo pré-criado** Lide com eventos comuns da empresa, como [automação](https://stripe.partners/?f_category=automation) ou [marketing e vendas](https://stripe.partners/?f_category=marketing-and-sales), integrando um aplicativo de parceiros. ## Test your integration Test your Amazon Pay integration with your test API keys by viewing the redirect page. You can test the successful payment case by authenticating the payment on the redirect page. The [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) transitions from `requires_action` to `succeeded`. To test the case where the user fails to authenticate, use your test API keys and view the redirect page. On the redirect page, click **Fail test payment**. The [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) transitions from `requires_action` to `requires_payment_method`. For manual capture PaymentIntents in a testing environment, the uncaptured [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) auto-expires 7 days after successful authorization. The payment flow that you simulate in a testing environment differs from the payment flow in live mode. In live mode, tapping **Pay** redirects you to the Amazon mobile application.