-
Notifications
You must be signed in to change notification settings - Fork 320
feat: add mobile onboarding and StoreKit billing #255
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,7 @@ | ||
| { | ||
| "platforms": ["apple"], | ||
| "apple": { | ||
| "modules": ["AfilmorySessionModule", "PhotoMasonryModule", "NativePagesModule"], | ||
| "modules": ["AfilmorySessionModule", "PhotoMasonryModule", "NativePagesModule", "StoreKitBillingModule"], | ||
| "appDelegateSubscribers": ["PushAppDelegateSubscriber", "UploadAppDelegateSubscriber"] | ||
| } | ||
| } |
172 changes: 172 additions & 0 deletions
172
apps/mobile/modules/photo-masonry/ios/Billing/StoreKitBillingModule.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,172 @@ | ||
| import ExpoModulesCore | ||
| import StoreKit | ||
| import UIKit | ||
|
|
||
| public final class StoreKitBillingModule: Module { | ||
| private var transactionUpdatesTask: Task<Void, Never>? | ||
|
|
||
| public func definition() -> ModuleDefinition { | ||
| Name("StoreKitBilling") | ||
| Events("onTransaction") | ||
|
|
||
| OnCreate { | ||
| self.transactionUpdatesTask = Task { [weak self] in | ||
| for await verification in Transaction.updates { | ||
| guard !Task.isCancelled else { return } | ||
| guard case .verified(let transaction) = verification else { continue } | ||
| let payload = Self.transactionPayload(transaction, signedTransactionInfo: verification.jwsRepresentation) | ||
| await MainActor.run { | ||
| self?.sendEvent("onTransaction", payload) | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| OnDestroy { | ||
| self.transactionUpdatesTask?.cancel() | ||
| self.transactionUpdatesTask = nil | ||
| } | ||
|
|
||
| AsyncFunction("loadProducts") { (productIds: [String]) in | ||
| let requestedIds = Self.uniqueProductIds(productIds) | ||
| let products = try await Product.products(for: requestedIds) | ||
| let productsById = Dictionary(uniqueKeysWithValues: products.map { ($0.id, $0) }) | ||
| return requestedIds.compactMap { productId in | ||
| productsById[productId].map(Self.productPayload) | ||
| } | ||
| } | ||
|
|
||
| AsyncFunction("purchase") { (productId: String, appAccountToken: String) in | ||
| guard let token = UUID(uuidString: appAccountToken) else { | ||
| throw StoreKitBillingError.invalidAppAccountToken | ||
| } | ||
| guard let product = try await Product.products(for: [productId]).first(where: { $0.id == productId }) else { | ||
| throw StoreKitBillingError.productUnavailable | ||
| } | ||
|
|
||
| switch try await product.purchase(options: [.appAccountToken(token)]) { | ||
| case .success(let verification): | ||
| switch verification { | ||
| case .verified(let transaction): | ||
| return Self.transactionPayload(transaction, signedTransactionInfo: verification.jwsRepresentation) | ||
| .merging(["status": "success"]) { _, next in next } | ||
| case .unverified: | ||
| throw StoreKitBillingError.unverifiedTransaction | ||
| } | ||
| case .pending: | ||
| return ["status": "pending"] | ||
| case .userCancelled: | ||
| return ["status": "cancelled"] | ||
| @unknown default: | ||
| throw StoreKitBillingError.unknownPurchaseResult | ||
| } | ||
| } | ||
|
|
||
| AsyncFunction("unfinishedTransactions") { | ||
| var transactions: [[String: Any]] = [] | ||
| for await verification in Transaction.unfinished { | ||
| guard case .verified(let transaction) = verification else { continue } | ||
| transactions.append( | ||
| Self.transactionPayload(transaction, signedTransactionInfo: verification.jwsRepresentation) | ||
| ) | ||
| } | ||
| return transactions | ||
| } | ||
|
|
||
| AsyncFunction("restoreTransactions") { (productIds: [String]) in | ||
| try await AppStore.sync() | ||
| let allowedProductIds = Set(Self.uniqueProductIds(productIds)) | ||
| var transactions: [[String: Any]] = [] | ||
| for await verification in Transaction.currentEntitlements { | ||
| guard case .verified(let transaction) = verification else { continue } | ||
| guard allowedProductIds.contains(transaction.productID) else { continue } | ||
| transactions.append( | ||
| Self.transactionPayload(transaction, signedTransactionInfo: verification.jwsRepresentation) | ||
| ) | ||
| } | ||
| return transactions | ||
| } | ||
|
|
||
| AsyncFunction("finishTransaction") { (transactionId: String) in | ||
| guard let expectedId = UInt64(transactionId) else { | ||
| throw StoreKitBillingError.invalidTransactionIdentifier | ||
| } | ||
| for await verification in Transaction.unfinished { | ||
| guard case .verified(let transaction) = verification else { continue } | ||
| guard transaction.id == expectedId else { continue } | ||
| guard StoreKitBillingFinishGate.allowsFinish(isVerified: true, serverAcknowledged: true) else { | ||
| return false | ||
| } | ||
| await transaction.finish() | ||
| return true | ||
| } | ||
| return false | ||
| } | ||
|
|
||
| AsyncFunction("manageSubscriptions") { | ||
| let windowScene = await MainActor.run { | ||
| UIApplication.shared.connectedScenes | ||
| .compactMap { $0 as? UIWindowScene } | ||
| .first { $0.activationState == .foregroundActive } | ||
| } | ||
| guard let windowScene else { | ||
| throw StoreKitBillingError.windowSceneUnavailable | ||
| } | ||
| try await AppStore.showManageSubscriptions(in: windowScene) | ||
| } | ||
| } | ||
|
|
||
| private static func uniqueProductIds(_ values: [String]) -> [String] { | ||
| var seen = Set<String>() | ||
| return values.compactMap { value in | ||
| let normalized = value.trimmingCharacters(in: .whitespacesAndNewlines) | ||
| guard !normalized.isEmpty, seen.insert(normalized).inserted else { return nil } | ||
| return normalized | ||
| } | ||
| } | ||
|
|
||
| private static func productPayload(_ product: Product) -> [String: Any] { | ||
| var payload: [String: Any] = [ | ||
| "displayName": product.displayName, | ||
| "displayPrice": product.displayPrice, | ||
| "id": product.id, | ||
| ] | ||
| if let period = product.subscription?.subscriptionPeriod { | ||
| payload["subscriptionPeriod"] = [ | ||
| "unit": subscriptionPeriodUnit(period.unit), | ||
| "value": period.value, | ||
| ] | ||
| } | ||
| return payload | ||
| } | ||
|
|
||
| private static func subscriptionPeriodUnit(_ unit: Product.SubscriptionPeriod.Unit) -> String { | ||
| switch unit { | ||
| case .day: "day" | ||
| case .week: "week" | ||
| case .month: "month" | ||
| case .year: "year" | ||
| @unknown default: "unknown" | ||
| } | ||
| } | ||
|
|
||
| private static func transactionPayload( | ||
| _ transaction: StoreKit.Transaction, | ||
| signedTransactionInfo: String | ||
| ) -> [String: Any] { | ||
| [ | ||
| "productId": transaction.productID, | ||
| "signedTransactionInfo": signedTransactionInfo, | ||
| "transactionId": String(transaction.id), | ||
| ] | ||
| } | ||
| } | ||
|
|
||
| private enum StoreKitBillingError: Error { | ||
| case invalidAppAccountToken | ||
| case invalidTransactionIdentifier | ||
| case productUnavailable | ||
| case unknownPurchaseResult | ||
| case unverifiedTransaction | ||
| case windowSceneUnavailable | ||
| } |
5 changes: 5 additions & 0 deletions
5
apps/mobile/modules/photo-masonry/ios/Billing/StoreKitBillingPolicy.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| enum StoreKitBillingFinishGate { | ||
| static func allowsFinish(isVerified: Bool, serverAcknowledged: Bool) -> Bool { | ||
| isVerified && serverAcknowledged | ||
| } | ||
| } |
14 changes: 14 additions & 0 deletions
14
apps/mobile/modules/photo-masonry/ios/Tests/StoreKitBillingPolicyTests.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| import XCTest | ||
|
|
||
| @testable import PhotoMasonry | ||
|
|
||
| final class StoreKitBillingPolicyTests: XCTestCase { | ||
| func testVerifiedTransactionFinishesOnlyAfterServerAcknowledgement() { | ||
| XCTAssertFalse(StoreKitBillingFinishGate.allowsFinish(isVerified: true, serverAcknowledged: false)) | ||
| XCTAssertTrue(StoreKitBillingFinishGate.allowsFinish(isVerified: true, serverAcknowledged: true)) | ||
| } | ||
|
|
||
| func testUnverifiedTransactionNeverFinishes() { | ||
| XCTAssertFalse(StoreKitBillingFinishGate.allowsFinish(isVerified: false, serverAcknowledged: true)) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,11 +1,13 @@ | ||
| import { Redirect } from 'expo-router' | ||
|
|
||
| import { useAuth } from '@/modules/auth/sessionStore' | ||
| import { isMobileWorkspaceReady, useMobileOnboarding } from '@/modules/onboarding/onboardingStore' | ||
| import { getDefaultTabPath } from '@/modules/shell/tabAccess' | ||
|
|
||
| export default function IndexRoute() { | ||
| const auth = useAuth() | ||
| const href = getDefaultTabPath(auth.status) | ||
| const onboarding = useMobileOnboarding() | ||
| const href = getDefaultTabPath(auth.status, isMobileWorkspaceReady(onboarding)) | ||
|
|
||
| return href ? <Redirect href={href} /> : null | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| import { Redirect } from 'expo-router' | ||
| import { useEffect } from 'react' | ||
|
|
||
| import { refreshMobileOnboarding } from '@/modules/onboarding/onboardingStore' | ||
|
|
||
| export default function StorageHandoffReturnRoute() { | ||
| useEffect(() => { | ||
| void refreshMobileOnboarding() | ||
| }, []) | ||
|
|
||
| return <Redirect href="/explore" /> | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
On a cold start or deep link to Photos/Map/Studio,
useMobileOnboarding()is stillidle/loading, soisMobileWorkspaceReady()returns false even for an already configured workspace. This branch immediately redirects signed-in users to Explore, and once readiness later becomesreadythere is no navigation back to the original/default tab, so valid signed-in sessions lose their intended route.Useful? React with 👍 / 👎.