# Pagamentos MobilePay Learn how to accept MobilePay, a popular payment method in Denmark and Finland. # Checkout > This is a Checkout for when payment-ui is checkout. View the full page at https://docs.stripe.com/payments/mobilepay/accept-a-payment?payment-ui=checkout. MobilePay is a [single-use](https://docs.stripe.com/payments/payment-methods.md#usage) card wallet payment method used in Denmark and Finland. It allows your customer to [authenticate and approve](https://docs.stripe.com/payments/payment-methods.md#customer-actions) payments using the MobilePay app. When your customer pays with MobilePay, Stripe performs a card transaction using the card data we receive from MobilePay. The processing of the card transaction is invisible to your integration, and Stripe [immediately notifies you](https://docs.stripe.com/payments/payment-methods.md#payment-notification) whether the payment succeeded or failed. > 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. Use this guide to enable MobilePay on [Checkout](https://docs.stripe.com/payments/checkout.md), our hosted checkout form, and learn the differences between accepting payments using dynamic payment methods and manually configuring payment methods. ## Determine compatibility **Localizações aceitas para empresas**: EEA **Moedas aceitas**: `eur, dkk, sek, nok` **Moedas de apresentação**: `eur, dkk, sek, nok` **Modo de pagamento**: Yes **Modo de configuração**: No **Modo de assinatura**: No A Checkout Session must satisfy all of the following conditions to support MobilePay payments: - *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 expressed in Euro, Danish Krona, Swedish Krona or Norwegian Krona (currency codes `eur`, `dkk`, `sek` or `nok`). ## Set up Stripe [Server-side] Primeiro, você precisa de uma conta Stripe. [Cadastre-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' ``` ## Accept a payment > This guide builds on the foundational [accept a payment](https://docs.stripe.com/payments/accept-a-payment.md?integration=checkout) Checkout integration. ### Enable MobilePay as a payment method Ao criar uma [sessão do Checkout](https://docs.stripe.com/api/checkout/sessions.md), é preciso: 1. Add `mobilepay` to the list of `payment_method_types`. 1. Make sure all your `line_items` use the `eur`, `dkk`, `sek` or `nok` currency. #### Stripe-hosted page ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d "line_items[0][price_data][currency]=dkk" \ -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]=mobilepay" \ --data-urlencode "success_url=https://example.com/success" ``` #### Full embedded page ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d "line_items[0][price_data][currency]=dkk" \ -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]=mobilepay" \ --data-urlencode "return_url=https://example.com/return" \ -d ui_mode=embedded_page ``` ### Executar pedidos Após aceitar um pagamento, saiba como [atender aos pedidos](https://docs.stripe.com/checkout/fulfillment.md). ## 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 the integration #### Mobile web app testing To test your integration, choose MobilePay as the payment method and tap **Pay**. In a testing environment, 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 MobilePay mobile application, where you can approve or decline the payment. #### Desktop web app testing To test your integration in a testing environment, this redirects you to a test payment page where you can approve or decline the test payment. In live mode, enter the phone number linked to MobilePay to send a push notification to your MobilePay mobile application. You can approve or decline the payment in the MobilePay mobile application. ## Optional: Authorize a payment and then capture later MobilePay supports [separate authorization and capture](https://docs.stripe.com/payments/place-a-hold-on-a-payment-method.md). ### Instruir a Stripe a autorizar somente To indicate that you want separate authorization and capture, set [capture_method](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-payment_intent_data-capture_method) to `manual` when creating the Checkout Session. This parameter instructs Stripe to only authorize the amount on the customer’s card linked to MobilePay. ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d mode=payment \ -d "payment_method_types[0]=card" \ -d "payment_method_types[1]=mobilepay" \ -d "line_items[0][price_data][currency]=dkk" \ -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 "payment_intent_data[capture_method]=manual" \ --data-urlencode "success_url=https://example.com/success.html" ``` After the authorization is successful, Stripe sends a [payment_intent.amount_capturable_updated](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.amount_capturable_updated) event. See [Events](https://docs.stripe.com/api/events.md) to learn more. ### Capture the funds After the authorization succeeds, the PaymentIntent’s [status](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-status) transitions to `requires_capture` and you can [capture](https://docs.stripe.com/api/payment_intents/capture.md) the authorized funds. Stripe only support manual captures of the full amount. ```curl curl https://api.stripe.com/v1/payment_intents/{{PAYMENTINTENT_ID}}/capture \ -u "<>:" \ -d amount_to_capture=2000 ``` ## Optional: Cancellation You can cancel MobilePay payments before they expire by [canceling the PaymentIntent](https://docs.stripe.com/api/payment_intents/cancel.md) associated with the MobilePay payment. ## Failed payments MobilePay transactions can fail if the underlying card transaction is declined. Learn more about [card declines](https://docs.stripe.com/declines/card.md). In this case, the PaymentMethod is detached and the PaymentIntent’s status automatically transitions to `requires_payment_method`. When the PaymentIntent’s status is `requires_action`, your customer must authenticate the payment within 5 minutes. If no action is taken after 5 minutes, the PaymentMethod detaches and the PaymentIntent’s status automatically transitions to `requires_payment_method`. ## Refunds and disputes Stripe performs a card transaction using standard card rails as part of a MobilePay transaction. [Refunds](https://docs.stripe.com/refunds.md) and [disputes](https://docs.stripe.com/disputes/how-disputes-work.md) are subject to the Visa and Mastercard network rules. ## See also - [More about MobilePay](https://docs.stripe.com/payments/mobilepay.md) - [Checkout fulfillment](https://docs.stripe.com/checkout/fulfillment.md) - [Customize 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/mobilepay/accept-a-payment?payment-ui=elements. MobilePay is a [single-use](https://docs.stripe.com/payments/payment-methods.md#usage) card wallet payment method used in Denmark and Finland. It allows your customer to [authenticate and approve](https://docs.stripe.com/payments/payment-methods.md#customer-actions) payments using the MobilePay app. When your customer pays with MobilePay, Stripe performs a card transaction using the card data we receive from MobilePay. The processing of the card transaction is invisible to your integration, and Stripe [immediately notifies you](https://docs.stripe.com/payments/payment-methods.md#payment-notification) whether the payment succeeded or failed. This guide shows you 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 MobilePay and other payment methods automatically. For advanced 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] First, you need a Stripe account. [Register now](https://dashboard.stripe.com/register). Use our official libraries for access to the Stripe API from your application: #### 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] Stripe uses a [PaymentIntent](https://docs.stripe.com/api/payment_intents.md) object to represent your intent to collect payment from a customer, tracking charge attempts and payment state changes throughout the process. #### Manage payment methods from the Dashboard Create a PaymentIntent on your server with an amount and currency. You can manage payment methods from 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. Before creating the Payment Intent, make sure to turn **MobilePay** 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 malicious 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 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 malicious customers from being able to choose their own prices. ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1000 \ -d currency=eur \ -d "payment_method_types[]=mobilepay" ``` ### 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; ``` ## Submit the payment to 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 MobilePay transactions with mobile or desktop apps. The client that the customer uses determines the authentication method after calling `confirmPayment`. #### Mobile app authentication After you call `confirmPayment`, Stripe redirects your customers to MobilePay to approve or decline the payment. After your customers authorize the payment, the page redirects them to the Payment Intent’s `return_url`. Stripe adds `payment_intent`, `payment_intent_client_secret`, `redirect_pm_type`, and `redirect_status` as URL query parameters (along with any existing query parameters in the `return_url`). An authentication session expires after 5 minutes, and the PaymentIntent’s status transitions back to `require_payment_method`. After the status transitions, your customer sees a payment error and must restart the payment process. #### Desktop web app authentication After you call `confirmPayment`, Stripe redirects your customers to a MobilePay-hosted page where they can input the phone number associated with their MobilePay account. This sends a push notification to their MobilePay app for payment authentication. After your customer successfully authenticates the payment, the page redirect them back to the `return_url`. If you prefer not to redirect customers on the web after payment, pass `redirect: if_required` to the Payment Element. An authentication session expires after 5 minutes, and the PaymentIntent’s status transitions back to `require_payment_method`. After the status transitions, your customer sees a payment error and must restart the payment process. ## 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 the integration #### Mobile web app testing To test your integration, choose MobilePay as the payment method and tap **Pay**. In a testing environment, 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 MobilePay mobile application, where you can approve or decline the payment. #### Desktop web app testing To test your integration in a testing environment, it redirects you to a test payment page where you can approve or decline the test payment. In live mode, enter the phone number linked to MobilePay to send a push notification to your MobilePay mobile application. You can approve or decline the payment in the MobilePay mobile application. ## Optional: Authorize a payment and then capture later MobilePay supports [separate authorization and capture](https://docs.stripe.com/payments/place-a-hold-on-a-payment-method.md). ### 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 card linked to MobilePay. ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=dkk \ -d capture_method=manual \ -d "payment_method_types[]=mobilepay" \ -d "payment_method_data[type]=mobilepay" ``` After the authorization is successful, Stripe sends a [payment_intent.amount_capturable_updated](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.amount_capturable_updated) event. See [Events](https://docs.stripe.com/api/events.md) to learn more. ### Capture the funds After the authorization succeeds, the PaymentIntent’s [status](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-status) transitions to `requires_capture` and you can [capture](https://docs.stripe.com/api/payment_intents/capture.md) the authorized funds. Stripe only support manual captures of the full amount. ```curl curl https://api.stripe.com/v1/payment_intents/{{PAYMENTINTENT_ID}}/capture \ -u "<>:" \ -d amount_to_capture=1099 ``` ## Optional: Cancellation You can cancel MobilePay payments before they expire by [canceling the PaymentIntent](https://docs.stripe.com/api/payment_intents/cancel.md) associated with the MobilePay payment. ## Failed payments MobilePay transactions can fail if the underlying card transaction is declined. Learn more about [card declines](https://docs.stripe.com/declines/card.md). In this case, the PaymentMethod is detached and the PaymentIntent’s status automatically transitions to `requires_payment_method`. When the PaymentIntent’s status is `requires_action`, your customer must authenticate the payment within 5 minutes. If no action is taken after 5 minutes, the PaymentMethod detaches and the PaymentIntent’s status automatically transitions to `requires_payment_method`. ## Refunds and disputes Stripe performs a card transaction using standard card rails as part of a MobilePay transaction. [Refunds](https://docs.stripe.com/refunds.md) and [disputes](https://docs.stripe.com/disputes/how-disputes-work.md) are subject to the Visa and Mastercard network rules. # API Direct > This is a API Direct for when payment-ui is direct-api. View the full page at https://docs.stripe.com/payments/mobilepay/accept-a-payment?payment-ui=direct-api. MobilePay is a [single-use](https://docs.stripe.com/payments/payment-methods.md#usage) card wallet payment method used in Denmark and Finland. It allows your customer to [authenticate and approve](https://docs.stripe.com/payments/payment-methods.md#customer-actions) payments using the MobilePay app. When your customer pays with MobilePay, Stripe performs a card transaction using the card data we receive from MobilePay. The processing of the card transaction is invisible to your integration, and Stripe [immediately notifies you](https://docs.stripe.com/payments/payment-methods.md#payment-notification) whether the payment succeeded or failed. ## Set up Stripe [Server-side] First, you need a Stripe account. [Register now](https://dashboard.stripe.com/register). Use our official libraries for access to the Stripe API from your application: #### 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 a payment from a customer and tracks the lifecycle of the payment process through each stage. Create a `PaymentIntent` on your server and specify the amount to collect and a supported currency (`eur`, `dkk`, `sek`, or `nok`). If you already have an integration using the [Payment Intents API](https://docs.stripe.com/payments/payment-intents.md), add `mobilepay` 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 amount=1099 \ -d currency=dkk \ -d "payment_method_types[]=mobilepay" \ -d "payment_method_data[type]=mobilepay" ``` ### Example response ```json { "id": "pi_12345", "amount": 1099, "client_secret": "pi_12345_secret_abcdef", "currency": "dkk", "payment_method": "pm_12345", "payment_method_types": [ "mobilepay" ], "status": "requires_confirmation" } ``` ### 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 ``` ## Confirm the PaymentIntent Use the PaymentIntent [ID](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-id) from [step 2](https://docs.stripe.com/payments/mobilepay/accept-a-payment.md#create-payment-intent) to *confirm* (Confirming an intent indicates that the customer intends to use the current or provided payment method. Upon confirmation, the intent attempts to initiate the portions of the flow that have real-world side effects) the PaymentIntent. This declares that the customer intends to pay with the specified *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs). Stripe initiates a payment after confirming the PaymentIntent. The [return_url](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-return_url) indicates where Stripe redirects the customer after they complete the payment. ```curl curl https://api.stripe.com/v1/payment_intents/{{PAYMENTINTENT_ID}}/confirm \ -u "<>:" \ --data-urlencode "return_url=https://example.com/checkout/complete" ``` ### Example response ```json { "id": "pi_12345", "amount": 1099, "currency": "dkk", "payment_method": "pm_12345", "next_action": { "redirect_to_url": { "return_url": "https://example.com/checkout/complete", "url": "https://pm-redirects.stripe.com/authorize/acct_123/pa_nonce_abc" }, "type": "redirect_to_url" }, "payment_method_types": [ "mobilepay" ], "status": "requires_action" } ``` To authorize the payment, redirect your customer to the URL in the [next_action[redirect_to_url][url]](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action-redirect_to_url-url) field. - On desktop, the URL opens a MobilePay landing page where the customer can enter their phone number, which identifies their MobilePay account. They can then use the MobilePay smartphone app to proceed with payment authorization. - On mobile devices, the URL opens the MobilePay application directly (if present) or directs to the MobilePay landing page, similar to the desktop process. Your customer has 5 minutes to open the redirect URL and authorize the payment in the MobilePay app. If the underlying card charge fails, your customer can choose a different card and retry in the MobilePay app. If the payment isn’t authorized within 5 minutes, the payment fails and the PaymentIntent’s status transitions to `requires_payment_method`. ## 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 the integration Using your [test API keys](https://docs.stripe.com/keys.md#test-live-modes), create a PaymentIntent. After confirming the PaymentIntent, follow the `next_action` redirect URL to a test page with options to authorize or fail the payment. - Click **Authorize test payment** to test the case when the payment is successful. The PaymentIntent transitions from `requires_action` to `succeeded`. - Click **Fail test payment** to test the case when the customer fails to authenticate. The PaymentIntent transitions from `requires_action` to `requires_payment_method`. ## Optional: Authorize a payment and then capture later MobilePay supports [separate authorization and capture](https://docs.stripe.com/payments/place-a-hold-on-a-payment-method.md). ### 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 card linked to MobilePay. ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=dkk \ -d capture_method=manual \ -d "payment_method_types[]=mobilepay" \ -d "payment_method_data[type]=mobilepay" ``` After the authorization is successful, Stripe sends a [payment_intent.amount_capturable_updated](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.amount_capturable_updated) event. See [Events](https://docs.stripe.com/api/events.md) to learn more. ### Capture the funds After the authorization succeeds, the PaymentIntent’s [status](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-status) transitions to `requires_capture` and you can [capture](https://docs.stripe.com/api/payment_intents/capture.md) the authorized funds. Stripe only support manual captures of the full amount. ```curl curl https://api.stripe.com/v1/payment_intents/{{PAYMENTINTENT_ID}}/capture \ -u "<>:" \ -d amount_to_capture=1099 ``` ## Optional: Cancellation You can cancel MobilePay payments before they expire by [canceling the PaymentIntent](https://docs.stripe.com/api/payment_intents/cancel.md) associated with the MobilePay payment. ## Failed payments MobilePay transactions can fail if the underlying card transaction is declined. Learn more about [card declines](https://docs.stripe.com/declines/card.md). In this case, the PaymentMethod is detached and the PaymentIntent’s status automatically transitions to `requires_payment_method`. When the PaymentIntent’s status is `requires_action`, your customer must authenticate the payment within 5 minutes. If no action is taken after 5 minutes, the PaymentMethod detaches and the PaymentIntent’s status automatically transitions to `requires_payment_method`. ## Refunds and disputes Stripe performs a card transaction using standard card rails as part of a MobilePay transaction. [Refunds](https://docs.stripe.com/refunds.md) and [disputes](https://docs.stripe.com/disputes/how-disputes-work.md) are subject to the Visa and Mastercard network rules. # 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/mobilepay/accept-a-payment?payment-ui=mobile&platform=ios. MobilePay is a [single-use](https://docs.stripe.com/payments/payment-methods.md#usage) card wallet payment method used in Denmark and Finland. It allows your customer to [authenticate and approve](https://docs.stripe.com/payments/payment-methods.md#customer-actions) payments using the MobilePay app. When your customer pays with MobilePay, Stripe performs a card transaction using the card data we receive from MobilePay. The processing of the card transaction is invisible to your integration, and Stripe [immediately notifies you](https://docs.stripe.com/payments/payment-methods.md#payment-notification) whether the payment succeeded or failed. Stripe recommends using the [Mobile Payment Element](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=ios), an embeddable payment form, to add MobilePay and other payment methods to your integration with the least amount of effort. This guide covers how to accept MobilePay from your native mobile application using your own custom payment form. Your native mobile application redirects your customer to the MobilePay mobile application to complete the payment. Completing the purchase requires no additional action in the MobilePay mobile application. ## 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. To create and confirm a `PaymentIntent` on your server: - Specify the amount to collect and a supported currency (`eur`, `dkk`, `sek`, or `nok`). - Add `mobilepay` to the list of [payment method types](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_types) for your `PaymentIntent`. Make sure that you enable MobilePay in the [Dashboard](https://dashboard.stripe.com/settings/payment_methods). - Set `payment_method_data[type]` to `mobilepay` to create a *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs) and immediately use it with this PaymentIntent. ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=dkk \ -d "payment_method_types[]=mobilepay" \ -d "payment_method_data[type]=mobilepay" \ --data-urlencode "return_url=payments-example://stripe-redirect" ``` The PaymentIntent includes a *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)). Send the client secret to the client to *confirm* (Confirming an intent indicates that the customer intends to use the current or provided payment method. Upon confirmation, the intent attempts to initiate the portions of the flow that have real-world side effects) the PaymentIntent in the next step. ### Client-side On the client, request a PaymentIntent from your server and store its client secret. #### 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 } } ``` ## Submit the payment to Stripe [Client-side] When a customer taps to pay with MobilePay, 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. ### Set up a return URL O cliente pode sair do seu aplicativo para autenticar (por exemplo, no Safari ou no aplicativo bancário). Para permitir que eles voltem ao seu aplicativo após a autenticação, [configure um esquema de URL personalizado](https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app) e configure seu aplicativo delegado para encaminhar o URL ao SDK. A Stripe não aceita [links universais](https://developer.apple.com/documentation/xcode/allowing-apps-and-websites-to-link-to-your-content). #### SceneDelegate #### Swift ```swift // This method handles opening custom URL schemes (for example, "your-app://stripe-redirect") func scene(_ scene: UIScene, openURLContexts URLContexts: Set) { guard let url = URLContexts.first?.url else { return } let stripeHandled = StripeAPI.handleURLCallback(with: url) if (!stripeHandled) { // This was not a Stripe url – handle the URL normally as you would } } ``` #### AppDelegate #### 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 } ``` #### SwiftUI #### Swift ```swift @main struct MyApp: App { var body: some Scene { WindowGroup { Text("Hello, world!").onOpenURL { incomingURL in let stripeHandled = StripeAPI.handleURLCallback(with: incomingURL) if (!stripeHandled) { // This was not a Stripe url – handle the URL normally as you would } } } } } ``` ### Confirm the payment Use the PaymentIntent client secret from [step 2](https://docs.stripe.com/payments/mobilepay/accept-a-payment.md#create-payment-intent) to confirm the PaymentIntent using [STPPaymentHandler.shared.confirmPayment()](https://stripe.dev/stripe-ios/stripepayments/documentation/stripepayments/stppaymenthandler/confirmpayment\(_:with:completion:\)). This opens the MobilePay application directly (if present) or a webview showing the MobilePay landing page. After the customer authorizes the payment, the completion block contains the status of the payment. #### Swift ```swift let paymentIntentParams = STPPaymentIntentParams(clientSecret: paymentIntentClientSecret) paymentIntentParams.paymentMethodParams = STPPaymentMethodParams( mobilePay: STPPaymentMethodMobilePayParams(), billingDetails: nil, metadata: nil ) paymentIntentParams.returnURL = "your-app://stripe-redirect" // Set returnURL to your app's return URL that you set up in the previous step 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() } } ``` Your customer has 5 minutes to authorize the payment in the MobilePay app. If the underlying card charge fails, your customer can choose a different card and retry in the MobilePay app. ## 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 the integration Use your [test API keys](https://docs.stripe.com/keys.md#test-live-modes) to create a PaymentIntent. After confirming the PaymentIntent, follow the `next_action` redirect URL to a test page with options to authorize or fail the payment. - Click **Authorize test payment** to test the case when the payment is successful. The PaymentIntent’s [status](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-status) transitions from `requires_action` to `succeeded`. - Click **Fail test payment** to test the case when the customer fails to authenticate. The PaymentIntent’s [status](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-status) transitions from `requires_action` to `requires_payment_method`. ## Optional: Cancellation You can cancel MobilePay payments before they expire by [canceling the PaymentIntent](https://docs.stripe.com/api/payment_intents/cancel.md) associated with the MobilePay payment. ## Failed payments MobilePay transactions can fail if the underlying card transaction is declined. Learn more about [card declines](https://docs.stripe.com/declines/card.md). In this case, the PaymentMethod is detached and the PaymentIntent’s status automatically transitions to `requires_payment_method`. When the PaymentIntent’s status is `requires_action`, your customer must authenticate the payment within 5 minutes. If no action is taken after 5 minutes, the PaymentMethod detaches and the PaymentIntent’s status automatically transitions to `requires_payment_method`. ## Refunds and disputes Stripe performs a card transaction using standard card rails as part of a MobilePay transaction. [Refunds](https://docs.stripe.com/refunds.md) and [disputes](https://docs.stripe.com/disputes/how-disputes-work.md) are subject to the Visa and Mastercard network rules. # 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/mobilepay/accept-a-payment?payment-ui=mobile&platform=android. MobilePay is a [single-use](https://docs.stripe.com/payments/payment-methods.md#usage) card wallet payment method used in Denmark and Finland. It allows your customer to [authenticate and approve](https://docs.stripe.com/payments/payment-methods.md#customer-actions) payments using the MobilePay app. When your customer pays with MobilePay, Stripe performs a card transaction using the card data we receive from MobilePay. The processing of the card transaction is invisible to your integration, and Stripe [immediately notifies you](https://docs.stripe.com/payments/payment-methods.md#payment-notification) whether the payment succeeded or failed. Stripe recommends using the [Mobile Payment Element](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=android), an embeddable payment form, to add MobilePay and other payment methods to your integration with the least amount of effort. This guide covers how to accept MobilePay from your native mobile application using your own custom payment form. Your native mobile application redirects your customer to the MobilePay mobile application to complete the payment. Completing the purchase requires no additional action in the MobilePay mobile application. ## 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.7.0") // Include the financial connections SDK to support US bank account as a payment method implementation("com.stripe:financial-connections:23.7.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. To create and confirm a `PaymentIntent` on your server: - Specify the amount to collect and a supported currency (`eur`, `dkk`, `sek`, or `nok`). - Add `mobilepay` to the list of [payment method types](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_types). Make sure that you enable MobilePay in the [Dashboard](https://dashboard.stripe.com/settings/payment_methods). - Set `payment_method_data[type]` to `mobilepay` to create a *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs) and immediately use it with this PaymentIntent. ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=dkk \ -d "payment_method_types[]=mobilepay" \ -d "payment_method_data[type]=mobilepay" ``` The PaymentIntent includes a *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)). Send the client secret to the client to *confirm* (Confirming an intent indicates that the customer intends to use the current or provided payment method. Upon confirmation, the intent attempts to initiate the portions of the flow that have real-world side effects) the PaymentIntent in the next step. ### Client-side On the client, request a PaymentIntent from your server and store its client secret. #### 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 } } ``` ## Submit the payment to Stripe [Client-side] When a customer taps to pay with MobilePay, 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 the payment Use the PaymentIntent client secret from [step 2](https://docs.stripe.com/payments/mobilepay/accept-a-payment.md#create-payment-intent) to confirm the PaymentIntent using [PaymentLauncher confirm](https://stripe.dev/stripe-android/payments-core/com.stripe.android.payments.paymentlauncher/-payment-launcher/index.html#74063765%2FFunctions%2F-1622557690). This opens the MobilePay application directly (if present) or a webview showing the MobilePay landing page. After the customer authorizes the payment, `onPaymentResult` contains the status of the payment. #### Kotlin ```kotlin class CheckoutActivity : AppCompatActivity() { // ... private lateinit var paymentIntentClientSecret: String private val paymentLauncher: PaymentLauncher by lazy { PaymentLauncher.create( this, PaymentConfiguration.getInstance(applicationContext).publishableKey, PaymentConfiguration.getInstance(applicationContext).stripeAccountId, ::onPaymentResult ) } private fun startCheckout() { // ... val confirmParams = ConfirmPaymentIntentParams .createWithPaymentMethodCreateParams( paymentMethodCreateParams = PaymentMethodCreateParams.createMobilePay(), clientSecret = paymentIntentClientSecret ) paymentLauncher.confirm(confirmParams) } private fun onPaymentResult(paymentResult: PaymentResult) { val message = when (paymentResult) { is PaymentResult.Completed -> { "Completed!" } is PaymentResult.Canceled -> { "Canceled!" } is PaymentResult.Failed -> { // This string comes from the PaymentIntent's error message. // See: https://docs.stripe.com/api/payment_intents/object#payment_intent_object-last_payment_error-message "Failed: " + paymentResult.throwable.message } } } } ``` Your customer has 5 minutes to authorize the payment in the MobilePay app. If the underlying card charge fails, your customer can choose a different card and retry in the MobilePay app. ## 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 the integration Use your [test API keys](https://docs.stripe.com/keys.md#test-live-modes) to create a PaymentIntent. After confirming the PaymentIntent, follow the `next_action` redirect URL to a test page with options to authorize or fail the payment. - Click **Authorize test payment** to test the case when the payment is successful. The PaymentIntent’s [status](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-status) transitions from `requires_action` to `succeeded`. - Click **Fail test payment** to test the case when the customer fails to authenticate. The PaymentIntent’s [status](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-status) transitions from `requires_action` to `requires_payment_method`. ## Optional: Cancellation You can cancel MobilePay payments before they expire by [canceling the PaymentIntent](https://docs.stripe.com/api/payment_intents/cancel.md) associated with the MobilePay payment. ## Failed payments MobilePay transactions can fail if the underlying card transaction is declined. Learn more about [card declines](https://docs.stripe.com/declines/card.md). In this case, the PaymentMethod is detached and the PaymentIntent’s status automatically transitions to `requires_payment_method`. When the PaymentIntent’s status is `requires_action`, your customer must authenticate the payment within 5 minutes. If no action is taken after 5 minutes, the PaymentMethod detaches and the PaymentIntent’s status automatically transitions to `requires_payment_method`. ## Refunds and disputes Stripe performs a card transaction using standard card rails as part of a MobilePay transaction. [Refunds](https://docs.stripe.com/refunds.md) and [disputes](https://docs.stripe.com/disputes/how-disputes-work.md) are subject to the Visa and Mastercard network rules. # React Native > This is a React Native for when payment-ui is mobile and platform is react-native. View the full page at https://docs.stripe.com/payments/mobilepay/accept-a-payment?payment-ui=mobile&platform=react-native. MobilePay is a [single-use](https://docs.stripe.com/payments/payment-methods.md#usage) card wallet payment method used in Denmark and Finland. It allows your customer to [authenticate and approve](https://docs.stripe.com/payments/payment-methods.md#customer-actions) payments using the MobilePay app. When your customer pays with MobilePay, Stripe performs a card transaction using the card data we receive from MobilePay. The processing of the card transaction is invisible to your integration, and Stripe [immediately notifies you](https://docs.stripe.com/payments/payment-methods.md#payment-notification) whether the payment succeeded or failed. Stripe recommends using the [Mobile Payment Element](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=react-native), an embeddable payment form, to add MobilePay and other payment methods to your integration with the least amount of effort. This guide covers how to accept MobilePay from your native mobile application using your own custom payment form. Your native mobile application redirects your customer to a webview to complete the payment on MobilePay. ## Set up Stripe [Server-side] [Client-side] First, you need a Stripe account. [Register now](https://dashboard.stripe.com/register). ### Server-side This integration requires endpoints on your server that talk to the Stripe API. Use the official libraries for access to the Stripe API from your server: #### 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' ``` ### Client-side O [SDK do React Native](https://github.com/stripe/stripe-react-native) é de código aberto e totalmente documentado. Internamente, utiliza as SDKs de [iOS nativo](https://github.com/stripe/stripe-ios) e [Android](https://github.com/stripe/stripe-android). Para instalar o SDK do React Native da Stripe, execute um dos seguintes comandos no diretório do seu projeto (dependendo de qual gerenciador de pacotes você usa): #### yarn ```bash yarn add @stripe/stripe-react-native ``` #### npm ```bash npm install @stripe/stripe-react-native ``` Em seguida, instale algumas outras dependências necessárias: - Para iOS, vá para o diretório **ios** e execute `pod install` para garantir a instalação das dependências nativas necessárias. - Para Android, não há mais dependências para instalar. > Recomendamos seguir o [guia oficial do TypeScript](https://reactnative.dev/docs/typescript#adding-typescript-to-an-existing-project) para adicionar suporte ao TypeScript. ### Inicialização da Stripe Para inicializar a Stripe no aplicativo React Native, insira sua tela de pagamento com o componente `StripeProvider` ou use o método de inicialização `initStripe`. Somente a [chave da API publicável](https://docs.stripe.com/keys.md#obtain-api-keys) em `publishableKey` é necessária. O exemplo a seguir mostra como inicializar a Stripe usando o componente `StripeProvider`. ```jsx import { useState, useEffect } from 'react'; import { StripeProvider } from '@stripe/stripe-react-native'; function App() { const [publishableKey, setPublishableKey] = useState(''); const fetchPublishableKey = async () => { const key = await fetchKey(); // fetch key from your server here setPublishableKey(key); }; useEffect(() => { fetchPublishableKey(); }, []); return ( {/* Your app code here */} ); } ``` > Use suas [chaves de API de teste](https://docs.stripe.com/keys.md#obtain-api-keys) enquanto testa e desenvolve, e as chaves de [modo de produção](https://docs.stripe.com/keys.md#test-live-modes) quando publica 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. To create and confirm a `PaymentIntent` on your server: - Specify the amount to collect and a supported currency (`eur`, `dkk`, `sek`, or `nok`). - Add `mobilepay` to the list of [payment method types](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_types). Make sure that you enable MobilePay in the [Dashboard](https://dashboard.stripe.com/settings/payment_methods). ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=dkk \ -d "payment_method_types[]=mobilepay" \ --data-urlencode "return_url=payments-example://stripe-redirect" ``` The PaymentIntent includes a *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)). Send the client secret to the client to *confirm* (Confirming an intent indicates that the customer intends to use the current or provided payment method. Upon confirmation, the intent attempts to initiate the portions of the flow that have real-world side effects) the PaymentIntent in the next step. ### Client-side On the client, request a PaymentIntent from your server and store its client secret: ```javascript function PaymentScreen() { const fetchPaymentIntentClientSecret = async () => { const response = await fetch(`${API_URL}/create-payment-intent`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ currency: 'dkk', }), }); const {clientSecret} = await response.json(); return clientSecret; }; const handlePayPress = async () => { // See below }; return (