1. 簡介
如要在 Flutter 應用程式中加入應用程式內購功能,必須設定 Apple App Store 和 Google Play 商店、在可信任的後端驗證購買權杖,以及授予權益,例如消耗性貨幣、一次性升級或週期性訂閱福利。
在本程式碼實驗室中,您將與 Google Antigravity 合作,建構 Dash Clicker,這是一款以 Dash 吉祥物為貨幣的手機點擊遊戲,並搭配 Dart shelf 後端服務和 Cloud Firestore,驗證及追蹤三種應用程式內購:
- 消耗性商品 (
dash_consumable_2k):可重複購買,玩家購買後會立即獲得 2,000 個衝刺道具。 - 非消耗性 (
dash_upgrade_3d):永久性的一次性升級,可將傳統 Dash 吉祥物永久轉換為現代 3D Dash。 - 訂閱 (
dash_subscription_doubler):自動續訂型訂閱項目,可在訂閱期間內,將被動產生的點擊次數乘以特定倍數。
|
|
|
建構項目
- Flutter 行動應用程式 (
app/) 採用material_ui和cupertino_ui樣式,可查詢商店產品、發起購買,並對即時購買串流做出反應。 - Dart
shelf後端伺服器 (dart-backend/),可向 Google Play 和應用程式商店驗證購買收據、輪詢商店帳單事件,以及在 Cloud Firestore 記錄購買狀態。
學習旅程
本程式碼實驗室會逐步引導您建構及連結全端應用程式內購購買流程:
- 設定開發環境:安裝 Flutter 和 Google Antigravity,提示 Antigravity 建構 Dash Clicker 範例專案 (
app/),並設定 iOS 軟體包 ID 和 AndroidapplicationId。 - 安裝外掛程式:提示 Antigravity 將
in_app_purchase和in_app_purchase_platform_interface新增至app/。 - 設定 App Store:註冊應用程式 ID、建立沙箱測試帳戶,並在 App Store Connect 中設定三項產品。
- 設定 Play 商店:在 Google Play 管理中心建立應用程式、提示 Antigravity 在 Gradle 中設定發布 KeyStore 簽署、上傳初始應用程式套件、新增授權測試人員,以及設定產品。
- 設定 Firebase:在 Firebase 控制台中啟用 Google 登入和 Cloud Firestore、執行
flutterfire configure,以及設定 Android SHA-1 指紋和 iOS 網址配置。 - 監聽購買交易更新:提示 Antigravity 新增可測試的
IAPConnection包裝函式、訂閱purchaseStream,並使用TestIAPConnection測試應用程式。 - 購物:提示 Antigravity 將
ProductDetails納入PurchasableProduct中、查詢商店產品、觸發buyConsumable和buyNonConsumable,以及完成購物交易未完成。 - 設定後端:提示 Antigravity 使用
IapRepository建構dart-backend/伺服器,並設定服務帳戶憑證。 - 驗證購買交易:提示 Antigravity 在
PurchasePage上要求 Firebase 登入、將購買權杖發布至/verifypurchase,並導入GooglePlayPurchaseHandler和AppStorePurchaseHandler。 - 追蹤購買交易:提示 Antigravity 在後端輪詢 Google Cloud Pub/Sub 和 App Store Server API,並使用
IAPRepo將授權同步回 Flutter 用戶端。
課程內容
- 如何與 Google Antigravity 協作,反覆建構及自訂全端 Flutter 應用程式內購應用程式和 Dart 後端。
- 如何設定 App Store Connect 和 Google Play 管理中心,提供消耗性、非消耗性和訂閱產品。
- 如何使用
in_app_purchase外掛程式查詢產品、發起購買交易,以及處理購買串流。 - 如何在 Dart 後端驗證 Google Play 和應用程式商店購買權杖,並儲存在 Cloud Firestore。
- 如何處理商店帳單事件,以及跨裝置同步訂閱和升級授權。
必要條件
- 熟悉 Flutter 小工具、Dart 語法和
Provider狀態管理。 - Apple 開發人員帳戶 (用於測試 iOS 上的 App Store 購買交易)、Google Play 開發人員帳戶 (用於測試 Android 上的 Play 商店購買交易),或兩者皆有。
- Firebase 帳戶和 Firebase CLI。
2. 設定開發環境
編輯者
本程式碼實驗室會使用 Google Antigravity 做為 AI 優先開發環境。在每個步驟中,您都會提示 Antigravity 生成或改良 Flutter 用戶端 (app/) 和 Dart 後端 (dart-backend/)、檢查生成的程式碼,並視需要探索變化版本。
安裝 Flutter
如需安裝 Flutter SDK 的最新操作說明,請前往 docs.flutter.dev。
請安裝下列軟體,以便進行本程式碼實驗室:
- Flutter SDK
- Google Antigravity,並啟用官方 Dart 和 Flutter 外掛程式 (可在外掛程式市集的「Build with Google」部分找到)。
- 所選行動目標的編譯器軟體 (Android 目標為 Android Studio,iOS 目標為 Xcode)。
提示 Antigravity 建立範例專案
- 啟動 Google Antigravity,並開啟空白的工作區目錄,用於建構 Flutter 應用程式 (
app/) 和 Dart 伺服器 (dart-backend/)。請選擇不需進階權限或不含空格的路徑,例如主目錄中的資料夾或C:\src\。 - 在 Antigravity 代理程式對話面板中,傳送下列提示詞,在
app/中建構 Dash Clicker 範例應用程式:
Create a new empty Flutter project in `app/` named `dashclicker` targeting Android and iOS (`flutter create app --project-name dashclicker --empty --platforms android,ios`). Add the `cloud_firestore`, `cupertino_icons`, `firebase_auth`, `firebase_core`, `google_sign_in`, `http`, `intl`, `provider`, `logging`, `material_ui`, and `cupertino_ui` packages. Download `dash_old.png` and `dash.png` from `https://raw.githubusercontent.com/flutter/codelabs/main/in_app_purchases/step_00/app/assets/dash_old.png` and `https://raw.githubusercontent.com/flutter/codelabs/main/in_app_purchases/step_00/app/assets/dash.png` into `app/assets/` and register `assets/` under `flutter: assets:` in `app/pubspec.yaml`. Set `minSdk = 23` in `app/android/app/build.gradle.kts`, and add `GIDClientID` and `CFBundleURLTypes` placeholders in `app/ios/Runner/Info.plist`. Scaffold the Dash Clicker starter files using `package:material_ui/material_ui.dart` and `package:cupertino_ui/cupertino_ui.dart`:
- `lib/constants.dart` defining `cloudRegion = 'europe-west1'`, `storeKeyConsumable = 'dash_consumable_2k'`, `storeKeyUpgrade = 'dash_upgrade_3d'`, `storeKeySubscription = 'dash_subscription_doubler'`, and `serverIp = '192.168.178.46'`
- `lib/firebase_options.dart` with a placeholder `DefaultFirebaseOptions` for Android and iOS
- `lib/model/firebase_state.dart` (`enum FirebaseState { loading, available, notAvailable }`), `lib/model/store_state.dart` (`enum StoreState { loading, available, notAvailable }`), `lib/model/purchasable_product.dart` (`enum ProductStatus { purchasable, purchased, pending }` and `PurchasableProduct(this.title, this.description, this.price)`), and `lib/model/past_purchase.dart` (`PurchaseType`, `Store`, `Status`, and `PastPurchase.fromJson`)
- `lib/logic/dash_counter.dart` (`DashCounter extends ChangeNotifier` with `count`, `countString`, `increment()`, `addAutoIncrement()`, `applyPaidMultiplier()`, `removePaidMultiplier()`, `addBoughtDashes(int amount)`, and a 10Hz `Timer.periodic`)
- `lib/logic/dash_purchases.dart` (`DashPurchases extends ChangeNotifier` with `counter`, `storeState = StoreState.available`, mock `products`, `bool get beautifiedDash => false`, and a simulated `buy(PurchasableProduct product)` method)
- `lib/logic/dash_upgrades.dart` (`DashUpgrades extends ChangeNotifier` and `Upgrade` for `'Tim Sneath'`)
- `lib/logic/firebase_notifier.dart` (`FirebaseNotifier extends ChangeNotifier` initializing `Firebase.initializeApp`, `GoogleSignIn.instance`, `FirebaseAuth`, and `FirebaseFirestore`)
- `lib/repo/iap_repo.dart` (`IAPRepo extends ChangeNotifier` listening to Firebase auth changes and the `purchases` collection in Firestore)
- `lib/pages/home_page.dart` (`HomePage`, `DashClickerWidget`, `CounterStateWidget`, and `UpgradeList`), `lib/pages/login_page.dart` (`LoginPage`), and `lib/pages/purchase_page.dart` (`PurchasePage`, `_PurchasesLoading`, `_PurchasesNotAvailable`, `_PurchaseList`, `_PurchaseWidget`, and `PastPurchasesWidget`)
- `lib/main.dart` (`MyApp` and `MyHomePage` providing `FirebaseNotifier`, `DashCounter`, `DashUpgrades`, `IAPRepo`, and `DashPurchases` using `MultiProvider` with a `BottomNavigationBar` switching between `HomePage` and `PurchasePage`)
- `test/widget_test.dart` pumping `const MyApp()` and verifying `find.text('Tim Sneath')`.
瞭解生成的範例程式碼
Antigravity 會建立 app/ Flutter 專案,並使用 Provider 和 ChangeNotifier 建構 Dash Clicker 遊戲架構:
app/lib/main.dart會在MyHomePage內註冊五個ChangeNotifierProvider(FirebaseNotifier、DashCounter、DashUpgrades、IAPRepo和DashPurchases),並在HomePage和PurchasePage之間切換。app/lib/constants.dart定義了三個商店產品 ID,這些 ID 必須與您在 App Store Connect 和 Google Play 管理中心設定的 ID 相符:
const cloudRegion = 'europe-west1';
const storeKeyConsumable = 'dash_consumable_2k';
const storeKeyUpgrade = 'dash_upgrade_3d';
const storeKeySubscription = 'dash_subscription_doubler';
// TODO: Replace by your own server IP
const serverIp = '192.168.178.46';
設定應用程式的軟體包 ID 和應用程式 ID
應用程式需要專屬的反向網域 ID (例如 dev.flutter.dashclicker),才能與應用程式商店和 Play 商店通訊。在 iOS 上,這稱為軟體包 ID;在 Android 上,則稱為應用程式 ID。在兩個平台使用相同的 ID,可簡化設定。
首先,在 Xcode 中開啟 app/ios/Runner.xcworkspace,設定 iOS 的軟體包 ID:

在 Xcode 的專案導覽器中,選取頂端的「Runner」,開啟「Signing & Capabilities」分頁標籤,選取「Team」,然後輸入專屬的「軟體包 ID」:

接著,更新 app/android/app/build.gradle.kts 中的 Android applicationId,使其與您選擇的 ID 相符 (您可以直接編輯,或要求 Antigravity 將 app/android/app/build.gradle.kts 中的 applicationId 更新為您選擇的 ID):

3. 安裝外掛程式
在這個步驟中,您會提示 Antigravity 將 in_app_purchase 外掛程式及其平台介面套件 (用於在小工具測試中模擬商店連線) 新增至 app/。
提示 Antigravity 安裝 in_app_purchase
在 Antigravity 代理程式對話面板,傳送下列提示詞:
In `app/`, add `in_app_purchase` to `dependencies` and `in_app_purchase_platform_interface` to `dev_dependencies` in `pubspec.yaml`.
瞭解生成的程式碼
Antigravity 會在 app/ 內執行 flutter pub add in_app_purchase dev:in_app_purchase_platform_interface,並更新 app/pubspec.yaml:
dependencies:
flutter:
sdk: flutter
cloud_firestore: ^7.1.0
cupertino_icons: ^2.0.0
cupertino_ui: ^1.1.6
firebase_auth: ^7.0.1
firebase_core: ^5.1.0
google_sign_in: ^7.2.0
http: ^1.6.0
in_app_purchase: ^3.3.1
intl: ^0.20.3
logging: ^1.3.0
material_ui: ^1.11.0
provider: ^6.1.5+1
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^6.0.0
in_app_purchase_platform_interface: ^1.4.1
in_app_purchase提供跨平台InAppPurchaseAPI,由 iOS 的 StoreKit 和 Android 的 Google Play 帳款服務 支援。in_app_purchase_platform_interface會公開InAppPurchasePlatformAddition,讓您在app/test/widget_test.dart中實作模擬InAppPurchase用戶端。
4. 設定 App Store
如要在 iOS 測試應用程式內購,請在 App Store Connect 註冊應用程式,並設定可購買的產品。您不必發布應用程式或送審,但需要 Apple 開發人員帳戶。如果沒有,請註冊 Apple Developer Program。
付費應用程式協議
如要使用應用程式內購功能,您必須在 App Store Connect 中簽署有效的付費應用程式協議。前往 App Store Connect,然後選取「Agreements, Tax, and Banking」(協議、稅務和銀行業務) (或「Business」(業務))。

詳閱免費和付費應用程式的協議。查看並接受付費應用程式條款,然後輸入必要的稅務和銀行資訊。

完成所有設定後,「付費應用程式」的狀態會變更為「有效」。如果沒有有效的付費應用程式協議,StoreKit 在測試期間不會傳回應用程式內商品。

註冊應用程式 ID
在 Apple 開發人員入口網站中建立新的 App ID:
- 前往 Apple Developer Identifiers,然後按一下「Identifiers」標題旁的「+」圖示。

- 選取「App IDs」,然後按一下「Continue」。

- 選取「應用程式」做為類型,然後按一下「繼續」。

- 輸入說明,並將「Bundle ID」(軟體包 ID) (明確) 設為您在 Xcode 中設定的確切軟體包 ID。確認已啟用「應用程式內購」功能,然後註冊 ID。

詳情請參閱 Apple 開發人員帳戶說明。
建立新的應用程式和沙箱使用者
使用註冊的軟體包 ID,在 App Store Connect 建立新的應用程式:
|
|
如需建立應用程式和管理協議的詳細指引,請參閱 App Store Connect 說明。
如要測試應用程式內購,但不想實際付費,請在 App Store Connect 的「Users and Access」>「Sandbox」下方,建立 Sandbox Apple 帳戶。請務必使用尚未與 Apple 帳戶建立關聯的電子郵件地址。

在測試用 iPhone 或 iPad 上,依序前往「設定」>「開發人員」>「沙箱 Apple 帳戶」,然後使用沙箱帳戶登入。
|
|
設定應用程式內購
接著,在 App Store Connect 中設定三個可購買的商品:
dash_consumable_2k:可重複購買的消耗性商品,每次購買可獲得 2,000 點衝刺。dash_upgrade_3d:非消耗性升級商品,只能購買一次,可解鎖 3D Dash 吉祥物。dash_subscription_doubler:自動續訂型訂閱項目,啟用後可增加被動點擊次數。

在應用程式的「應用程式內購」(和「訂閱項目」) 部分,建立三個產品,並使用下列產品 ID:
- 消耗品 (
dash_consumable_2k):- 建立消耗性產品,參考名稱為
dash consumable 2k,產品 ID 為dash_consumable_2k。
- 設定供應情形,讓產品在沙箱使用者的國家/地區或區域中供應。

- 將價格設為
\$1.99(或當地幣別等值金額)。
- 新增本地化設定,顯示名稱為「
Spring is in the air」,說明為「2000 dashes fly out」。
- 上傳評論螢幕截圖。圖片內容不會影響沙箱測試,但上傳螢幕截圖後,產品會轉換為「Ready to Submit」狀態,這是應用程式從 StoreKit 擷取產品的必要條件。

- 建立消耗性產品,參考名稱為
- 非消耗性 (
dash_upgrade_3d):- 建立非消耗性產品,參考名稱為
dash upgrade 3d,產品 ID 為dash_upgrade_3d。 - 將顯示名稱設為
3D Dash,說明設為Brings your dash back to the future,價格設為\$0.99。 - 設定供應情形並上傳審查螢幕截圖,就像您對
dash_consumable_2k所做的操作一樣。
- 建立非消耗性產品,參考名稱為
- 自動續訂型訂閱項目 (
dash_subscription_doubler):- 在「訂閱項目」下方,建立名為「
subscriptions」的訂閱群組 (使用者一次只能訂閱同一群組中的一項產品,並可在群組內升級或降級)。
- 為訂閱群組新增應用程式商店在地化資訊。

- 在群組中建立訂閱項目,參照名稱為
dash subscription doubler,產品 ID 為dash_subscription_doubler。
- 將「訂閱時長」設為「1 週」,「顯示名稱」設為
Jet Engine,「說明」設為Doubles your clicks,「價格」設為\$0.49。設定供應情形並上傳審查螢幕截圖,狀態就會變成「可提交」。
- 在「訂閱項目」下方,建立名為「
產品現在應該會顯示在 App Store Connect 中,狀態為「Ready to Submit」:


5. 設定 Play 商店
如要在 Android 測試應用程式內購,您需要 Google Play 開發人員帳戶。如果您還沒有 Google Play 開發人員帳戶,請註冊一個。
建立新的應用程式
在 Google Play 管理中心建立新應用程式:
- 開啟 Google Play 管理中心。
- 依序選取「所有應用程式」>「建立應用程式」。
- 選擇預設語言並輸入應用程式名稱 (日後可變更)。
- 應用程式類型選取「遊戲」,定價模式選取「免費」。
- 完成「Developer Program 政策」和「美國出口法律」聲明,然後選取「建立應用程式」。
建立應用程式後,請在資訊主頁上完成初始的「設定應用程式」工作:

簽署應用程式
如要測試 Google Play 帳款服務,您必須在 Google Play 管理中心將至少一個已簽署的發布 appbundle 上傳至測試群組。
建立 KeyStore
如果還沒有上傳 KeyStore,請從終端機產生。
macOS 或 Linux:
keytool -genkey -v -keystore ~/key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias key
Windows:
keytool -genkey -v -keystore c:\Users\USER_NAME\key.jks -storetype JKS -keyalg RSA -keysize 2048 -validity 10000 -alias key
建立「app/android/key.properties」
建立 app/android/key.properties,其中包含 KeyStore 的參照:
storePassword=<password from previous step>
keyPassword=<password from previous step>
keyAlias=key
storeFile=<location of the key store file, such as /Users/<user name>/key.jks>
提示 Antigravity 在 Gradle 中設定發布簽署
在 Antigravity 中傳送下列提示詞,在 app/android/app/build.gradle.kts 中設定版本簽署:
Update `app/android/app/build.gradle.kts` to load `key.properties` into a `Properties` object if the file exists, configure a `release` signing config inside `signingConfigs` using `keyAlias`, `keyPassword`, `storeFile`, and `storePassword`, and assign `signingConfigs.getByName("release")` to the `release` build type when `key.properties` is present.
Antigravity 會更新 app/android/app/build.gradle.kts,載入 key.properties 並簽署發布子版本:
val keystoreProperties = Properties()
val keystorePropertiesFile = rootProject.file("key.properties")
if (keystorePropertiesFile.exists()) {
keystoreProperties.load(FileInputStream(keystorePropertiesFile))
}
android {
// ...
signingConfigs {
create("release") {
keyAlias = keystoreProperties["keyAlias"] as String?
keyPassword = keystoreProperties["keyPassword"] as String?
storeFile = keystoreProperties["storeFile"]?.let { file(it) }
storePassword = keystoreProperties["storePassword"] as String?
}
}
buildTypes {
release {
signingConfig = signingConfigs.getByName("release")
}
}
}
上傳第一個版本
從 app/ 建構已簽署的發布版應用程式套件:
cd app
flutter build appbundle
發布套件會寫入 app/build/app/outputs/bundle/release/app-release.aab。
在 Google Play 管理中心,依序前往「測試及發布」>「測試」>「封閉測試」,建立封閉測試版本,上傳 app-release.aab,然後依序點選「儲存」>「檢查版本」>「開始向封閉測試群組發布」。
設定測試使用者
如要在 Android 測試應用程式內購,請在 Google Play 管理中心的兩個位置新增測試人員的 Google 帳戶:
- 測試群組測試人員:依序前往「測試及發布」>「測試」>「內部測試」(或「封閉測試」),開啟「測試人員」分頁,按一下「建立電子郵件名單」,新增測試人員的電子郵件地址,選取名單,然後按一下「儲存變更」。

- 授權測試人員:返回「所有應用程式」檢視畫面,依序選取「設定」>「授權測試」,新增相同的測試人員電子郵件地址,將「授權回應」設為
RESPOND_NORMALLY,然後按一下「儲存變更」。
設定應用程式內購
在 Google Play 管理中心設定相同的三個產品 ID:
dash_consumable_2k:可消耗商品,購買後可獲得 2,000 個 Dash。dash_upgrade_3d:非消耗性一次性 3D Dash 升級。dash_subscription_doubler:自動續訂點擊倍增訂閱方案。
首先,建立單次產品 (dash_consumable_2k 和 dash_upgrade_3d):
- 在 Google Play 管理中心選取應用程式,然後依序前往「透過 Google Play 營利」>「產品」>「應用程式內商品」。
- 按一下「建立產品」。

- 輸入正確的產品 ID (
dash_consumable_2k)、名稱、說明和價格,然後按一下「儲存」和「啟用」。 - 對
dash_upgrade_3d重複上述程序。
接著建立訂閱項目 (dash_subscription_doubler):
- 依序前往「透過 Google Play 營利」>「產品」>「訂閱」,然後按一下「建立訂閱項目」。

- 輸入產品 ID (
dash_subscription_doubler),新增基本方案並設定每週帳單週期和價格,然後依序點選「儲存」和「啟用」。
6. 設定 Firebase
搭配 Cloud Firestore 使用後端服務來驗證及追蹤購買交易,可為應用程式帶來多項安全性優勢:
- 直接透過 Google Play 和 Apple 伺服器驗證交易。
- 您可以回應伺服器端帳單事件 (例如續訂或取消)。
- 您將單一事實來源儲存在 Cloud Firestore 中,並與每位經過驗證的使用者建立關聯。
- 使用者無法透過竄改裝置時鐘來解鎖付費福利。
建立 Firebase 專案
- 開啟 Firebase 控制台,建立新的 Firebase 專案 (例如 Dash Clicker)。
- 依序前往「Build」>「Authentication」,點選「Get started」,開啟「Sign-in method」分頁,然後啟用「Google」登入服務供應商。

- 依序前往「建構」>「Firestore 資料庫」,然後建立資料庫。

- 在 Cloud Firestore 中開啟「規則」分頁,並發布下列安全性規則,讓通過驗證的使用者只能讀取自己的購買文件:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /purchases/{purchaseId} {
allow read: if request.auth != null && request.auth.uid == resource.data.userId
}
}
}
設定 Flutter 適用的 Firebase
按照 FlutterFire 設定指南安裝 FlutterFire CLI,然後在 app/ 中執行 flutterfire configure:
cd app
flutterfire configure
- 選取您建立的 Firebase 專案。
- 啟用 android 和 ios。
- 系統詢問是否要覆寫
lib/firebase_options.dart時,請確認「是」。
設定 Firebase for Android:偵錯 SHA-1 憑證
如要在 Android 上使用 Google 登入功能,必須在 Firebase 控制台中註冊偵錯 KeyStore 的 SHA-1 指紋:
- 在 Firebase 控制台中,依序開啟「專案總覽」>「專案設定」>「一般」,向下捲動至「您的應用程式」,然後選取 Android 應用程式:

- 從
app/android/產生簽署報告:cd app/android ./gradlew :app:signingReport - 在
Variant: debug和Config: debug下方找出SHA1指紋,然後在 Firebase 控制台中將指紋新增至 Android 應用程式,並在app/中重新執行flutterfire configure,讓google-services.json和lib/firebase_options.dart包含更新後的 OAuth 用戶端設定。
設定 Firebase for iOS:設定網址配置
如要在 iOS 上支援 Google 登入,app/ios/Runner/Info.plist 必須在 CFBundleURLTypes 中加入 app/ios/Runner/GoogleService-Info.plist 的 REVERSED_CLIENT_ID (請參閱 google_sign_in iOS 整合文件)。
您可以提示 Antigravity 將 REVERSED_CLIENT_ID 和 CLIENT_ID 從 app/ios/Runner/GoogleService-Info.plist 複製到 app/ios/Runner/Info.plist:
Read `CLIENT_ID` and `REVERSED_CLIENT_ID` from `app/ios/Runner/GoogleService-Info.plist` and update `GIDClientID` and `CFBundleURLTypes` (`CFBundleURLSchemes`) in `app/ios/Runner/Info.plist` with those values.
在 app/ios/Runner/Info.plist 中,CFBundleURLTypes 項目如下所示:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLSchemes</key>
<array>
<string>com.googleusercontent.apps.YOUR_REVERSED_CLIENT_ID</string>
</array>
</dict>
</array>
7. 聆聽購買交易的最新消息
在這個步驟中,您將準備 Flutter 應用程式,讓應用程式在啟動時立即監聽商店購買更新,並導入可覆寫的 IAPConnection 包裝函式,確保小工具樹狀結構可供測試。
提示 Antigravity 聆聽購買更新
在 Antigravity 中傳送下列提示詞:
Update `app/lib/main.dart` to define an `IAPConnection` class with a static `InAppPurchase? _instance` and a static getter and setter for `instance` (defaulting to `InAppPurchase.instance`), and set `lazy: false` on `ChangeNotifierProvider<DashPurchases>`. Update `DashPurchases` in `app/lib/logic/dash_purchases.dart` to set `storeState = StoreState.notAvailable`, hold `final iapConnection = IAPConnection.instance` and `late StreamSubscription<List<PurchaseDetails>> _subscription`, subscribe to `iapConnection.purchaseStream.listen(_onPurchaseUpdate, onDone: _updateStreamOnDone, onError: _updateStreamOnError)` in the constructor, cancel `_subscription` in `dispose()`, and add `_onPurchaseUpdate`, `_updateStreamOnDone`, and `_updateStreamOnError` methods. Finally, update `app/test/widget_test.dart` to define `TestIAPConnection implements InAppPurchase` and set `IAPConnection.instance = TestIAPConnection()` before pumping `MyApp`.
瞭解生成的程式碼
積極供應商初始化和 app/lib/main.dart 中的 IAPConnection
根據預設,Provider 會在小工具首次讀取時延遲建立值。由於待處理的商店交易可能會在啟動時立即到達 purchaseStream,因此 ChangeNotifierProvider 會設定 lazy: false。此外,IAPConnection 提供靜態接縫,因此小工具測試可以插入假 InAppPurchase 實作:
class IAPConnection {
static InAppPurchase? _instance;
static set instance(InAppPurchase value) {
_instance = value;
}
static InAppPurchase get instance {
_instance ??= InAppPurchase.instance;
return _instance!;
}
}
ChangeNotifierProvider<DashPurchases>(
create: (context) => DashPurchases(context.read<DashCounter>()),
lazy: false,
),
在app/lib/logic/dash_purchases.dart訂閱「purchaseStream」
在 DashPurchases 中,建構函式會訂閱 iapConnection.purchaseStream,而 dispose() 會取消 _subscription:
final iapConnection = IAPConnection.instance;
DashPurchases(this.counter) {
final purchaseUpdated = iapConnection.purchaseStream;
_subscription = purchaseUpdated.listen(
_onPurchaseUpdate,
onDone: _updateStreamOnDone,
onError: _updateStreamOnError,
);
}
@override
void dispose() {
_subscription.cancel();
super.dispose();
}
執行及測試應用程式
在 app/ 中執行小工具測試套件,確認 TestIAPConnection 能順利模擬商店連線:
cd app
flutter test
8. 購物
在這個步驟中,您會將硬式編碼的模擬產品替換為使用 queryProductDetails 擷取的實際商店產品、在使用者輕觸產品時啟動購買程序,並在 purchaseStream 收到更新時完成交易。
提示 Antigravity 載入並購買
在 Antigravity 中傳送下列提示詞:
Update `PurchasableProduct` in `app/lib/model/purchasable_product.dart` to wrap a `ProductDetails productDetails` from `package:in_app_purchase/in_app_purchase.dart`, exposing `id`, `title`, `description`, and `price` getters from `productDetails` and initializing `status = ProductStatus.purchasable`. Then update `DashPurchases` in `app/lib/logic/dash_purchases.dart` to initialize `storeState = StoreState.loading`, `products = []`, and `bool _beautifiedDashUpgrade = false` (backing `beautifiedDash`), call `loadPurchases()` in the constructor to check `iapConnection.isAvailable()` and query `{storeKeyConsumable, storeKeySubscription, storeKeyUpgrade}` with `iapConnection.queryProductDetails(ids)`, implement `buy(PurchasableProduct product)` using `PurchaseParam` to call `iapConnection.buyConsumable` for `storeKeyConsumable` and `iapConnection.buyNonConsumable` for `storeKeySubscription` and `storeKeyUpgrade`, and implement `_onPurchaseUpdate` and `_handlePurchase(PurchaseDetails purchaseDetails)` to apply `PurchaseStatus.purchased` rewards (`counter.applyPaidMultiplier()`, `counter.addBoughtDashes(2000)`, `_beautifiedDashUpgrade = true`) and call `iapConnection.completePurchase(purchaseDetails)` when `purchaseDetails.pendingCompletePurchase` is true.
瞭解生成的程式碼
在 app/lib/model/purchasable_product.dart 中包裝 ProductDetails
PurchasableProduct 會包裝商店傳回的 ProductDetails,同時追蹤本機 UI ProductStatus (purchasable、purchased 或 pending):
class PurchasableProduct {
String get id => productDetails.id;
String get title => productDetails.title;
String get description => productDetails.description;
String get price => productDetails.price;
ProductStatus status;
ProductDetails productDetails;
PurchasableProduct(this.productDetails) : status = ProductStatus.purchasable;
}
正在查詢app/lib/logic/dash_purchases.dart中的產品
loadPurchases() 會先確認基礎商店可透過 iapConnection.isAvailable() 存取,然後查詢 app/lib/constants.dart 中定義的三個產品 ID:
Future<void> loadPurchases() async {
final available = await iapConnection.isAvailable();
if (!available) {
storeState = StoreState.notAvailable;
notifyListeners();
return;
}
const ids = <String>{
storeKeyConsumable,
storeKeySubscription,
storeKeyUpgrade,
};
final response = await iapConnection.queryProductDetails(ids);
products = response.productDetails
.map((e) => PurchasableProduct(e))
.toList();
storeState = StoreState.available;
notifyListeners();
}
開始及完成購買
當使用者輕觸 PurchasePage 中的產品時,buy() 會建構 PurchaseParam,並將消耗品調度至 buyConsumable,將一次性升級或訂閱調度至 buyNonConsumable:
Future<void> buy(PurchasableProduct product) async {
final purchaseParam = PurchaseParam(productDetails: product.productDetails);
switch (product.id) {
case storeKeyConsumable:
await iapConnection.buyConsumable(purchaseParam: purchaseParam);
case storeKeySubscription:
case storeKeyUpgrade:
await iapConnection.buyNonConsumable(purchaseParam: purchaseParam);
default:
throw ArgumentError.value(
product.productDetails,
'${product.id} is not a known product',
);
}
}
當商店在 purchaseStream 上發出更新的 PurchaseDetails 物件時,_handlePurchase 會授予相應獎勵,並呼叫 completePurchase 確認完成:
Future<void> _handlePurchase(PurchaseDetails purchaseDetails) async {
if (purchaseDetails.status == PurchaseStatus.purchased) {
switch (purchaseDetails.productID) {
case storeKeySubscription:
counter.applyPaidMultiplier();
case storeKeyConsumable:
counter.addBoughtDashes(2000);
case storeKeyUpgrade:
_beautifiedDashUpgrade = true;
}
}
if (purchaseDetails.pendingCompletePurchase) {
await iapConnection.completePurchase(purchaseDetails);
}
}
執行及測試應用程式
在 app/ 中執行 flutter test,並在設定的測試裝置上啟動應用程式。商店產品啟用後,「購買」分頁會顯示可供購買的產品:

9. 設定後端
在伺服器上驗證及追蹤購買交易前,您必須在 dart-backend/ 中與 app/ 一起建構 Dart 後端服務,並設定 Firebase、Google Play 和應用程式商店的憑證。
提示 Antigravity 建立 Dart 後端鷹架
在 Antigravity 代理程式對話面板中,傳送下列提示詞來建立 dart-backend/ 專案:
Create a Dart shelf server project in `dart-backend/` with package name `firebase_backend_dart` (`dart create -t server-shelf`). Add `googleapis: ^16.0.0`, `googleapis_auth`, `http`, and `app_store_server_sdk` to `dependencies`, and `test` to `dev_dependencies` (configuring `deprecated_member_use: ignore` in `dart-backend/analysis_options.yaml`). Create:
- `dart-backend/lib/constants.dart` defining `androidPackageId`, `appStoreIssuerId`, `appStoreKeyId`, `appStoreSharedSecret`, `bundleId`, `googleCloudProjectId`, and `googlePlayPubsubBillingTopic = 'play_billing'`
- `dart-backend/lib/helpers.dart` with `serveHandler(Handler handler)`, `listenPort()`, and `terminateRequestFuture()` listening to `SIGINT` and `SIGTERM`
- `dart-backend/lib/products.dart` defining `ProductData(this.productId, this.type)`, `enum ProductType { subscription, nonSubscription }`, and `productDataMap` for `'dash_consumable_2k'`, `'dash_upgrade_3d'`, and `'dash_subscription_doubler'`
- `dart-backend/lib/iap_repository.dart` defining `enum IAPSource { googleplay, appstore }`, `abstract class Purchase`, `NonSubscriptionPurchase`, `SubscriptionPurchase`, and `IapRepository(this.api, this.projectId)` using `package:googleapis/firestore/v1.dart` (`createOrUpdatePurchase`, `updatePurchase`, and `getPurchases`)
- `dart-backend/bin/server.dart` starting an empty `Router()` with `await serveHandler(router.call)`.
瞭解生成的程式碼
dart-backend/bin/server.dart會初始化shelf_routerRouter,並使用dart-backend/lib/helpers.dart中的serveHandler,在通訊埠8080上提供 HTTP 要求。dart-backend/lib/products.dart會將每個產品 ID (dash_consumable_2k、dash_upgrade_3d和dash_subscription_doubler) 對應至其ProductType(nonSubscription或subscription)。dart-backend/lib/iap_repository.dart會使用FirestoreApi,封裝 Cloud Firestorepurchases集合中NonSubscriptionPurchase和SubscriptionPurchase文件的讀取和寫入作業。
您可以執行下列指令,測試伺服器是否在本機啟動:
cd dart-backend
dart run ./bin/server.dart
設定 Firebase 存取權
如要讓 dart-backend/ 將已驗證的購買交易寫入 Cloud Firestore,請產生服務帳戶金鑰:
- 在 Firebase 控制台中,依序開啟「專案設定」>「服務帳戶」,然後按一下「產生新的私密金鑰」。

- 將下載的 JSON 檔案儲存為
dart-backend/assets/service-account-firebase.json。
設定 Google Play 存取權
如要讓 dart-backend/ 透過 Google Play Android Developer API 驗證 Android 購買交易,請按照下列步驟操作:
- 在 Google Cloud 控制台中開啟 Google Play Android Developer API 頁面,然後啟用 API。

- 前往 Google Cloud 服務帳戶頁面,然後按一下「+ 建立服務帳戶」。

- 輸入服務帳戶名稱,然後點選「建立並繼續」。

- 授予「Pub/Sub 訂閱者」角色,然後按一下「完成」。

- 開啟新建立服務帳戶的動作選單,然後選取「管理金鑰」。

- 依序選取「新增金鑰」>「建立新的金鑰」,然後選擇「JSON」並下載金鑰:


- 將下載的檔案儲存為
dart-backend/assets/service-account-google-play.json。 - 在 Google Play 管理中心開啟「使用者和權限」,點選「邀請新使用者」,然後輸入服務帳戶的電子郵件地址:


- 授予應用程式「查看財務資料」和「管理訂單和訂閱項目」權限,然後按一下「邀請使用者」。

設定 Apple 應用程式商店存取權
如要在後端驗證 App Store 收據,請產生應用程式專屬共用密鑰:
- 開啟 App Store Connect,選取「Apps」,然後選擇您的應用程式。
- 在側欄中,依序前往「General」>「App Information」。
- 在「App-Specific Shared Secret」下方,按一下「Manage」,產生新的共用密鑰並複製:


更新「dart-backend/lib/constants.dart」
請確認 dart-backend/lib/constants.dart 中已設定下列常數:
androidPackageId:您的 AndroidapplicationId(例如com.example.dashclicker)。appStoreSharedSecret:App Store Connect 共用密鑰。bundleId:iOS 軟體包 ID (例如com.example.dashclicker)。
10. 驗證購買交易
使用者在 iOS 或 Android 裝置上完成購買交易後,應用程式商店會核發驗證權杖 (PurchaseDetails.verificationData.serverVerificationData)。Flutter 應用程式不會直接信任用戶端裝置,而是將這個權杖傳送至 dart-backend/,由向 Google Play 或 App Store 驗證權杖,並在 Cloud Firestore 中記錄購買交易。

提示 Antigravity 在用戶端和後端驗證購買交易
在 Antigravity 中傳送下列提示,連結 Flutter 應用程式和 Dart 後端驗證流程:
1. In `app/`:
- Update `PurchasePage` in `app/lib/pages/purchase_page.dart` to watch `FirebaseNotifier` and return `_PurchasesLoading()` when `state == FirebaseState.loading`, `_PurchasesNotAvailable()` when `state == FirebaseState.notAvailable`, and `const LoginPage()` when `!firebaseNotifier.loggedIn`.
- Add `User? get user => FirebaseAuth.instance.currentUser;` to `FirebaseNotifier` in `app/lib/logic/firebase_notifier.dart`.
- Update `DashPurchases` in `app/lib/logic/dash_purchases.dart` (and its provider in `app/lib/main.dart`) to accept `this.firebaseNotifier`, implement `_verifyPurchase(PurchaseDetails purchaseDetails)` that sends an HTTP `POST` request to `Uri.http('$serverIp:8080', '/verifypurchase')` with JSON body `{'source': purchaseDetails.verificationData.source, 'productId': purchaseDetails.productID, 'verificationData': purchaseDetails.verificationData.serverVerificationData, 'userId': firebaseNotifier.user?.uid}`, and update `_handlePurchase` so purchase rewards are only applied when `await _verifyPurchase(purchaseDetails)` returns `true`.
2. In `dart-backend/`:
- Create `dart-backend/lib/purchase_handler.dart` with `abstract class PurchaseHandler` defining `handleNonSubscription`, `handleSubscription`, and `verifyPurchase` switching on `productData.type`.
- Create `dart-backend/lib/google_play_purchase_handler.dart` with `GooglePlayPurchaseHandler extends PurchaseHandler` that verifies one-time purchases using `androidPublisher.purchases.products.get` and subscriptions using `androidPublisher.purchases.subscriptions.get`, parses order IDs with `extractOrderId(String orderId)` (stripping `..` renewal suffixes), maps statuses with `_nonSubscriptionStatusFrom` and `_subscriptionStatusFrom`, and saves purchases to `iapRepository`.
- Create `dart-backend/lib/app_store_purchase_handler.dart` with `AppStorePurchaseHandler extends PurchaseHandler` that validates receipts with `ITunesApi(ITunesHttpClient(ITunesEnvironment.sandbox(), loggingEnabled: true)).verifyReceipt` and saves `NonSubscriptionPurchase` and `SubscriptionPurchase` records to `iapRepository`.
- Update `dart-backend/bin/server.dart` to initialize `AndroidPublisherApi` and `FirestoreApi` from the service account JSON files in `_createPurchaseHandlers()`, register a `POST /verifypurchase` route, and extract request fields in `getPurchaseData(dynamic payload)` using Dart 3 map pattern matching.
瞭解生成的程式碼
透過驗證和呼叫 /verifypurchase 限制購買
在 app/lib/pages/purchase_page.dart 中,PurchasePage 會檢查 FirebaseNotifier,並顯示 LoginPage,直到使用者登入為止:
var firebaseNotifier = context.watch<FirebaseNotifier>();
if (firebaseNotifier.state == FirebaseState.loading) {
return _PurchasesLoading();
} else if (firebaseNotifier.state == FirebaseState.notAvailable) {
return _PurchasesNotAvailable();
}
if (!firebaseNotifier.loggedIn) {
return const LoginPage();
}
在 app/lib/logic/dash_purchases.dart 中,_verifyPurchase 會先將商店來源 (google_play 或 app_store)、productID、serverVerificationData 和已登入的 userId 發布至 Dart 後端,_handlePurchase 才會發放應用程式內獎勵:
Future<bool> _verifyPurchase(PurchaseDetails purchaseDetails) async {
final url = Uri.http('$serverIp:8080', '/verifypurchase');
const headers = {
'Content-type': 'application/json',
'Accept': 'application/json',
};
final response = await http.post(
url,
body: jsonEncode({
'source': purchaseDetails.verificationData.source,
'productId': purchaseDetails.productID,
'verificationData':
purchaseDetails.verificationData.serverVerificationData,
'userId': firebaseNotifier.user?.uid,
}),
headers: headers,
);
if (response.statusCode == 200) {
return true;
} else {
return false;
}
}
dart-backend/bin/server.dart中的轉送和 Dart 3 模式比對
在伺服器上,POST /verifypurchase 會使用 Dart 3 對應模式和記錄傳回類型,透過 getPurchaseData 解碼 JSON 要求主體,然後將驗證作業委派給相符的商店處理常式:
router.post('/verifypurchase', (Request request) async {
final dynamic payload = json.decode(await request.readAsString());
final (:userId, :source, :productData, :token) = getPurchaseData(payload);
final result = await purchaseHandlers[source]!.verifyPurchase(
userId: userId,
productData: productData,
token: token,
);
if (result) {
return Response.ok('all good!');
} else {
return Response.internalServerError();
}
});
({String userId, String source, ProductData productData, String token})
getPurchaseData(dynamic payload) {
if (payload case {
'userId': String userId,
'source': String source,
'productId': String productId,
'verificationData': String token,
}) {
return (
userId: userId,
source: source,
productData: productDataMap[productId]!,
token: token,
);
} else {
throw const FormatException('Unexpected JSON');
}
}
驗證 Google Play 和 App Store 收據
- 在
dart-backend/lib/google_play_purchase_handler.dart中,GooglePlayPurchaseHandler會查詢單次產品的androidPublisher.purchases.products.get和訂閱項目的androidPublisher.purchases.subscriptions.get,使用extractOrderId從訂閱項目訂單 ID 中移除..#續訂後置字串,並使用iapRepository將產生的NonSubscriptionPurchase或SubscriptionPurchase寫入 Cloud Firestore。 - 在
dart-backend/lib/app_store_purchase_handler.dart中,AppStorePurchaseHandler會使用app_store_server_sdk套件呼叫_iTunesAPI.verifyReceipt,並將response.latestReceiptInfo中每個經過驗證的收據保留至 Cloud Firestore。
執行及測試後端
從 dart-backend/ 啟動後端伺服器:
cd dart-backend
dart run bin/server.dart
11. 追蹤購買交易
訂閱項目可能會在應用程式外續訂、到期或取消。在這個步驟中,您將設定後端,從 Google Cloud Pub/Sub 和 App Store Server API 輪詢商店帳單更新,並更新 Flutter 用戶端,使用 IAPRepo 從 Cloud Firestore 主動同步處理使用者的有效授權。
設定 Cloud Pub/Sub 和 App Store Server API 金鑰
Google Play Cloud Pub/Sub 設定
- 將
dart-backend/lib/constants.dart中的googleCloudProjectId設為 Google Cloud 和 Firebase 專案 ID。 - 在 Google Cloud 控制台中開啟 Cloud Pub/Sub 主題頁面,確認已選取專案,然後按一下「+ 建立主題」。

- 將「主題 ID」設為
play_billing(與dart-backend/lib/constants.dart中的googlePlayPubsubBillingTopic相符,系統會自動建立預設訂閱項目play_billing-sub),然後按一下「建立」。
- 開啟
play_billing主題的三點圖示選單,然後選取「查看權限」。
- 按一下「新增主體」,輸入
google-play-developer-notifications@system.gserviceaccount.com,指派「Pub/Sub 發布者」角色,然後按一下「儲存」。
- 複製完整主題名稱,在 Google Play 管理中心開啟應用程式,依序前往「透過 Google Play 營利」>「營利設定」,貼上主題名稱,然後按一下「儲存變更」。

設定 App Store Server API 金鑰
- 登入 App Store Connect,然後選取「Users and Access」。
- 依序前往「整合」>「金鑰」>「應用程式內購」,然後點選「+」按鈕,產生新的金鑰 (例如
Codelab key)。 - 下載
.p8金鑰檔案,並儲存為dart-backend/assets/SubscriptionKey.p8。 - 將金鑰 ID 和核發者 ID 複製到
dart-backend/lib/constants.dart的appStoreKeyId和appStoreIssuerId。

提示 Antigravity 輪詢商店事件並同步處理用戶端狀態
在 Antigravity 中傳送下列提示詞:
1. In `dart-backend/`:
- Update `GooglePlayPurchaseHandler` in `dart-backend/lib/google_play_purchase_handler.dart` to accept `pubsub.PubsubApi pubsubApi` from `package:googleapis/pubsub/v1.dart`, start a 10-second `Timer.periodic` calling `_pullMessageFromPubSub()`, decode base64 Pub/Sub messages in `_processMessage(String data64, String? ackId)` (handling `testNotification`, `subscriptionNotification`, and `oneTimeProductNotification`), and acknowledge processed messages in `_ackMessage(String id)`.
- Update `AppStorePurchaseHandler` in `dart-backend/lib/app_store_purchase_handler.dart` to accept `AppStoreServerAPI appStoreServerAPI`, start a 10-second `Timer.periodic` calling `_pullStatus()`, query `appStoreServerAPI.getAllSubscriptionStatuses(purchase.orderId)` for active App Store subscriptions in `iapRepository`, and update their expiration date and `SubscriptionStatus` in Firestore.
- Update `dart-backend/bin/server.dart` to add `pubsub.PubsubApi.cloudPlatformScope` to the Google Play client scopes, construct `PubsubApi` and `AppStoreServerAPI` (reading `assets/SubscriptionKey.p8` and caching JWT tokens in `assets/appstore.token`), and pass them to `GooglePlayPurchaseHandler` and `AppStorePurchaseHandler`.
- Create unit tests in `dart-backend/test/firebase_backend_dart_test.dart` verifying `extractOrderId` (with and without a `..0` suffix) and `getPurchaseData` (valid and invalid payloads).
2. In `app/`:
- Update `DashPurchases` in `app/lib/logic/dash_purchases.dart` (and its provider in `app/lib/main.dart`) to accept `this.iapRepo` (`IAPRepo`), register `iapRepo.addListener(purchasesUpdate)` in the constructor and `iapRepo.removeListener(purchasesUpdate)` in `dispose()`, and implement `purchasesUpdate()` and `_updateStatus(PurchasableProduct product, ProductStatus status)` (setting `product.status = status` when `product.status != status`) so `iapRepo.hasActiveSubscription` applies or removes the paid counter multiplier and `iapRepo.hasUpgrade` updates `_beautifiedDashUpgrade` and product statuses.
瞭解生成的程式碼
在後端輪詢 Google Play Pub/Sub 和 App Store Server API
在 dart-backend/lib/google_play_purchase_handler.dart 中,_pullMessageFromPubSub 每 10 秒輪詢一次 projects/$googleCloudProjectId/subscriptions/$googlePlayPubsubBillingTopic-sub 訂閱項目、解碼每個 base64 通知酬載、重新執行 handleSubscription 或 handleNonSubscription 來重新整理 Firestore,並使用 _ackMessage 確認訊息:
Future<void> _pullMessageFromPubSub() async {
print('Polling Google Play messages');
final request = pubsub.PullRequest(maxMessages: 1000);
final topicName =
'projects/$googleCloudProjectId/subscriptions/$googlePlayPubsubBillingTopic-sub';
final pullResponse = await pubsubApi.projects.subscriptions.pull(
request,
topicName,
);
final messages = pullResponse.receivedMessages ?? [];
for (final message in messages) {
final data64 = message.message?.data;
if (data64 != null) {
await _processMessage(data64, message.ackId);
}
}
}
同樣地,在 dart-backend/lib/app_store_purchase_handler.dart 中,_pullStatus 每 10 秒查詢一次 appStoreServerAPI.getAllSubscriptionStatuses(purchase.orderId),並在 Cloud Firestore 中更新每個訂閱項目的 expiryDate 和 SubscriptionStatus (active 或 expired)。
在裝置上同步處理 Firestore 購買交易
在 app/lib/repo/iap_repo.dart 中,IAPRepo 會即時監聽 Cloud Firestore 中已驗證使用者的 purchases 文件,並計算 hasActiveSubscription 和 hasUpgrade:
var purchaseStream = _firestore
.collection('purchases')
.where('userId', isEqualTo: user.uid)
.snapshots();
_purchaseSubscription = purchaseStream.listen((snapshot) {
purchases = snapshot.docs.map((document) {
var data = document.data();
return PastPurchase.fromJson(data);
}).toList();
hasActiveSubscription = purchases.any(
(element) =>
element.productId == storeKeySubscription &&
element.status != Status.expired,
);
hasUpgrade = purchases.any(
(element) => element.productId == storeKeyUpgrade,
);
notifyListeners();
});
每當 IAPRepo 通知事件監聽器時,app/lib/logic/dash_purchases.dart 中的 DashPurchases.purchasesUpdate() 就會啟用或停用 10 倍點擊乘數、切換 _beautifiedDashUpgrade,並更新 PurchasePage 上顯示的產品狀態:
void purchasesUpdate() {
var subscriptions = <PurchasableProduct>[];
var upgrades = <PurchasableProduct>[];
if (products.isNotEmpty) {
subscriptions = products
.where((element) => element.productDetails.id == storeKeySubscription)
.toList();
upgrades = products
.where((element) => element.productDetails.id == storeKeyUpgrade)
.toList();
}
if (iapRepo.hasActiveSubscription) {
counter.applyPaidMultiplier();
for (var element in subscriptions) {
_updateStatus(element, ProductStatus.purchased);
}
} else {
counter.removePaidMultiplier();
for (var element in subscriptions) {
_updateStatus(element, ProductStatus.purchasable);
}
}
if (iapRepo.hasUpgrade != _beautifiedDashUpgrade) {
_beautifiedDashUpgrade = iapRepo.hasUpgrade;
for (var element in upgrades) {
_updateStatus(
element,
_beautifiedDashUpgrade
? ProductStatus.purchased
: ProductStatus.purchasable,
);
}
notifyListeners();
}
}
void _updateStatus(PurchasableProduct product, ProductStatus status) {
if (product.status != status) {
product.status = status;
notifyListeners();
}
}
執行並測試應用程式和後端
在兩項專案中執行單元和 Widget 測試,確認所有項目都經過分析且順利通過:
cd dart-backend
dart test
cd ../app
flutter test
12. 恭喜
恭喜!您已與 Google Antigravity 合作,在 Flutter 中建構全端應用程式內購整合,並使用 Dart 驗證後端。
建構內容
- 在 App Store Connect 和 Google Play 管理中心,設定消耗性 (
dash_consumable_2k)、非消耗性 (dash_upgrade_3d) 和自動續訂型訂閱 (dash_subscription_doubler) 產品。 - 將 Dash Clicker Flutter 應用程式 (
app/) 連結至in_app_purchase外掛程式,查詢產品詳細資料並監聽purchaseStream。 - 建構 Dart
shelf後端 (dart-backend/),使用 Google Play Android Developer API 和應用程式商店驗證購買權杖、使用 Cloud Pub/Sub 和 App Store Server API 輪詢帳單更新,並將購買狀態保存在 Cloud Firestore 中。 - 使用
IAPRepo,將已驗證的購買授權即時同步回 Flutter 用戶端。
後續步驟
- 將 Firebase 驗證 ID 權杖驗證中介軟體新增至
dart-backend/bin/server.dart中的POST /verifypurchase。 - 將
dart-backend/部署至 Cloud Run,並為 Google Cloud Pub/Sub 和應用程式商店伺服器通知設定推送 Webhook。






