You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Shopify Rails应用中设置免费试用功能

在Shopify Rails应用中配置免费试用功能

问题背景

我正在使用官方Shopify Rails应用gem开发应用,现有计费配置如下:

config.billing = ShopifyApp::BillingConfiguration.new(
  charge_name: "Apps",
  amount: 6.99,
  interval: ShopifyApp::BillingConfiguration::INTERVAL_EVERY_30_DAYS,
  currency_code: "USD" # 目前仅支持USD
)

想添加免费试用选项,但发现gem的内置配置没有相关API支持,该如何实现?

实现方案

由于当前版本的Shopify Rails gem未直接提供免费试用的配置项,需要通过手动调用Shopify GraphQL API来创建带免费试用的订阅,具体步骤如下:

1. 自定义订阅创建逻辑

在应用的计费控制器中(比如BillingController),替换gem默认的计费生成逻辑,通过GraphQL API创建包含免费试用参数的订阅:

def create_subscription
  client = ShopifyAPI::GraphQL.client

  # 构建GraphQL mutation
  create_subscription_mutation = <<~GRAPHQL
    mutation CreateSubscription($name: String!, $price: MoneyInput!, $interval: BillingInterval!, $trialDays: Int!, $returnUrl: String!) {
      appSubscriptionCreate(
        name: $name
        returnUrl: $returnUrl
        test: #{Rails.env.development?}
        lineItems: [
          {
            plan: {
              appRecurringPricingDetails: {
                price: $price
                interval: $interval
                trialDays: $trialDays
              }
            }
          }
        ]
      ) {
        userErrors {
          field
          message
        }
        confirmationUrl
      }
    }
  GRAPHQL

  # 设置变量,这里指定14天免费试用
  variables = {
    name: "Apps",
    price: { amount: "6.99", currencyCode: "USD" },
    interval: "EVERY_30_DAYS",
    trialDays: 14,
    returnUrl: billing_success_url # 替换为你的订阅成功回调地址
  }

  # 发送请求并处理结果
  result = client.query(create_subscription_mutation, variables: variables)
  if result.data.app_subscription_create.user_errors.empty?
    redirect_to result.data.app_subscription_create.confirmation_url
  else
    # 处理错误,比如返回错误提示
    flash[:error] = result.data.app_subscription_create.user_errors.map(&:message).join(", ")
    redirect_to root_path
  end
end

2. 替换gem的自动计费校验

如果你之前使用了gem的ensure_billing回调来强制商家订阅,需要自定义这个校验逻辑:

  • 检查商家是否已有包含免费试用的有效订阅
  • 如果没有,引导到你自定义的订阅创建页面(即上面的create_subscription动作)

3. 处理订阅回调与状态跟踪

当商家完成订阅后,Shopify会发送app_subscription_created和app_subscription_updated webhook到你的应用,你需要:

  • 配置webhook接收这些事件
  • 在webhook处理逻辑中记录订阅的试用到期时间、状态等信息,用于后续的权限校验或到期提醒

内容的提问来源于stack exchange,提问作者Hakeem Baba

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 23:10:22