Stripe

How to connect

To connect Stripe payment system, you will need a secret API key and a webhook key.

You can copy the secret API key by going to the Developers -> API key section and copying the Secret key.

Step 1. Go to the Developers -> API key section:

Pic.1 How to find API section

Step 2. Find and copy the Secret key:

Next, you need to set the URL for callbacks. This is necessary in order for the bot to receive payment notifications.

Go to the Webhooks section and add the address for the webhooks.

The form opens:

Step 1. Click on "+add destination".

Step 2. Select events:

Step 3. Select the type of "Webhook endpoint":

Step 4. We get acquainted with the type of request and click "Continue":

Step 5. We write the name and specify the endpoint URL:

Specify URL - https://chatter.salebot.pro/stripe_callback/resultarrow-up-right

Step 6. Two endpoints will be created, you can view the settings before adding:

Step 7. Next, click the "Add destinations" button. Then the webhooks will be saved.

Step 8. Click the "Done" button.

We save it and get to the page with the installed webhook:

Step 9. Next, click on the webhook where you have selected all the events:

Step 10. We find the Signig key and save it to ourselves (in the future we will need it to connect to Salebot):

After receiving the keys, we proceed to connect to Mavibot.

In Mavibot, open "Acquiring" section and select Stripe.

On the connection page, you need to enter the received keys:

Click "Save Settings".

circle-check

How to connect a callback about the transaction status

To get an additional callback, we will need to connect a webhook in addition to the existing one.

Specify URL - https://chatter.salebot.pro/stripe_callback/<api_key>/charge_statusarrow-up-right

and select the events:

  • charge.failed

  • charge.pending

  • charge.succeeded

circle-check

We add the webhook received after saving to Mavibot field - Webhook key2:

stripe_invoice_id - Transaction ID for which the successful payment callback was not received immediately after the payment.

How to connect taxes

To use taxes in payments, firstly you need to create them in Stripe's personal account. To do this, enter tax rates in the search bar:

And click "+ Add tax rates":

Next, specify the applicable tax rate:

In the opened menu, select the tax type, the region for where it applies, the tax rate, and the option indicating whether this tax should be included in the payment amount 'Inclusive' or will be added in excess of the amount - exclusive:

After creating the tax rate, copy its ID into the stripe_tax_id variable before setting the payment amount.

To avoid errors, put an empty string ("") in the stripe_tax_id variable after receiving the link, so that you can apply the tax only when it is needed.

If everything is done correctly, then in the case of the tax rate with the exclusive parameter, you will see the following

Example of a payment with an exclusive tax rate

To generate a payment link, you need to set the value of the payment_sum variable (for example, 150 or 100.55 (separated by a dot!)), and the stripe_pay_url variable will appear after that. This variable can be displayed with a link or placed on a button with the text "Pay".

The link looks like:

https://checkout.stripe.com/pay/cs_test_a17mskKFFRwEuo3WgBSAUjfk7xaZZIrct9B3Ds2AdODVq1I8aRiqYEBdrU#fidkdWxOYHwnPyd1blpxYHZxWjA0TGFsVzFPVmpmMzJAbVYzUkp1Y0lLYDVgfzR2Q0NxcWZBNUNnTnRSVVRJSGFobEB1UExSczRMMTc8PWRLMGBddl8xalxyPDRoUGhnZm9xXXZANDZyaF0wNTVBVExsPHZyfycpJ2N3amhWYHdzYHcnP3F3cGApJ2lkfGpwcVF8dWAnPyd2bGtiaWBabHFgaCcpJ2BrZGdpYFVpZGZgbWppYWB3dic%2FcXdwYHgl

circle-exclamation

Also, before setting the value of the payment_sum variable, you can set the following optional variables to configure the payment.

Function parameters
Parameters description

currency

is the order currency. Acceptable values -https://stripe.com/docs/currenciesarrow-up-right

payment_description

order description

stripe_tax_id

This is the tax rate ID, set up in Stripe's personal account. How to set it up is described in the section "How to set taxes" ссылка "Как подключить налоги"

stripe_invoice_enable

This parameter indicates the need to save invoices (invoices,receipts). Enter any value — all necessary documents will then be available in your Stripe personal account.

stripe_locale

set language of the payment link: en, ru, de. All available languages are here: https://stripe.com/docs/api/checkout/sessions/create#create_checkout_session-locale arrow-up-right If the stripe_local value is not provided, the client’s browser language will be used by default.

stripe_payment_method_type

is the payment method, the default payment is by card. You can replace it with other payment methods available for Stripe. The available methods are listed below

For example, stripe_payment_method_type = "customer_balance"

stripe_additional_payment_method_type

is to add an additional payment method. The available methods are listed below for example, stripe_additional_payment_method_type = "sepa_debit"

coupon_id

discount coupon ID

stripe_expired

is the lifetime of the payment link. Specified in seconds. The minimum time is 30 minutes, the maximum is 24 hours. The default is 24 hours

stripe_automatic_tax

enabling automatic taxes calculation and collection during payment. To enable it, pass "1". Detailed information about this setting can be found in the Stripe documentation. ссылка в документации Stripe arrow-up-right

circle-exclamation
chevron-rightList of values for stripe_payment_method_type and stripe_additional_payment_method_typehashtag

card acss_debit affirm afterpay_clearpay alipay au_becs_debit bacs_debit bancontact blik boleto cashapp customer_balance eps fpx giropay grabpay ideal klarna konbini link oxxo p24 paynow paypal pix promptpay sepa_debit sofort us_bank_account wechat_pay zip

Подробнее про каждый из методов и для каких стран они доступны можно узнать в документации Stripe: посмотреть на сайте arrow-up-right

Пример формирования ссылки на оплату

Создадим ссылку на оплату в размере 1000 рублей (по умолчанию доллар)

circle-exclamation

Далее в нужном месте выводим переменную stripe_pay_url, в которой содержится ссылка в блоке либо в кнопке:

Пример 1. Выводим ссылку на оплату прямо в сообщении:

Тестирование в боте:

Пример 2. Добавляем ссылку на оплату в кнопку:

Пример 3. Добавляем ссылку в качестве вложения к сообщению:

Тестирование в боте:

circle-check

При клике на кнопку или при переходе по ссылке, вашего плательщика переадресует на платежную страницу:

В примере видно, что параметры, которые мы указывали в калькуляторе в настройках блока были применены: описание заказа, валюта и сумма.

Если передадите параметр налоговой ставки (stripe_tax_id) в блоке:

То также будет отображена налоговая ставка в форме оплаты:

chevron-rightПример кода для копированияhashtag

payment_description = 'Тестовая оплата в Страйп' currency = 'RUB' stripe_tax_id = 'скопируйте сюда ваш tax ID' payment_sum = 1000

Где найти tax ID:

Как настроить рекуррентные платежи

Для рекуррентных платежей (подписки) нужно до объявления переменной payment_sum объявить переменную stripe_subscription и присвоить ей название подписки.

Также можно добавить следующие переменные: interval – продолжительность интервала подписки, в эту переменную нужно передать значение ‘day’ - для дней, ‘week’ - недель, ‘month’ - месяцев, ‘year’ - лет. Если переменная не объявлена, то по умолчанию будет передан параметр ‘month’.

circle-exclamation

interval_count – количество указанных интервалов, сколько дней, недель или месяцев будет в подписке за указанную сумму. По умолчанию будет передан параметр, равный единице (1);

stripe_payment_method_type - метод оплаты, по умолчанию стоит оплата картой (card). Можно заменить на другие доступные для Stripe методы оплаты. Ниже указаны доступные методы.

Например, stripe_payment_method_type = 'customer_balance'

stripe_additional_payment_method_type - добавить дополнительный метод оплаты. Ниже указаны доступные методы

Например, stripe_additional_payment_method_type = 'sepa_debit'

circle-exclamation
chevron-rightList of values for stripe_payment_method_type и stripe_additional_payment_method_type:hashtag

card acss_debit affirm afterpay_clearpay alipay au_becs_debit bacs_debit bancontact blik boleto cashapp customer_balance eps fpx giropay grabpay ideal klarna konbini link oxxo p24 paynow paypal pix promptpay sepa_debit sofort us_bank_account wechat_pay zip

circle-info

For more information about each of the methods and for which countries they are available, see the Stripe documentation: see the website ссылка посмотреть на сайте arrow-up-right

circle-exclamation

In this example, a subscription named 'My_subscription' will be created with a price of 90 USD for 3 months and a repeat payment will be made with the same amount after these 1 month:

An example to copy:

stripe_subscription = 'My_subscription' interval = 'month' interval_count = 3 payment_sum = 90

After payment, the client will have stripe_subscription_id variables in the deal variables, which will be required to configure subscription cancellation, and stripe_customer_id, which can later be used to check the subscription status.

circle-exclamation

Returning to regular payments settings

To return to regular payments, assign the subscription variable an empty string stripe_subscription = ". In this case, the interval and interval_count variables will not affect the creation of the link.

Cancelling subscription settings

To cancel a subscription in the calculator, use the stripe_remove_subscription(stripe_subscription_id) method, where stripe_subscription_id is the identifier that was saved in the deal information after payment.

This will allow you to keep your paid subscription active until the end of the current paid period, but further charges won't happen, and the subscription will be canceled after the expiration date:

answer = stripe_remove_subscription('#{stripe_subscription_id}')

stripe_remove_subscription - On success, you will receive a response with information about the date on which the cancelled subscription remains valid.

In this example, the result of the function execution will be placed in the answer variable and it will be possible to check the result of the execution.

Checking the subscription status

stripe_check_subscription(subscription_id, customer_id), where

stripe_subscription_id - subscription ID stripe_customer_id - client ID in Stripe (optional parameter)

How to create a coupon and get a discount ID

To receive the discount ID, create a coupon in your personal account in the ”coupons” section. ссылка ”couponsarrow-up-right”.

After clicking the “New” button, a page opens where you need to specify:

  1. Name — discount name;

  2. ID — identifier that is generated automatically.

  3. Type — type of discount: percentage or fixed amount

  4. Duration — The duration of the discount (one-time or recurring, for example, for subscriptions) and other parameters.

The discount coupon will appear in the “Product catalog“ in the “Coupons” section, and you can view the discount ID by going to the coupon menu:

Click on the coupon to copy the coupon ID:

How to add a discount to order

  1. When generating a payment link (for both subscriptions and one-time payments).

In the block’s calculator, before declaring the payment_sum variable, set the coupon_id variable by assigning it the discount ID from Stripe personal account.

  1. To add to an existing subscription using the stripe_add_subscription_discount function.

Set the conditions for triggering the block and call the specified function in the calculator, giving the parameters stripe_subscription_id (subscription id) and coupon_id (discount coupon id) to it. The discount will be applied for subsequent subscription payments.

chevron-rightПример кода для копированияhashtag

stripe_subscription = 'Подписка премиум' interval = 'month' payment_description = 'Тестовая оплата в Страйп' currency = 'USD' coupon_id = 'ID вашего купона' stripe_add_subscription_discount(stripe_subscription_id, coupon_id) stripe_tax_id = 'ID налога' payment_sum = 90

Upon successful addition, the function returns a message indicating the subscription ID, type, amount, or percentage of the discount and also its expiration date.

circle-info

For more information about creating a subscription, see the section "How to set up recurring payments" ссылка "Как настроить рекуррентные платежи"

How to delete/change the subscription discount

The discount attached to the subscription can be deleted or replaced with another discount.

If you want to terminate the discount, set a condition for the block to be triggered and call the stripe_remove_subscription_discount function in the calculator, giving the stripe_subscrition_id parameter (subscription id) to it.

Upon successful completion of the operation, the function returns a message containing the subscription ID and the date of cancellation of the discount.

The discount replacing, as well as adding a new one is made by using stripe_add_subscription_discount function. Don't forget to pass the stripe_subscription_id and coupon_id parameters to it. A successful request will update the coupon attached to the subscription and return a message with current information.

circle-info

You can read how to get a discount ID in the section "How to create a coupon and get a discount ID". ссылка "Как создать купон и получить ID скидки".

How to process the result

After a successful payment, callbacks will be sent to the bot, which will let you know that the payment was successful. You see these callbacks in the system as messages from the user, so that the user cannot send them, they consist of the first 20 characters of the secret key and the success postscript, for example: sk_live_d35gky6d8ers_success

These callbacks are NOT VISIBLE TO the user, they are displayed only to the operator.

The type of comparison should be "Exact Match"

Also, after successful payment, the stripe_payment_completed variable is set to True.

For example, you can process a successful payment in a conditional block and display the corresponding message to the user:

After the payment is completed, the stripe_callback_data variable will be added to the client, containing the data of the payment system's response to the completed transaction. You can extract the necessary data from the resulting dictionary using the get method.

circle-exclamation

How to test payments

To test the integration, you can use the secret key from the test environment. To do this, switch to test mode in Stripe personal account using the toggle in the right menu

Next, perform the configuration described at the beginning of this guide. Enter the test secret key and add the webhook address to the testing environment.

The test card number

4242 4242 4242 4242 any date in the future CVC - any three numbers

If something doesn't work, compare the data with the data on the official website. ссылка на официальном сайте.arrow-up-right

Last updated