---
title: "通过 Unity SDK 中的付费墙启用购买功能"
description: "了解如何在 Unity 应用中使用 Adapty SDK 展示付费墙。"
---

要启用应用内购买，您需要了解三个关键概念：

- [**产品**](product) – 用户可以购买的任何内容（订阅、消耗型商品、永久授权）
- [**付费墙**](paywalls) 是定义要提供哪些产品的配置。在 Adapty 中，付费墙是检索产品的唯一方式，但这种设计让您无需修改应用代码即可更改产品组合、定价和优惠内容。
- [**版位**](placements) – 在应用中展示付费墙的位置和时机（如 `main`、`onboarding`、`settings`）。您在看板中为版位配置付费墙，然后在代码中通过版位 ID 请求它们。这使得运行 A/B 测试以及向不同用户展示不同付费墙变得更加简单。

Adapty 为您提供三种在应用中启用购买功能的方式。请根据应用需求选择其中一种：

| 实现方式 | 复杂度 | 适用场景 |
|---|---|---|
| Adapty 付费墙编辑工具 | ✅ 简单 | 您[在无代码编辑工具中创建完整的、可立即购买的付费墙](quickstart-paywalls)。Adapty 自动渲染付费墙，并在后台处理所有复杂的购买流程、收据验证和订阅管理。 |
| 手动创建的付费墙 | 🟡 中等 | 您在应用代码中实现付费墙 UI，但仍从 Adapty 获取付费墙对象以保持产品组合的灵活性。请参阅[指南](unity-quickstart-manual)。 |
| 观察者模式 | 🔴 困难 | 您已有自己的购买处理基础设施并希望继续使用。请注意，观察者模式在 Adapty 中有一定限制。请参阅[文章](observer-vs-full-mode)。 |

:::important
**以下步骤展示如何实现在 Adapty 付费墙编辑工具中创建的付费墙。**

如果您不想使用付费墙编辑工具，请参阅[处理手动创建付费墙中购买的指南](unity-making-purchases)。
:::

要展示在 Adapty 付费墙编辑工具中创建的付费墙，在应用代码中您只需：

1. **获取付费墙**：从 Adapty 获取付费墙。
2. **展示付费墙，Adapty 将为您处理购买流程**：在应用中显示您获取到的付费墙容器。
3. **处理按钮操作**：将用户与付费墙的交互与应用的响应关联起来。例如，当用户点击按钮时打开链接或关闭付费墙。

## 开始之前 \{#before-you-start\}

在开始之前，请完成以下步骤：

1. 在 Adapty 看板中将您的应用连接到 [App Store](initial_ios) 和/或 [Google Play](initial-android)。
2. 在 Adapty 中[创建产品](create-product)。
3. [创建付费墙并向其添加产品](create-paywall)。
4. [创建版位并将付费墙添加到其中](create-placement)。
5. 在应用代码中[安装并激活 Adapty SDK](sdk-installation-unity)。

:::tip
完成这些步骤最快的方式是按照[快速入门指南](quickstart)操作，或使用 [Developer CLI](developer-cli-quickstart) 创建付费墙和版位。
:::

## 1. 获取付费墙 \{#1-get-the-paywall\}

您的付费墙与在看板中配置的版位关联。版位允许您为不同目标受众运行不同的付费墙，或运行 [A/B 测试](ab-tests)。

要获取在 Adapty 付费墙编辑工具中创建的付费墙，您需要：

1. 使用 `GetPaywall` 方法通过[版位](placements) ID 获取 `paywall` 对象，并使用 `HasViewConfiguration` 属性检查它是否是在编辑工具中创建的付费墙。

2. 使用 `CreatePaywallView` 方法创建付费墙视图。该视图包含展示付费墙所需的 UI 元素和样式。

:::important
要获取视图配置，您必须在付费墙编辑工具中开启 **Show on device** 开关。否则，您将获得空的视图配置，付费墙将无法显示。
:::

```csharp showLineNumbers
Adapty.GetPaywall("YOUR_PLACEMENT_ID", (paywall, error) => {
    if(error != null) {
        // handle the error
        return;
    }
    
    // Create paywall view parameters
    var parameters = new AdaptyUICreatePaywallViewParameters();
    
    // Create the paywall view
    AdaptyUI.CreatePaywallView(paywall, parameters, (view, error) => {
        if(error != null) {
            // handle the error
            return;
        }
        
        // view - the paywall view ready to be presented
    });
});
```

:::info
本快速入门提供展示付费墙所需的最低配置。有关高级配置详情，请参阅我们的[获取付费墙指南](unity-get-pb-paywalls)。
:::

## 2. 展示付费墙 \{#2-display-the-paywall\}

现在，当您已获得付费墙配置后，只需添加几行代码即可展示付费墙。

要展示付费墙，请对由 `CreatePaywallView` 方法创建的 `view` 调用 `view.Present()` 方法。每个 `view` 只能使用一次。如果需要再次展示付费墙，请再次调用 `CreatePaywallView` 创建新的 `view` 实例。

```csharp showLineNumbers title="Unity"
view.Present((error) => {
  // handle the error
});
```

:::info
有关如何展示付费墙的更多详情，请参阅我们的[指南](unity-present-paywalls)。
:::

## 3. 处理按钮操作 \{#3-handle-button-actions\}

当用户点击付费墙中的按钮时，Unity SDK 会自动处理购买和恢复操作。但是，其他按钮具有自定义或预定义的 ID，需要在您的代码中处理相应操作。

例如，您的付费墙可能有一个关闭按钮和需要打开的 URL（如使用条款和隐私政策）。要处理这些操作，您的类需要实现 `AdaptyPaywallsEventsListener` 接口并注册为监听器。

:::tip
请阅读我们关于如何处理按钮[操作](unity-handle-paywall-actions)和[事件](unity-handling-events)的指南。
:::

```csharp showLineNumbers title="Unity"
public class YourClass : MonoBehaviour, AdaptyPaywallsEventsListener
{
    void Start()
    {
        // Register this class as the paywall events listener
        Adapty.SetPaywallsEventsListener(this);
    }

    // AdaptyPaywallsEventsListener method - handles button actions
    public void PaywallViewDidPerformAction(
        AdaptyUIPaywallView view,
        AdaptyUIUserAction action
    ) {
        switch (action.Type) {
            case AdaptyUIUserActionType.Close:
                view.Dismiss(null);
                break;
            case AdaptyUIUserActionType.OpenUrl:
                Application.OpenURL(action.Value);
                break;
            default:
                break;
        }
    }
}
```

## 后续步骤 \{#next-steps\}

:::tip
有疑问或遇到问题？欢迎访问我们的[支持论坛](https://adapty.featurebase.app/)，在那里你可以找到常见问题的解答，也可以提出自己的问题。我们的团队和社区随时为你提供帮助！
:::

您的付费墙已准备好在应用中展示。在 [App Store 沙盒](test-purchases-in-sandbox)或 [Google Play Store](testing-on-android) 中测试您的购买，以确保可以从付费墙完成测试购买。

接下来，您需要[检查用户的访问等级](unity-check-subscription-status)，以确保向正确的用户展示付费墙或授予付费功能的访问权限。

## 完整示例 \{#full-example\}

以下是如何将所有步骤整合到您的应用中的完整示例。

```csharp showLineNumbers
using System;
using UnityEngine;
using AdaptySDK;

public class PaywallManager : MonoBehaviour, AdaptyPaywallsEventsListener
{
    [SerializeField] private string placementId = "YOUR_PLACEMENT_ID";
    
    private AdaptyUIPaywallView currentPaywallView;
    
    void Start()
    {
        // Register for paywall events
        Adapty.SetPaywallsEventsListener(this);
        GetAndDisplayPaywall();
    }
    
    private void GetAndDisplayPaywall()
    {
        Adapty.GetPaywall(placementId, (paywall, error) => {
            if (error != null) {
                Debug.LogError("Error getting paywall: " + error.Message);
                return;
            }
            
            if (paywall.HasViewConfiguration) {
                CreateAndPresentPaywallView(paywall);
            } else {
                Debug.LogWarning("Paywall was not created using the builder");
            }
        });
    }
    
    private void CreateAndPresentPaywallView(AdaptyPaywall paywall)
    {
        var parameters = new AdaptyUICreatePaywallViewParameters();
        
        AdaptyUI.CreatePaywallView(paywall, parameters, (view, error) => {
            if (error != null) {
                Debug.LogError("Error creating paywall view: " + error.Message);
                return;
            }
            
            currentPaywallView = view;
            
            view.Present((presentError) => {
                if (presentError != null) {
                    Debug.LogError("Error presenting paywall: " + presentError.Message);
                    return;
                }
                
                Debug.Log("Paywall presented successfully");
            });
        });
    }
    
    // AdaptyPaywallsEventsListener implementation
    public void PaywallViewDidPerformAction(
        AdaptyUIPaywallView view, 
        AdaptyUIUserAction action
    ) {
        switch (action.Type) {
            case AdaptyUIUserActionType.Close:
                Debug.Log("Close button pressed");
                view.Dismiss(null);
                break;
            case AdaptyUIUserActionType.OpenUrl:
                Application.OpenURL(action.Value);
                break;
            default:
                break;
        }
    }
    
    // Required interface methods (implement as needed)
    public void PaywallViewDidAppear(AdaptyUIPaywallView view) { }
    public void PaywallViewDidDisappear(AdaptyUIPaywallView view) { }
    public void PaywallViewDidSelectProduct(AdaptyUIPaywallView view, string productId) { }
    public void PaywallViewDidStartPurchase(AdaptyUIPaywallView view, AdaptyPaywallProduct product) { }
    public void PaywallViewDidFinishPurchase(AdaptyUIPaywallView view, AdaptyPaywallProduct product, AdaptyPurchaseResult purchasedResult) { }
    public void PaywallViewDidFailPurchase(AdaptyUIPaywallView view, AdaptyPaywallProduct product, AdaptyError error) { }
    public void PaywallViewDidStartRestore(AdaptyUIPaywallView view) { }
    public void PaywallViewDidFinishRestore(AdaptyUIPaywallView view, AdaptyProfile profile) { }
    public void PaywallViewDidFailRestore(AdaptyUIPaywallView view, AdaptyError error) { }
    public void PaywallViewDidFailRendering(AdaptyUIPaywallView view, AdaptyError error) { }
    public void PaywallViewDidFailLoadingProducts(AdaptyUIPaywallView view, AdaptyError error) { }
    public void PaywallViewDidFinishWebPaymentNavigation(AdaptyUIPaywallView view, AdaptyPaywallProduct product, AdaptyError error) { }
    
    public void ShowPaywall()
    {
        GetAndDisplayPaywall();
    }
    
    void OnDestroy()
    {
        if (currentPaywallView != null) {
            currentPaywallView.Dismiss(null);
        }
    }
}
```