Плагин подписок Discourse

:discourse2: Summary The Discourse Subscriptions plugin allows site owners to sell recurring and one-time purchase subscriptions that grant access to a group on a Discourse instance.
:open_book: Install Guide This plugin is bundled with Discourse core. There is no need to install the plugin separately.

The Discourse Subscriptions plugin allows you to create one-time as well as recurring subscriptions that users can pay for in order to access gated content. This can be a great way to fund the hosting cost of your community.

Features

The Discourse Subscriptions plugin supports the following features:

The “Subscribe” button located in the top nav will take you to the Subscribe page /s where it lists the subscriptions you have configured for your site:

Once a user clicks on one of the “Subscribe” button for a specific plan it will open up the payment page for that plan:

After a user fills out their payment details and their address and click “Subscribe”, they are shown a “Thank you!” message and taken to their billing page:

The user is also automatically added to a group of your choosing so that you can easily see which users have subscribed as well as provide gated content in categories only that group can see.

Terms

  • Subscription - Subscriptions are a recurring payment plan which allow you to control access to content on your community. When a subscription is created or deleted, a user is added or removed from the user group you associate with your subscription plan. A subscription is made up of a product and plans.
  • Product - A product in Stripe’s terms is what you’re selling. A product can contain one or more plans.
    • To add a description to your product, add a metadata field named “description” and use that one instead. You can use Markdown.
  • Plan - A plan contains a price, recurring cycle, and associates with a group to which your subscribers gain access.

:police_car_light: Be very careful to keep your Stripe private keys safe and secure at all times.

:warning: If you were to shut down your instance of Discourse, uninstall this plugin or your site were to go offline, Stripe will continue to bill your customers for your service until the subscription is cancelled.

Configuration

  1. Install & enable the plugin
  2. Configure Payment Gateway (Stripe)
  3. Configure Webhooks & Events in Stripe
  4. Add your Stripe keys (public, secret, webhook secret) under Admin > Plugins > Installed > Subscriptions > Settings /admin/site_settings/category/discourse_subscriptions?filter=plugin%3Adiscourse-subscriptions.
  5. Create a group for your subscribers to join via purchase
  6. Create a product and plan under Admin > Plugins > Subscriptions
  7. Profit!

Set up your Payment Gateway.

Firstly, you’ll need an account with the Stripe payment gateway. To get started, you can set up an account in test mode and see how it all works without making any real transactions or having to set up a bank account. There is no test mode toggle in the plugin; instead, be sure to use your developer keys (they begin with pk_test, sk_test)

Set up Webhooks and Events in your Stripe account

:bomb: Webhooks are required to make subscription cancellations work fully. Be sure you have them configured correctly.

Once you have an account on Stripe, you’ll need to tell Stripe your website’s address so it can notify you about certain transactions. You can enter this in your Stripe dashboard under Endpoints > URL.

Webhooks address: [your server address]/s/hooks – where [your server address] is the URL of your Discourse install.

You’ll also need to tell Stripe which events it should notify you about via the webhook URL.

Currently, Discourse Subscriptions responds to the following events:

  • customer.subscription.deleted
  • customer.subscription.updated
  • checkout.session.completed

Add the Stripe API and Webhook keys to your plugin settings

Stripe needs to be authorized to communicate with your website. To do this, it publishes a pair of private and public API keys and a signing secret for your web hooks.

To authorize webhooks, add the API keys and webhook secret from Stripe to your settings page (under Developers).

:warning: Adding production keys will make live payments. If you plan to test, be sure to switch to View test data mode and get pk_test and sk_test keys under Developers.

In your Stripe account settings, see:

Add these keys under the appropriate settings in Admin > Plugins > Installed > Subscriptions > Settings /admin/site_settings/category/discourse_subscriptions?filter=plugin%3Adiscourse-subscriptions.

Set up your User Groups in Discourse

When a user successfully subscribes to your Discourse application, after their credit card transaction has been processed, they are added to a User Group. By assigning users to a User Group, you can manage what your users have access to on your website. User groups are a core functionality of Discourse and this plugin does nothing with them except add and remove users from the group you associated with your Plan.

Create one or more products with plans.

Under Admin > Plugins > Subscriptions, click add a new Product. Once you have a product saved, you can add plans to it. Keep in mind that the pricing and billing intervals of plans cannot be changed once you create them. This is to avoid confusion around subscription management.

If you take a look at your Stripe Dashboard, you’ll see all those products and plans are listed. Discourse Subscriptions does not create them locally. They are created in Stripe.

Testing

Test with these credit card numbers:

  • 4242 4242 4242 4242
  • 4111 1111 1111 1111 (no authentication required)
  • 4000 0027 6000 3184 (authentication required)

For more test card numbers: Test card numbers | Stripe Documentation

Visit /s and enter a few test transactions.

Going Live

Once you’re ready to go live, change your API and webhook secret keys to production keys. You will need to create new products and plans in live mode.

Do be aware that if if you don’t properly configure Stripe webhooks, and recurring payments fail to process for any reason (expired credit card, etc.), users will still have access to the group . To have Stripe automatically cancel subscriptions, be sure to set your Manage failed payments settings similar to the below image and configure webhooks as described above.

Update Payment Info

Users can update their card used for individual subscriptions by visiting the billing page and clicking the edit button next to the subscription which will open up this screen:

Stripe Checkout with Stripe Pricing Tables

You can also opt to replace the Subscription Plugin product and checkout pages and instead use Stripe Checkout with Stripe Pricing Tables.

In your Stripe Dashboard:

  1. After you’ve created the products on Discourse, Go to Products > Product catalog
  2. Click on the product you’d like to include in the pricing table
  3. Click Edit product
  4. More Options and enter the following under Metadata:
    • Key: group_name
    • Value: The group’s name on Discourse (e.g., trust_level_0)
  5. Click Update product to save

:red_exclamation_mark: Make sure the group name matches the group that is selected under User_Groups on Discourse

Create your Stripe pricing table

  1. Go to Products > Pricing tables
  2. Create a new table and add the products you just created
  3. After publishing the table, copy the pricing table ID found within the embed code (it starts with prctbl_...)
  4. Paste the pricing table ID into your discourse_subscriptions_pricing_table_id and enable the subscriptions pricing table setting.
  5. Click the green checkmarks to save both settings.

Recommended step:

When setting up the Pricing Table inside of Stripe it is recommended to link the user to your site after checkout is complete otherwise they will stay on a Stripe confirmation page without a link back to your site.

Redirecting to https://<your-site>/my/billing/subscriptions is a good choice for subscriptions. For one-off payments you could link directly to https://<your-site>/my/billing/payments.

Automatic Tax Collecting

To enable Automatic Tax Collecting check the Site Setting box for discourse_subscriptions_enable_automatic_tax.

If you enable it, but you have not configured your Stripe instance properly to collect tax users may see this popup after completing the checkout process:

There is this guide for more info, but there shouldn’t be much to do since the plugin is now passing in the appropriate automatic_tax[enabled]=true parameter (step 5).

Be sure you configure your registrations (step 4) as well:

Here is an example Discourse Subscription Plugin transaction in Stripe showing that tax was automatically collected:

Settings

Name Description
discourse subscriptions enabled Enable the Discourse Subscriptions plugin.
discourse subscriptions extra nav subscribe Show the subscribe button in the primary navigation
discourse subscriptions public key Stripe Publishable Key
discourse subscriptions secret key Stripe Secret Key
discourse subscriptions webhook secret Stripe Webhook Secret
discourse subscriptions currency Default Currency Code. This can be overridden when creating a subscription plan.
discourse subscriptions campaign enabled Enables a campaign banner to promote supporting this community financially.
discourse subscriptions campaign goal The numerical goal for your support campaign (subscribers or amount raised).
discourse subscriptions campaign type Selects the type of campaign to run (subscribers or monthly amount raised).
discourse subscriptions campaign banner location Selects the location of the campaign banner (top or sidebar).
discourse subscriptions campaign banner bg image Upload a custom image to use as the background on the campaign banner.
discourse subscriptions campaign banner shadow color Selects the color of the campaign banner drop shadow.
discourse subscriptions campaign show contributors Show avatars of the most recent purchases of subscription products.
discourse subscriptions campaign product The Stripe product id to send supporters when they click the button on the campaign. If this setting is blank, supporters will be directed to the main products page.
discourse subscriptions campaign grant Grants the user a free month of subscriptions
discourse subscriptions pricing table id The Stripe pricing table id from the embed code
discourse subscriptions pricing table enabled Enables using the Stripe pricing table and replaces the existing subscribe page
discourse_subscriptions_enable_automatic_tax Toggles if sales tax is going to be collected. Requires some setup in Stripe.
discourse_subscriptions_enable_verbose_logging Enables more verbose logging to aid in debugging. Please do not leave permanently enabled in production.

:discourse2: Hosted by us? This plugin is available on our Pro, Business, and Enterprise hosting plans Subscriptions | Discourse - Civilized Discussion

139 лайков
Steady plugin for community funding
ProCourse Memberships :money_with_wings:
Group membership subscriptions with profit split
Email drip campaign
Discourse Category Lockdown
How to give unpaid users limited access without making Discourse private?
Discourse for Membership Association Members?
Please suggest a good Discourse Plugin for Membership that supports Indian Payment Gateway
Super simple Discourse-Wordpress-membership integration
Allow users to donate to pay hosting fees for a site
Login required after some days of free access
User can't repurchase a subscription product after canceling
Add user to group after purchase
User Card Directory
Multiple paywalls with common communication hub
How to move Topics in Category into their own Pinned Topic inside new Categories?
Subscription Access To Discourse
Discourse Subscriptions + btcpayserver
Any good Memberpress alternatives for wordpress?
Send an invite to a user but complete their profile programmatically
Discourse subscriptions - changing price during recurring subscription
Do I need Wordpress? Or Discourse can be my solution to ALL?
Discourse Subscriptions - user not removed from group when subscription cancelled
Discourse Subscriptions - user not removed from group when subscription cancelled
Discourse vs Skool
Subscription Access To Discourse
Tax implication of funding a forum
Tick badge for username?
Subscription update problem
Setting up a subscription group
Charging a membership fee
Discourse Subscriptions with Thrive Cart
Admin creating subscription for user
Plugin for charity donations?
Allow subscription of predetermined length
Link Sign Up to Subscriptions Plugin
User monetization with group access?
Allow option to open Stripe payment website
Embed a list of Discourse topics onto an external site
Is it possible to use the subscription plugin to limit creating topics in a category to subscribers?
Best approach to a landing page/payment front end
Managing consumable AI costs
Allow multiple ‘new topic’ drafts
Stripe iframe causes a blank page on my print layout
No 'deleted' event in Stripe?
Tell us how you manage subscriptions on Discourse
Addding a paid group who can reply to topics but not create them
Integration with WP membership Pro
Hosting questions
Alternative sign up pathways
Control Category Visibility and Access by User Levels
Tighter integration of account-creation and subscriptions?
Blank page when resuming discourse app
Does the Subscriptions plugin work with "one-off" payment pricing tables?
Subscriber group automation (Remove and Add users to specific group with subscription)
"Support Us" Banner Not Updating
Tip or Pay Button - for user post/content, does it exist already?
May I or can I monetize my forum?
May I or can I monetize my forum?
Bundling more popular plugins with Discourse core
Guest Gate Theme Component
Error loading route Caused by plugin 'discourse-subscriptions'
Why doesn't Discourse hosting include the Subscriptions plugin on the Starter plan?
How would I install a cryptocurrency paywall?
Rebuild fails when these plugins are present
Changing excerpt length
Installing discourse for free?
Options to manage payments for paid Discourse communities
Using a plug-in to monetize my Discourse
ProCourse Memberships :money_with_wings:
UX: Add metadata to subscription page to improve SEO and link UI design
A feature request related to this plugin. Pointed questions or rewarded questions
Plugin to use Discourse for classified ads or as a job board?
Subscription Plugin not working (Error)
How to set message limits for user groups?
API POST for New User
ProCourse Memberships :money_with_wings:
Steady plugin for community funding
New customer setup
Discourse Category Lockdown
Making group joins automatic to an external pricing plan
Platform integration - videos
Any way to accept paypal or stripe payment at signup?
Looking for feedback on Discourse Subscriptons
WooCommerce Discourse Website newbie help
Switching to Discourse Subscriptions from WordPress Subscriptions
Integration with Wix.com membership to only let the paid member can access to Discourse
2020: The Year in Review
Managing Subscriptions through Wordpress (Ultimate Member + Paid Memberships Pro)
Discourse Unlock
How does uninstalling the Subscriptions plugin affect Stripe billing?
Memberful opinions?
Is there an E-commerce plugin for Discourse?
Memberful opinions?
Prefill custom html with user's email address?
Can't make the subscription plugin work
How to charge members for my Discourse website?
New site landing-page + discourse integration and marketing
Pay or Play usage?
Latest topics on homepage with only members to read in detail?
Banner text customization for Subscriptions plugin
Subscriptions: Change User's Plan
Donation Bar for House Ad
Can I use the Subscriptions plugin on my own server?
Limiting Subscription Length
Discourse Subscriptions - use API to find out product, plan and renewal date

5 сообщений были перенесены в новую тему: Ошибка «Похожий объект существует в тестовом режиме»

Настройка Sidebar кажется не имеющей эффекта (последняя версия Discourse aeb3d717dc, последний плагин cc43d32a).

1 лайк

Я тоже получаю это сообщение в логе:

Уведомление об устаревании: имя иконки "donate" было изменено на "circle-dollar-to-slot". Пожалуйста, используйте новое имя в вашем коде. Старые имена будут удалены во втором квартале 2025 года. [id устаревания: discourse.fontawesome-6-upgrade] [инфо: https://meta.discourse.org/t/325349]

РЕДАКТИРОВАНИЕ: Создал PR по этому вопросу

3 лайка

2 сообщения были объединены с существующей темой: “Поддержите нас” Баннер не обновляется

Хм… у меня локально оно появляется в боковой панели, когда я переключаю режим.

Если у вас включена боковая панель, мы добавляем этот CSS-класс. Вы можете проверить страницу и поискать subscription-campain-sidebar.

У вас оно просто остаётся вверху?

Теперь я понял. У меня по умолчанию была установлена страница Категорий. Там, очевидно, это не отображается. А в списке «Последние» — да. Так что всё работает отлично. Спасибо!

3 лайка

Это действительно должно отображаться на странице «Категории» (или других страницах по умолчанию), не так ли?

1 лайк

Из-за ограничений в материковом Китае Stripe испытывает трудности с прохождением проверки. Не могли бы вы рассмотреть возможность интеграции интерфейсов Alipay или WeChat Pay?

2 лайка

В прошлом на подобные вопросы отвечали так: «Правильным решением будет создание плагина для Alipay или WeChat Pay». discourse.org зарабатывает на тех, кто платит за хостинг, и, думаю, у них не так много корпоративных клиентов, которым нужны Alipay или WeChat Pay, поэтому вам стоит задать вопрос в канале Marketplace или разработать решение самостоятельно. Возможно, вы сможете заинтересовать Alipay или WeChat Pay финансированием разработки.

3 лайка

Я выполнил шаги с 1 по 5, но, видимо, я тупой или слепой. Не могу найти интерфейс для настройки продуктов и тарифных планов на моём сервере.

Ах, ладно… Нашёл. Последний кусок головоломки — я не понимаю этого:

  • Чтобы добавить описание к вашему продукту, добавьте поле метаданных с именем «description» и используйте его. Вы можете использовать Markdown.

Я считаю, что всё настроено правильно. Если я проверяю настройку:
Кнопка «Подписаться» будет показывать встроенную таблицу цен, и будет использоваться Stripe Checkout.
Тогда покупки работают корректно, однако, если я снимаю эту галочку и использую встроенный интерфейс, я получаю сообщения об ошибках, такие как:

Ожидалось наличие способа оплаты типа «card», но у этого PaymentIntent нет способа оплаты, и он не был предоставлен. Попробуйте снова, указав либо параметр payment_method, либо payment_method_data.

или

У этого клиента нет привязанного источника оплаты или способа оплаты по умолчанию. Пожалуйста, рассмотрите возможность добавления способа оплаты по умолчанию. Для получения дополнительной информации посетите https://stripe.com/docs/billing/subscriptions/payment-methods-setting#payment-method-priority.

Верхняя ошибка относится к плану без периодических платежей, нижняя — к плану с периодическими платежами.
Есть какие-либо идеи, как это исправить? Мне больше нравится встроенный интерфейс.

Я разобрался в этом. Похоже, что когда я экспериментировал с пользователями в тестовой среде, Stripe не принял использование одного и того же пользователя Discourse с разными «пользователями подписки».

Кроме того, автор оригинального поста должен уточнить, что

Чтобы добавить описание к вашему продукту, добавьте поле метаданных с именем «description» и используйте его. Вы можете использовать Markdown.

Перейдите в панель управления Stripe, нажмите на «Каталог продуктов», выберите продукт, затем нажмите на цену. Именно здесь вы найдете поля метаданных, к которым можно добавить описание.

Однако, это, похоже, не сработало для меня. Я добавил тестовое описание, но ничего не изменилось — ни при использовании таблицы Stripe, ни при использовании встроенного макета.

6 сообщений были объединены в существующую тему: Добавить разные способы оплаты к подписке Discourse

Пост был объединен с существующей темой: Добавить различные способы оплаты к подписке Discourse

При попытке создать товар я получаю ошибку «500». Я настраиваю это в тестовой среде. Что можно проверить, чтобы выяснить причину ошибки сервера?

Аналогичная проблема возникает с купонами.

Создан ли в то же время какой-либо запись в {YOURFORUM}/logs?

2 лайка

Ого, я даже не знал, что такая страница существует. Выдает ошибку «неверный ключ API». Я пока ввел какой-то мусор в поле секретного ключа, чтобы перейти дальше и настроить пакеты подписки, а к ключам вернусь позже, когда буду готов к тестированию.

1 лайк

Мне удалось успешно настроить плагин, но затем я понял, что он поддерживает только повторяющиеся подписки, а не разовые, которые истекают по истечении заданного периода.

Например, списывать сумму X за 30 дней. По прошествии 30 дней пользователь удаляется из премиум-группы. При желании он может купить подписку снова. Обычно я предлагаю членства сроком на 1, 3 или 12 месяцев.

Stripe требует регистрации в качестве юридического лица для поддержки повторяющихся платежей. Я принимаю разовые платежи на XenForo, где встроенная функция XenForo автоматически обрабатывает истечение подписки и удаление пользователя из группы.

Это полностью разрушает мои планы по переходу на Discourse в течение месяца. :cry:

У меня есть решение. Я могу помочь вам создать GitHub Action, которая будет извлекать данные из Data Explorer, включая имя пользователя и идентификатор группы, из которой нужно удалить пользователя, а затем изменять его группу соответствующим образом.

Я делаю это для клиента, который переходит на Discourse и имеет пользовательское поле с датами. Нам нужно перемещать пользователей в группу «исчезает скоро», чтобы показать им баннер, а затем перемещать их в другую группу, чтобы удалить из платной группы, когда время истечет.

Если у вас есть бюджет, вы можете связаться со мной или задать вопрос в Marketplace. Я планирую написать статью об этом с общим примером, если когда-нибудь найду время.

6 лайков

Здравствуйте, подписки работают корректно до момента получения обратного вызова от Stripe. Я использую таблицу цен Stripe.

Я вижу, что подписка успешно зарегистрирована на странице admin/plugins/discourse-subscriptions/subscriptions.

Однако пользователь не был добавлен в требуемую группу.

Я настроил продукт с точно таким же названием, как в Stripe, и также создал тарифный план с выбранной группой. Цену в тарифном плане я установил равной нулю, предполагая, что для конфигурации таблицы цен Stripe это не имеет значения.

Что я упускаю?