0
0

RevenueCat SDKを使ったPurchase Managerの作成とPaywallへの実装

Last updated at Posted at 2024-09-19
  1. RevenueCatのセットアップ
    RevenueCatを使用するためには、まずプロジェクトにSDKを導入する必要があります。iOSの場合、CocoaPodsを使ってSDKをインストールするのが一般的です。
pod 'RevenueCat'

Podfileにこの行を追加し、pod installを実行してSDKをインストールします。これが完了したら、AppDelegateやSceneDelegate内でRevenueCatの初期設定を行います。

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        Purchases.configure(withAPIKey: "YOUR_PUBLIC_API_KEY")
        return true
    }
}

  1. Purchase Managerの作成

次に、Purchase Managerを作成して課金ロジックを管理します。ここではシングルトンクラスとして作成し、アプリ内のどこからでもアクセスできるようにします。

import RevenueCat

class PurchaseManager: ObservableObject {
    static let shared = PurchaseManager()

    @Published var isPremiumUser: Bool = false

    private init() {
        checkSubscriptionStatus()
    }

    func checkSubscriptionStatus() {
        Purchases.shared.getCustomerInfo { (customerInfo, error) in
            if let customerInfo = customerInfo {
                self.isPremiumUser = customerInfo.entitlements["premium"]?.isActive == true
            } else {
                print("Failed to fetch customer info: \(String(describing: error?.localizedDescription))")
            }
        }
    }

    func purchaseProduct(productIdentifier: String) {
        Purchases.shared.getOfferings { (offerings, error) in
            guard let offering = offerings?.current, let package = offering.availablePackages.first else {
                print("No offerings available: \(String(describing: error?.localizedDescription))")
                return
            }

            Purchases.shared.purchase(package: package) { (transaction, customerInfo, error, userCancelled) in
                if let error = error {
                    print("Purchase failed: \(error.localizedDescription)")
                } else if userCancelled {
                    print("User cancelled the purchase.")
                } else if let customerInfo = customerInfo {
                    self.isPremiumUser = customerInfo.entitlements["premium"]?.isActive == true
                }
            }
        }
    }
}

PurchaseManagerでは、以下の2つの主な機能を実装しています:

checkSubscriptionStatus: ユーザーのサブスクリプションステータスを確認し、プレミアムユーザーかどうかを判断します。
purchaseProduct: RevenueCatのofferingsから提供されている商品を取得し、その商品を購入します。

  1. Paywall画面の実装
    次に、作成したPurchaseManagerをPaywallに統合します。Paywallはユーザーが課金機能を利用するための画面で、プレミアムコンテンツの紹介や購入オプションを表示します。
import SwiftUI

struct PaywallView: View {
    @ObservedObject var purchaseManager = PurchaseManager.shared

    var body: some View {
        VStack {
            if purchaseManager.isPremiumUser {
                Text("You are a premium user!")
                    .font(.largeTitle)
                    .padding()

                // プレミアムコンテンツ
                Text("Enjoy all premium features")
            } else {
                Text("Unlock Premium")
                    .font(.largeTitle)
                    .padding()

                Text("Gain access to exclusive content.")
                    .padding()

                Button(action: {
                    purchaseManager.purchaseProduct(productIdentifier: "com.app.premium")
                }) {
                    Text("Unlock Premium for $4.99/month")
                        .bold()
                        .padding()
                        .background(Color.blue)
                        .foregroundColor(.white)
                        .cornerRadius(10)
                }
                .padding()

                Text("Restore Purchases")
                    .foregroundColor(.blue)
                    .onTapGesture {
                        Purchases.shared.restoreTransactions { (customerInfo, error) in
                            if let customerInfo = customerInfo {
                                purchaseManager.isPremiumUser = customerInfo.entitlements["premium"]?.isActive == true
                            }
                        }
                    }
            }
        }
        .padding()
    }
}

このPaywallViewは、以下の機能を持っています:

isPremiumUser: プレミアムユーザーかどうかを表示するラベル。
プレミアムを購入するためのボタン。
購入済みの場合は「Restore Purchases」オプションも追加されています。
4. テストとデバッグ

実際にアプリで動作を確認するためには、AppleのSandbox環境を使用して課金のテストを行います。RevenueCatのサーバーは、自動的にAppleのSandbox環境と統合されており、開発中のテストが簡単に行えます。

まず、Xcodeの「Signing & Capabilities」で「In-App Purchase」機能を有効にします。次に、App Store Connectでテスト用のSandboxユーザーを設定し、そのユーザーでアプリにログインします。

購入フローが正常に動作することを確認できたら、App Storeにアプリを提出し、実際の課金処理を行うことが可能になります。

  1. まとめ

RevenueCatを利用することで、アプリ内課金の実装は従来よりも大幅に簡素化され、サブスクリプションや課金ロジックを簡単に管理できます。今回紹介したPurchaseManagerとPaywallの実装例をベースに、アプリの収益化をスムーズに進めることができます。RevenueCatの優れた点は、さまざまなプラットフォームで一貫した課金管理を提供し、AppleやGoogleの課金システムとの複雑な処理を自動化してくれることです。

これにより、開発者はアプリの機能向上に集中でき、ユーザーにとってはストレスのない課金体験を提供できるでしょう。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0