# Set up a subscription with BECS Direct Debit in Australia Learn how to create and charge for a subscription with BECS Direct Debit. > Se você é um usuário novo, use o[Payment Element](https://docs.stripe.com/payments/payment-element.md) em vez de usar Stripe Elements como descrito neste guia. O Payment Element oferece um caminho de integração low-code com otimizações de conversão integradas. Para instruções, veja[Criar uma assinatura](https://docs.stripe.com/billing/subscriptions/build-subscriptions.md?payment-ui=elements). Use this guide to set up a *subscription* (A Subscription represents the product details associated with the plan that your customer subscribes to. Allows you to charge the customer on a recurring basis) using [BECS Direct Debit](https://docs.stripe.com/payments/au-becs-debit.md) as a payment method. ## Criar um produto e preço [Dashboard] [Produtos](https://docs.stripe.com/api/products.md) representam o item ou serviço que você está vendendo. [Preços](https://docs.stripe.com/api/prices.md) definem quanto e com que frequência você cobra por um produto. Você estabelece quanto custa o produto, qual moeda você aceita e se a cobrança é avulsa ou recorrente. Se você tiver apenas alguns produtos e preços, crie e gerencie-os no Dashboard. Este guia usa um serviço de banco de imagens como exemplo e cobra dos clientes uma assinatura mensal de 15 AUD. Para modelar isso: 1. Vá para a página [Produtos](https://dashboard.stripe.com/products?active=true) e clique em **Criar produto**. 1. Insira um **Nome** para o produto. Opcionalmente, você pode adicionar uma **Descrição** e fazer o upload de uma imagem do produto. 1. Selecione um **Código fiscal de produto**. Saiba mais sobre [códigos fiscais de produto](https://docs.stripe.com/tax/tax-codes.md). 1. Selecione **Recorrente**. Em seguida, insira **15** como preço e selecione **AUD** como moeda. 1. Escolha se deseja **Incluir imposto no preço**. Você pode usar o valor padrão das suas [configurações fiscais](https://dashboard.stripe.com/test/settings/tax) ou definir o valor manualmente. Neste exemplo, selecione **Automático**. 1. Em **Período de faturamento**, selecione **Mensal**. 1. Clique em **Mais opções de planos de preços**. Em seguida, selecione **Taxa fixa** como o modelo de preço para este exemplo. Saiba mais sobre [taxa fixa](https://docs.stripe.com/products-prices/pricing-models.md#flat-rate) e outros [modelos de planos de preços](https://docs.stripe.com/products-prices/pricing-models.md). 1. Adicione uma **Descrição de preço** interna e uma [Chave de pesquisa](https://docs.stripe.com/products-prices/manage-prices.md#lookup-keys) para organizar, consultar e atualizar preços específicos no futuro. 1. Clique em **Próximo**. Em seguida, clique em **Adicionar produto**. Depois de criar o produto e o preço, registre o ID do preço para utilizá-lo nas etapas subsequentes. A página de preços exibe o ID, que tem esta estrutura: `price_G0FvDp6vZvdwRZ`. ## Criar um SetupIntent [Do lado do servidor] A [SetupIntent](https://docs.stripe.com/api/setup_intents.md) is an object that represents your intent to set up a customer’s payment method for future payments. The `SetupIntent` will track the steps of this set-up process. For BECS Direct Debit, this includes collecting a mandate from the customer and tracking its validity throughout its lifecycle. Create a [SetupIntent](https://docs.stripe.com/api/setup_intents.md) on your server with [payment_method_types](https://docs.stripe.com/api/setup_intents/create.md#create_setup_intent-payment_method_types) set to `au_becs_debit`: #### curl ```bash curl https://api.stripe.com/v1/setup_intents \ -u <>: \ -d "payment_method_types[]"="au_becs_debit" ``` The returned `SetupIntent` object contains a `client_secret` property. Pass the client secret to the client-side application to continue with the setup process. ## Coletar detalhes de forma de pagamento e reconhecimento de mandato [Lado do cliente] You’re ready to collect payment information on the client with [Stripe Elements](https://docs.stripe.com/payments/elements.md). Elements is a set of prebuilt UI components for collecting payment details. Um Stripe Element contém um iframe que envia com segurança os dados de pagamento para a Stripe por uma conexão HTTPS. O endereço da página de checkout também deve iniciar com https://, e não http://, para que sua integração funcione. Você pode testar sua integração sem usar HTTPS. [Habilite-o](https://docs.stripe.com/security/guide.md#tls) quando estiver pronto para aceitar pagamentos no modo de produção. ### Configurar o Stripe Elements #### HTML + JS Stripe Elements is automatically available as a feature of Stripe.js. Include the Stripe.js script on your payment page by adding it to the `head` of your HTML file. Always load Stripe.js directly from js.stripe.com to remain PCI compliant. Don’t include the script in a bundle or host a copy of it yourself. ```html Payment Setup ``` Create an instance of [Elements](https://docs.stripe.com/js.md#stripe-elements) with the following JavaScript on your payment page: ```javascript const stripe = Stripe('<>'); const elements = stripe.elements(); ``` ### Direct Debit Requests Before you can create a BECS Direct Debit payment, your customer must agree with the Direct Debit Request Service Agreement. They do so by submitting a completed Direct Debit Request (DDR). The approval gives you a mandate to debit their account. The `Mandate` is a record of the permission to debit a payment method. For online mandate acceptance, you can create a form to collect the necessary information. Serve the form over [HTTPS](https://docs.stripe.com/security/guide.md#tls) and capture the following information: | Informações | Descrição | | ------------------ | ------------------------------------------------------------------------- | | **Account name** | The full name of the account holder | | **BSB number** | The Bank-State-Branch number of the bank account (for example, `123-456`) | | **Account number** | The bank account number (for example, `87654321`) | When collecting a Direct Debit Request, follow our [BECS Direct Debit Terms](https://stripe.com/au-becs/legal) and as part of your checkout form: - Display the exact terms of [Stripe’s DDR service agreement](https://stripe.com/au-becs-dd-service-agreement/legal) either inline on the form, or on a page linked from the form, and identifying it as the “DDR service agreement.” - Make sure the accepted DDR and its accompanying [DDR service agreement](https://stripe.com/au-becs-dd-service-agreement/legal) can be shared with your customer at all times, either as a printed or non-changeable electronic copy (such as email). Stripe hosts this for you. - Display the following standard authorization text for your customer to accept the BECS DDR, where you replace *Rocketship Inc* with your company name. Their acceptance authorizes you to initiate BECS Direct Debit payments from their bank account. > By providing your bank account details, you agree to this Direct Debit Request and the [Direct Debit Request service agreement](https://stripe.com/au-becs-dd-service-agreement/legal), and authorize Stripe Payments Australia Pty Ltd ACN 160 180 343 Direct Debit User ID number 507156 (“Stripe”) to debit your account through the Bulk Electronic Clearing System (BECS) on behalf of *Rocketship Inc* (the “Merchant”) for payments as per the terms of your agreement with the Merchant. You certify that you’re either an account holder or an authorized signatory on the account listed above. The details of the accepted mandate are generated when setting up a [PaymentMethod](https://docs.stripe.com/payments/payment-methods.md) or confirming a `PaymentIntent`. At all times, you should be able to share this mandate—the accepted DDR and its accompanying DDR service agreement—with your customer, either in print or as a non-changeable electronic copy (such as email). Stripe hosts this for you under the `url` property of the `Mandate` object linked to the `PaymentMethod`. ### Add and configure an Australia Bank Account Element The Australia Bank Account Element will help you collect and validate both the BSB number and the account number. It needs a place to live in your payment form. Create empty DOM nodes (containers) with unique IDs in your payment form. Additionally, your customer must read and accept the [Direct Debit Request service agreement](https://stripe.com/au-becs-dd-service-agreement/legal). #### HTML ```html
By providing your bank account details, you agree to this Direct Debit Request and the Direct Debit Request service agreement, and authorise Stripe Payments Australia Pty Ltd ACN 160 180 343 Direct Debit User ID number 507156 (“Stripe”) to debit your account through the Bulk Electronic Clearing System (BECS) on behalf ofRocket Rides(the "Merchant") for any amounts separately communicated to you by the Merchant. You certify that you are either an account holder or an authorised signatory on the account listed above.
``` When the form loads, you can [create an instance](https://docs.stripe.com/js/elements_object/create_element?type=au_bank_account) of the Australia Bank Account Element and mount it to the Element container: ```javascript // Custom styling can be passed to options when creating an Element const style = { base: { color: '#32325d', fontSize: '16px', '::placeholder': { color: '#aab7c4' }, ':-webkit-autofill': { color: '#32325d', }, }, invalid: { color: '#fa755a', iconColor: '#fa755a', ':-webkit-autofill': { color: '#fa755a', }, } }; const options = { style: style, disabled: false, hideIcon: false, iconStyle: "default", // or "solid" } // Create an instance of the auBankAccount Element. const auBankAccount = elements.create('auBankAccount', options); // Add an instance of the auBankAccount Element into // the `au-bank-account-element`
. auBankAccount.mount('#au-bank-account-element'); ``` #### React #### npm 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 ``` #### umd Também fornecemos uma compilação UMD para sites que não usam npm nem módulos. Insira o script Stripe.js, que exporta uma função `Stripe` global, e a compilação UMD de React Stripe.js, que exporta um objeto `ReactStripe` global. Sempre carregue o script Stripe.js diretamente de **js.stripe.com** para manter a conformidade com PCI. Não insira o script em um pacote nem hospede sua própria cópia dele. ```html ``` > A [demonstração da CodeSandbox](https://codesandbox.io/s/react-stripe-official-q1loc?fontsize=14&hidenavigation=1&theme=dark) permite testar o React Stripe.js sem criar um novo projeto. ### Adicione Stripe.js e Elements à sua página Para usar componentes do Elements, 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`. ```jsx import React from 'react'; import ReactDOM from 'react-dom'; import {Elements} from '@stripe/react-stripe-js'; import {loadStripe} from '@stripe/stripe-js'; import PaymentSetupForm from './PaymentSetupForm'; // 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() { return ( ); }; ReactDOM.render(, document.getElementById('root')); ``` ### Direct Debit Requests Before you can create a BECS Direct Debit payment, your customer must agree with the Direct Debit Request Service Agreement. They do so by submitting a completed Direct Debit Request (DDR). The approval gives you a mandate to debit their account. The `Mandate` is a record of the permission to debit a payment method. For online mandate acceptance, you can create a form to collect the necessary information. Serve the form over [HTTPS](https://docs.stripe.com/security/guide.md#tls) and capture the following information: | Informações | Descrição | | ------------------ | ------------------------------------------------------------------------- | | **Account name** | The full name of the account holder | | **BSB number** | The Bank-State-Branch number of the bank account (for example, `123-456`) | | **Account number** | The bank account number (for example, `87654321`) | When collecting a Direct Debit Request, follow our [BECS Direct Debit Terms](https://stripe.com/au-becs/legal) and as part of your checkout form: - Display the exact terms of [Stripe’s DDR service agreement](https://stripe.com/au-becs-dd-service-agreement/legal) either inline on the form, or on a page linked from the form, and identifying it as the “DDR service agreement.” - Make sure the accepted DDR and its accompanying [DDR service agreement](https://stripe.com/au-becs-dd-service-agreement/legal) can be shared with your customer at all times, either as a printed or non-changeable electronic copy (such as email). Stripe hosts this for you. - Display the following standard authorization text for your customer to accept the BECS DDR, where you replace *Rocketship Inc* with your company name. Their acceptance authorizes you to initiate BECS Direct Debit payments from their bank account. > By providing your bank account details, you agree to this Direct Debit Request and the [Direct Debit Request service agreement](https://stripe.com/au-becs-dd-service-agreement/legal), and authorize Stripe Payments Australia Pty Ltd ACN 160 180 343 Direct Debit User ID number 507156 (“Stripe”) to debit your account through the Bulk Electronic Clearing System (BECS) on behalf of *Rocketship Inc* (the “Merchant”) for payments as per the terms of your agreement with the Merchant. You certify that you’re either an account holder or an authorized signatory on the account listed above. The details of the accepted mandate are generated when setting up a [PaymentMethod](https://docs.stripe.com/payments/payment-methods.md) or confirming a `PaymentIntent`. At all times, you should be able to share this mandate—the accepted DDR and its accompanying DDR service agreement—with your customer, either in print or as a non-changeable electronic copy (such as email). Stripe hosts this for you under the `url` property of the `Mandate` object linked to the `PaymentMethod`. ### Add and configure an AuBankAccountElement component The `AuBankAccountElement` component will help you collect and validate both the BSB number and the account number. Additionally, your customer must read and accept the [Direct Debit Request service agreement](https://stripe.com/au-becs-dd-service-agreement/legal). #### JSX ```jsx /** * Use the CSS tab above to style your Element's container. */ import React from 'react'; import {AuBankAccountElement} from '@stripe/react-stripe-js'; import './BecsFormStyles.css' // Custom styling can be passed as options when creating an Element. const AU_BANK_ACCOUNT_STYLE = { base: { color: '#32325d', fontSize: '16px', '::placeholder': { color: '#aab7c4' }, ':-webkit-autofill': { color: '#32325d', }, }, invalid: { color: '#fa755a', iconColor: '#fa755a', ':-webkit-autofill': { color: '#fa755a', }, } }; const AU_BANK_ACCOUNT_ELEMENT_OPTIONS = { style: AU_BANK_ACCOUNT_STYLE, disabled: false, hideIcon: false, iconStyle: "default", // or "solid" }; export default function BecsForm({onSubmit, disabled}) { return (
{/* Display mandate acceptance text. */}
By providing your bank account details, you agree to this Direct Debit Request and the Direct Debit Request service agreement, and authorise Stripe Payments Australia Pty Ltd ACN 160 180 343 Direct Debit User ID number 507156 (“Stripe”) to debit your account through the Bulk Electronic Clearing System (BECS) on behalf ofRocket Rides(the "Merchant") for any amounts separately communicated to you by the Merchant. You certify that you are either an account holder or an authorised signatory on the account listed above.
``` Elements are completely customizable. You can [style Elements](https://docs.stripe.com/js/elements_object/create_element?type=au_bank_account#elements_create-options) to match the look and feel of your site, providing a seamless checkout experience for your customers. It’s also possible to style various input states, for example when the Element has focus. ## Enviar os detalhes da forma de pagamento para a Stripe [Lado do cliente] Rather than sending the entire `SetupIntent` object to the client, use its [client secret](https://docs.stripe.com/api/setup_intents/object.md#setup_intent_object-client_secret) from [step 2](https://docs.stripe.com/billing/subscriptions/au-becs-debit.md#web-create-setup-intent). This is different from your API keys that authenticate Stripe API requests. The client secret should be handled carefully because it can complete the setup. Don’t log it, embed it in URLs, or expose it to anyone but the customer. #### HTML + JS Use [stripe.confirmAuBecsDebitSetup](https://docs.stripe.com/js/setup_intents/confirm_au_becs_debit_setup) to complete the setup when the user submits the form. A successful setup returns a `succeeded` value for the SetupIntent’s `status` property. If the setup isn’t successful, inspect the returned `error` to determine the cause. ```javascript const form = document.getElementById('setup-form'); const accountholderName = document.getElementById('accountholder-name'); const email = document.getElementById('email'); const submitButton = document.getElementById('submit-button'); const clientSecret = submitButton.dataset.secret; form.addEventListener('submit', async (event) => { event.preventDefault(); stripe.confirmAuBecsDebitSetup( clientSecret, { payment_method: { au_becs_debit: auBankAccount, billing_details: { name: accountholderName.value, email: email.value } } } ); }); ``` After successfully confirming the `SetupIntent`, you should share the [mandate URL](https://docs.stripe.com/api/mandates/object.md#mandate_object-payment_method_details-au_becs_debit-url) from the [Mandate object](https://docs.stripe.com/api/mandates.md) with your customer. We also recommend including the following details to your customer when you confirm their mandate has been established: - an explicit confirmation message that indicates a Direct Debit arrangement has been set up - the [business name](https://docs.stripe.com/billing/subscriptions/au-becs-debit.md#statement-descriptors) that will appear on the customer’s bank statement whenever their account gets debited - the payment amount and schedule (if applicable) - a link to the generated DDR mandate URL The `Mandate` object’s ID is accessible from the `mandate` on the SetupIntent object, which is sent as part of the `setup_intent.succeeded` event sent after confirmation, but can also be [retrieved through the API](https://docs.stripe.com/api/setup_intents/retrieve.md). ```curl curl -G https://api.stripe.com/v1/setup_intents/{{SETUP_INTENT_ID}} \ -u "<>:" \ -d "expand[]=mandate" ``` #### React Use [stripe.confirmAuBecsDebitSetup](https://docs.stripe.com/js/setup_intents/confirm_au_becs_debit_setup) to complete the mandate collection when the user submits the form. Including the customer’s email address and the account holder’s name in the `billing_details` property of the `payment_method` parameter is required to create a BECS Direct Debit `PaymentMethod`. To call `stripe.confirmAuBecsDebitSetup` from your payment form component, use the [useStripe](https://docs.stripe.com/sdks/stripejs-react.md#usestripe-hook) and [useElements](https://docs.stripe.com/sdks/stripejs-react.md#useelements-hook) hooks. If you prefer traditional class components over hooks, you can instead use an [ElementsConsumer](https://docs.stripe.com/sdks/stripejs-react.md#elements-consumer). #### Hooks ```jsx import React from 'react'; import {useStripe, useElements, AuBankAccountElement} from '@stripe/react-stripe-js'; import BecsForm from './BecsForm'; export default function PaymentSetupForm() { const stripe = useStripe(); const elements = useElements(); 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 auBankAccount = elements.getElement(AuBankAccountElement); // For brevity, this example is using uncontrolled components for // the accountholder's name and email. In a real world app you will // probably want to use controlled components. // https://reactjs.org/docs/uncontrolled-components.html // https://reactjs.org/docs/forms.html#controlled-components const accountholderName = event.target['accountholder-name']; const email = event.target.email; const result = await stripe.confirmAuBecsDebitSetup('{{CLIENT_SECRET}}', { payment_method: { au_becs_debit: auBankAccount, billing_details: { name: accountholderName.value, email: email.value, }, } }); if (result.error) { // Show error to your customer. console.log(result.error.message); } else { // Show a confirmation message to your customer. // The SetupIntent is in the 'succeeded' state. } }; return ( ); } ``` #### Componentes de classe ```jsx import React from 'react'; import {ElementsConsumer, AuBankAccountElement} from '@stripe/react-stripe-js'; import BecsForm from './BecsForm'; class PaymentSetupForm extends React.Component { handleSubmit = async (event) => { // We don't want to let default form submission happen here, // which would refresh the page. event.preventDefault(); const {stripe, elements} = this.props; if (!stripe || !elements) { // Stripe.js hasn't yet loaded. // Make sure to disable form submission until Stripe.js has loaded. return; } const auBankAccount = elements.getElement(AuBankAccountElement); // For brevity, this example is using uncontrolled components for // the accountholder's name and email. In a real world app you will // probably want to use controlled components. // https://reactjs.org/docs/uncontrolled-components.html // https://reactjs.org/docs/forms.html#controlled-components const accountholderName = event.target['accountholder-name']; const email = event.target.email; const result = await stripe.confirmAuBecsDebitSetup('{{CLIENT_SECRET}}', { payment_method: { au_becs_debit: auBankAccount, billing_details: { name: accountholderName.value, email: email.value, }, } }); if (result.error) { // Show error to your customer. console.log(result.error.message); } else { // Show a confirmation message to your customer. // The SetupIntent is in the 'succeeded' state. } }; render() { const {stripe} = this.props; return ( ); } } export default function InjectedPaymentSetupForm() { return ( {({stripe, elements}) => ( )} ); } ``` After successfully confirming the `SetupIntent`, you should share the [mandate URL](https://docs.stripe.com/api/mandates/object.md#mandate_object-payment_method_details-au_becs_debit-url) from the [Mandate object](https://docs.stripe.com/api/mandates.md) with your customer. We also recommend including the following details to your customer when you confirm their mandate has been established: - an explicit confirmation message that indicates a Direct Debit arrangement has been set up - the [business name](https://docs.stripe.com/billing/subscriptions/au-becs-debit.md#statement-descriptors) that will appear on the customer’s bank statement whenever their account gets debited - the payment amount and schedule (if applicable) - a link to the generated DDR mandate URL The `Mandate` object’s ID is accessible from the `mandate` on the SetupIntent object, which is sent as part of the `setup_intent.succeeded` event sent after confirmation, but can also be [retrieved through the API](https://docs.stripe.com/api/setup_intents/retrieve.md). ```curl curl -G https://api.stripe.com/v1/setup_intents/{{SETUP_INTENT_ID}} \ -u "<>:" \ -d "expand[]=mandate" ``` ## Create a customer with a PaymentMethod [Do lado do servidor] Creating subscriptions requires an object that represents the customer, which can be either a customer-configured [Account](https://docs.stripe.com/api/v2/core/accounts/object.md) or a [Customer](https://docs.stripe.com/api.md#customer_object). Because the subscription charges recurring payments, you need to add a stored payment method to the customer to use for future payments. > #### Use a API Accounts v2 para representar clientes > > A API Accounts v2 está geralmente disponível para usuários do Connect e em prévia pública para outros usuários da Stripe. Se faz parte da prévia de Accounts v2, é necessário [especificar uma versão de prévia](https://docs.stripe.com/api-v2-overview.md#sdk-and-api-versioning) no seu código. > > Para solicitar acesso à prévia de Accounts v2, > > Para a maioria dos casos de uso, recomendamos [modelar seus clientes como objetos Accounts configuradas pelo cliente](https://docs.stripe.com/accounts-v2/use-accounts-as-customers.md), em vez de usar objetos [Customer](https://docs.stripe.com/api/customers.md). #### Accounts v2 [Create a customer-configured Account](https://docs.stripe.com/api/v2/core/accounts/create.md), then update it to set the payment method you just collected as its [configuration.customer.billing.default_payment_method](https://docs.stripe.com/api/v2/core/accounts/update.md#v2_update_accounts-configuration-customer-billing-default_payment_method). This makes the payment method the default for invoices and subscriptions. ```curl curl -X POST https://api.stripe.com/v2/core/accounts/acct_Gk0uVzT2M4xOKD \ -H "Authorization: Bearer <>" \ -H "Stripe-Version: 2026-04-22.preview" \ --json '{ "configuration": { "customer": { "billing": { "default_payment_method": "pm_1FU2bgBF6ERF9jhEQvwnA7sX" } } } }' ``` #### Customers v1 Create a `Customer` object and set the payment method you just collected as both the [payment_method](https://docs.stripe.com/api/customers/create.md#create_customer-payment_method) and the [invoice_settings.default_payment_method](https://docs.stripe.com/api/customers/create.md#create_customer-invoice_settings-default_payment_method): ```curl curl https://api.stripe.com/v1/customers \ -u "<>:" \ --data-urlencode "email=jenny.rosen@example.com" \ -d payment_method=pm_1FU2bgBF6ERF9jhEQvwnA7sX \ -d "invoice_settings[default_payment_method]=pm_1FU2bgBF6ERF9jhEQvwnA7sX" ``` This returns a `Customer` object. You can see the default payment method in the `invoice_settings`: ```json { "id": "cus_Gk0uVzT2M4xOKD", "object": "customer", "address": null, "balance": 0, "created": 1581797088, "currency": null, "default_source": null, "delinquent": false, "description": null, "discount": null, "email": "jenny.rosen@example.com", "invoice_prefix": "11D0B3D7", "invoice_settings": { "custom_fields": null, "default_payment_method": "pm_1FU2bgBF6ERF9jhEQvwnA7sX", "footer": null }, "livemode": false, "metadata": { }, "name": null, "phone": null, "preferred_locales": [ ], "shipping": null, "sources": { "object": "list", "data": [ ], "has_more": false, "total_count": 0, "url": "/v1/customers/cus_Gk0uVzT2M4xOKD/sources" }, "subscriptions": { "object": "list", "data": [ ], "has_more": false, "total_count": 0, "url": "/v1/customers/cus_Gk0uVzT2M4xOKD/subscriptions" }, "tax_exempt": "none", "tax_ids": { "object": "list", "data": [ ], "has_more": false, "total_count": 0, "url": "/v1/customers/cus_Gk0uVzT2M4xOKD/tax_ids" } } ``` After creating the customer, store its ID in your own database so you can use it later. ## Criar a assinatura [Do lado do servidor] Crie uma [assinatura](https://docs.stripe.com/api/subscriptions.md) com preço e cliente: #### Accounts v2 ```curl curl https://api.stripe.com/v1/subscriptions \ -u "<>:" \ -d "customer_account={{CUSTOMERACCOUNT_ID}}" \ -d "items[0][price]=price_F52b2UdntfQsfR" ``` #### Customers v1 ```curl curl https://api.stripe.com/v1/subscriptions \ -u "<>:" \ -d customer=cus_Gk0uVzT2M4xOKD \ -d "items[0][price]=price_F52b2UdntfQsfR" ``` Creating subscriptions automatically charges customers using the default payment method. After the first successful payment, the subscription status [in the Dashboard](https://dashboard.stripe.com/test/subscriptions) changes to **Active**. Subsequent charges use the price you created earlier. ## Gerenciar o status da assinatura [Lado do cliente] Quando o pagamento inicial for realizado, o status da assinatura ** (A Subscription represents the product details associated with the plan that your customer subscribes to. Allows you to charge the customer on a recurring basis) estará `active` e nenhuma outra ação será necessária. Quando os pagamentos falharem, o status será alterado para **Status da assinatura** definido nas suas [configurações de cobrança automática](https://docs.stripe.com/invoicing/automatic-collection.md). Notifique o cliente após uma falha e [cobre-o com uma forma de pagamento diferente](https://docs.stripe.com/billing/subscriptions/overview.md#requires-payment-method). > BECS Direct Debit payments are never automatically retried, even if you have a [retry schedule](https://docs.stripe.com/invoicing/automatic-collection.md) configured for other payment methods. ## Testar a integração You can test your form using the test BSB number `000000` and one of the test account numbers below with your [confirmAuBecsDebitSetup](https://docs.stripe.com/js/setup_intents/confirm_au_becs_debit_setup) request, or use the corresponding token to skip manually entering bank account details. | Número BSB | Número da conta | Token | Descrição | | ---------- | --------------- | ---------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `000000` | `000123456` | `pm_auBecsDebit_success` | O status do PaymentIntent criado com o PaymentMethod resultante muda de `processing` para `succeeded`. O status do mandato permanece `active`. | | `000000` | `900123456` | `pm_auBecsDebit_successDelayed` | O status do PaymentIntent criado com o PaymentMethod resultante muda de `processing` para `succeeded`, com um atraso de três minutos. O status do mandato permanece `active`. | | `000000` | `111111113` | `pm_auBecsDebit_accountClosed` | O status do PaymentIntent criado com o PaymentMethod resultante muda de `processing` para `requires_payment_method`, com o código de erro `account_closed`. O status do mandato muda para `inactive`. | | `000000` | `111111116` | `pm_auBecsDebit_noAccount` | O status do PaymentIntent criado com o PaymentMethod resultante muda de `processing` para `requires_payment_method`, com o código de erro `no_account`. O status do mandato muda para `inactive`. | | `000000` | `222222227` | `pm_auBecsDebit_referToCustomer` | O status do PaymentIntent criado com o PaymentMethod resultante muda de `processing` para `requires_payment_method`, com o código de erro `refer_to_customer`. O status do mandato permanece `active`. | | `000000` | `922222227` | `pm_auBecsDebit_referToCustomerDelayed` | O status do PaymentIntent criado com o PaymentMethod resultante muda de `processing` para `requires_payment_method`, com o código de erro `refer_to_customer` e um atraso de três minutos. O status da autorização permanece `active`. | | `000000` | `333333335` | `pm_auBecsDebit_debitNotAuthorized` | O status do PaymentIntent criado com o PaymentMethod resultante muda de `processing` para `requires_payment_method`, com o código de erro `debit_not_authorized`. O status da autorização muda para `inactive`. | | `000000` | `666666660` | `pm_auBecsDebit_dispute` | O status do PaymentIntent criado com o PaymentMethod resultante muda de `processing` para `succeeded`, mas uma contestação é criada imediatamente. | | `000000` | `343434343` | `pm_auBecsDebit_exceedsWeeklyLimit` | O PaymentIntent criado com o PaymentMethod resultante falha com um erro `charge_exceeds_source_limit` devido ao valor do pagamento, fazendo com que a conta exceda seu limite de volume de pagamentos semanal. | | `000000` | `121212121` | `pm_auBecsDebit_exceedsTransactionLimit` | O PaymentIntent criado com o PaymentMethod resultante falha com um erro `charge_exceeds_transaction_limit` porque o valor do pagamento excede o limite de volume de transações da conta. | ## Optional: Set the billing period Ao criar uma assinatura, ela define automaticamente o ciclo de cobrança por padrão. Por exemplo, se um cliente assina um plano mensal em 7 de setembro, ele será cobrado no dia 7 de cada mês subsequente. Algumas empresas preferem definir manualmente o ciclo de cobrança, de modo a cobrar todos os clientes ao mesmo tempo. O argumento [âncora do ciclo de cobrança](https://docs.stripe.com/api/subscriptions/create.md#create_subscription-billing_cycle_anchor) permite que você faça isso. #### Accounts v2 ```curl curl https://api.stripe.com/v1/subscriptions \ -u "<>:" \ -d "customer_account={{CUSTOMERACCOUNT_ID}}" \ -d "items[0][price]={{PRICE_ID}}" \ -d billing_cycle_anchor=1611008505 ``` #### Customers v1 ```curl curl https://api.stripe.com/v1/subscriptions \ -u "<>:" \ -d "customer={{CUSTOMER_ID}}" \ -d "items[0][price]={{PRICE_ID}}" \ -d billing_cycle_anchor=1611008505 ``` A definição manual do ciclo de cobrança gera cobra o cliente proporcionalmente pelo tempo decorrido da criação da assinatura até o primeiro dia do ciclo de cobrança. Se não quiser cobrar esse período dos clientes, defina o argumento [proration_behavior](https://docs.stripe.com/api/subscriptions/create.md#create_subscription-proration_behavior) como `none`. Você também pode combinar a âncora do ciclo de cobrança com [períodos de avaliação](https://docs.stripe.com/billing/subscriptions/au-becs-debit.md#trial-periods) para oferecer acesso gratuito ao seu produto e depois cobrar um valor proporcional. ## Optional: Avaliações de assinaturas As avaliações oferecem acesso gratuito ao seu produto por um período. Usar avaliações gratuitas é diferente de definir [proration_behavior](https://docs.stripe.com/api/subscriptions/create.md#create_subscription-proration_behavior) como `none`, porque você pode personalizar a duração do período gratuito. Passe um carimbo de data e hora em [fim do teste](https://docs.stripe.com/api/subscriptions/create.md#create_subscription-trial_end) para definir o período do teste. #### Accounts v2 ```curl curl https://api.stripe.com/v1/subscriptions \ -u "<>:" \ -d "customer_account={{CUSTOMERACCOUNT_ID}}" \ -d "items[0][price]={{PRICE_ID}}" \ -d trial_end=1610403705 ``` #### Clientes v1 ```curl curl https://api.stripe.com/v1/subscriptions \ -u "<>:" \ -d "customer={{CUSTOMER_ID}}" \ -d "items[0][price]={{PRICE_ID}}" \ -d trial_end=1610403705 ``` Também é possível combinar uma [âncora de ciclo de faturamento](https://docs.stripe.com/billing/subscriptions/au-becs-debit.md#billing-cycle) com um período de teste gratuito. Por exemplo, digamos que seja 15 de setembro e você queira oferecer um teste gratuito de sete dias e começar o ciclo de cobrança normal em 1º de outubro. Você pode definir o teste gratuito para terminar em 22 de setembro e a âncora do ciclo de faturamento para 1º de outubro. Assim, o cliente ganha um teste de sete dias e depois paga um valor proporcional do fim do teste até 1º de outubro. Em 1º de outubro, você cobra o valor normal da assinatura pelo primeiro ciclo de faturamento completo.