Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci-kmp-iap.yml
Original file line number Diff line number Diff line change
Expand Up @@ -118,4 +118,4 @@ jobs:
uses: ./.github/actions/setup-xcode

- name: Verify SwiftPM library, Xcode app, and Maven consumer without CocoaPods
run: bash scripts/verify-swiftpm-build.sh
run: bash scripts/verify-swiftpm-build.sh --allow-unreleased-apple
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package expo.modules.iap

import android.content.Context
import dev.hyo.openiap.DeepLinkOptions
import dev.hyo.openiap.ExternalPurchaseLinkRequest
import dev.hyo.openiap.FetchProductsResultAll
import dev.hyo.openiap.FetchProductsResultProducts
import dev.hyo.openiap.FetchProductsResultSubscriptions
Expand Down Expand Up @@ -880,6 +881,52 @@ class ExpoIapModule : Module() {
}
}

AsyncFunction("isExternalPurchaseLinkAvailable") { promise: Promise ->
ExpoIapLog.payload("isExternalPurchaseLinkAvailable", null)
scope.launch {
try {
val isAvailable = openIapStore.isExternalPurchaseLinkAvailable()
ExpoIapLog.result("isExternalPurchaseLinkAvailable", isAvailable)
promise.resolve(isAvailable)
} catch (e: Exception) {
ExpoIapLog.failure("isExternalPurchaseLinkAvailable", e)
promise.reject((e as? OpenIapError)?.code ?: OpenIapError.ServiceUnavailable.CODE, e.message, e)
}
}
}

AsyncFunction("openExternalPurchaseLink") { params: Map<String, Any?>, promise: Promise ->
ExpoIapLog.payload("openExternalPurchaseLink", params)
scope.launch {
try {
val request =
runCatching { ExternalPurchaseLinkRequest.fromJson(params) }
.getOrNull() ?: run {
promise.reject(
OpenIapError.DeveloperError.CODE,
"Invalid external purchase link request: `url` is required.",
null,
)
return@launch
}
val activity =
runCatching { currentActivity }
.onFailure {
ExpoIapLog.failure("openExternalPurchaseLink activity", it)
}.getOrNull() ?: run {
promise.reject(OpenIapError.ServiceUnavailable.CODE, "Activity not available", null)
return@launch
}
val result = openIapStore.openExternalPurchaseLink(activity, request).toJson()
ExpoIapLog.result("openExternalPurchaseLink", result)
promise.resolve(result)
} catch (e: Exception) {
ExpoIapLog.failure("openExternalPurchaseLink", e)
promise.reject((e as? OpenIapError)?.code ?: OpenIapError.ServiceUnavailable.CODE, e.message, e)
}
}
}

OnDestroy {
try {
listenerHandles?.let { ExpoIapHelper.cleanupListeners(openIap, it) }
Expand Down
42 changes: 42 additions & 0 deletions libraries/expo-iap/example/__tests__/alternative-billing.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,48 @@ describe('AlternativeBilling Component', () => {
expect(getByText('Not supported on Amazon Vega')).toBeDefined();
});

it('opens the iOS external purchase link through the shared API', async () => {
Object.defineProperty(Platform, 'OS', {
get: jest.fn(() => 'ios'),
configurable: true,
});
jest
.mocked(ExpoIap.isExternalPurchaseLinkAvailable)
.mockResolvedValueOnce(true);
jest.mocked(ExpoIap.openExternalPurchaseLink).mockResolvedValueOnce({
platform: 'ios',
status: 'opened',
reportToken: 'external-purchase-token',
});
const {getByText} = await render(<AlternativeBilling />);

await fireEvent.press(getByText('Test Consumable'));
await fireEvent.press(getByText('🛒 Buy (External URL)'));

expect(ExpoIap.openExternalPurchaseLink).toHaveBeenCalledWith({
url: 'https://openiap.dev',
});
expect(getByText(/External purchase link opened/)).toBeTruthy();
expect(getByText(/Report token: Present/)).toBeTruthy();
});

it('skips the iOS link when the storefront is not eligible', async () => {
Object.defineProperty(Platform, 'OS', {
get: jest.fn(() => 'ios'),
configurable: true,
});
jest
.mocked(ExpoIap.isExternalPurchaseLinkAvailable)
.mockResolvedValueOnce(false);
const {getByText} = await render(<AlternativeBilling />);

await fireEvent.press(getByText('Test Consumable'));
await fireEvent.press(getByText('🛒 Buy (External URL)'));

expect(ExpoIap.openExternalPurchaseLink).not.toHaveBeenCalled();
expect(getByText(/not available for this app or storefront/)).toBeTruthy();
});

it('switches the billing flow only after native applies its program', async () => {
Object.defineProperty(Platform, 'OS', {
get: jest.fn(() => 'android'),
Expand Down
68 changes: 38 additions & 30 deletions libraries/expo-iap/example/app/alternative-billing.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ import {
useIAP,
requestPurchase,
initConnection,
presentExternalPurchaseLinkIOS,
isExternalPurchaseLinkAvailable,
openExternalPurchaseLink,
isBillingProgramAvailableAndroid,
launchExternalLinkAndroid,
createBillingProgramReportingDetailsAndroid,
Expand All @@ -36,11 +37,12 @@ import {
*
* Demonstrates alternative billing flows for iOS and Android:
*
* iOS (Alternative Billing):
* - Redirects users to external website configured in app.config.ts
* - No onPurchaseUpdated callback when using external URL
* - User completes purchase on external website
* - Must implement deep link to return to app
* iOS (External Purchase Link - 17.4+):
* - Enable the external purchase entitlement in app.config.ts
* - Check eligibility with isExternalPurchaseLinkAvailable()
* - openExternalPurchaseLink() shows Apple's disclosure, then opens the URL
* - No onPurchaseUpdated callback; the purchase completes on your website
* - Report the returned reportToken from your server
*
* Android (Billing Programs API - 8.2.0+):
* - Step 1: Check availability with isBillingProgramAvailableAndroid()
Expand Down Expand Up @@ -152,6 +154,7 @@ function AlternativeBillingScreen() {
'external-payments': 'External Payments',
'user-choice-billing': 'User Choice Billing',
'billing-choice': 'Billing Choice',
'alternative-billing-only': 'Alternative Billing Only',
};

setPurchaseResult(
Expand All @@ -170,13 +173,9 @@ function AlternativeBillingScreen() {
[fetchProducts],
);

// Handle iOS alternative billing purchase (external URL)
// Handle iOS external purchase link
const handleIOSAlternativeBillingPurchase = useCallback(
async (product: Product) => {
console.log('[iOS] Starting alternative billing purchase:', product.id);
console.log('[iOS] External URL:', externalUrl);
console.log('[iOS] Platform.Version:', Platform.Version);

if (!externalUrl || externalUrl.trim() === '') {
Alert.alert('Error', 'Please enter a valid external purchase URL');
return;
Expand All @@ -186,24 +185,32 @@ function AlternativeBillingScreen() {
setPurchaseResult('🌐 Opening external purchase link...');

try {
// Use StoreKit External Purchase Link API
const result = await presentExternalPurchaseLinkIOS(externalUrl);
console.log('[iOS] External purchase link result:', result);

if (result.error) {
setPurchaseResult(`❌ Error: ${result.error}`);
Alert.alert('Error', result.error);
} else if (result.success) {
if (!(await isExternalPurchaseLinkAvailable())) {
setPurchaseResult(
`✅ External purchase link opened successfully\n\nProduct: ${product.id}\nURL: ${externalUrl}\n\nUser was redirected to external website.\n\nNote: Complete purchase on your website and implement server-side validation.`,
'❌ External purchase links are not available for this app or storefront',
);
Alert.alert(
'Redirected',
'User was redirected to your external purchase website. Complete the purchase there.',
return;
}

// Shows Apple's disclosure sheet first, then opens the URL.
const result = await openExternalPurchaseLink({url: externalUrl});
console.log('[iOS] External purchase link status:', result.status);

if (result.status === 'opened') {
setPurchaseResult(
`✅ External purchase link opened\n\nProduct: ${
product.id
}\nURL: ${externalUrl}\nReport token: ${
result.reportToken ? 'Present' : 'Missing'
}\n\nNote: Complete purchase on your website and report the token from your server.`,
);
} else if (result.status === 'cancelled') {
setPurchaseResult('User cancelled the external purchase link');
} else {
setPurchaseResult('❌ External purchase link unavailable');
}
} catch (error: any) {
console.log('[iOS] Alternative billing error:', error);
console.log('[iOS] External purchase link error:', error);
setPurchaseResult(`❌ Error: ${error.message}`);
Alert.alert('Error', error.message);
} finally {
Expand Down Expand Up @@ -356,7 +363,7 @@ function AlternativeBillingScreen() {
{isVega
? 'Not supported on Amazon Vega'
: Platform.OS === 'ios'
? 'External purchase links (iOS 16.0+)'
? 'External purchase links (iOS 17.4+)'
: 'Google Play alternative billing'}
</Text>
</View>
Expand All @@ -382,14 +389,15 @@ function AlternativeBillingScreen() {
<>
<Text style={styles.infoText}>
• Enter your external purchase URL{'\n'}• Tap Purchase on any
product{'\n'}• User will be redirected to the external URL{'\n'}
• Complete purchase on your website{'\n'}• No onPurchaseUpdated
callback{'\n'}• Implement deep link to return to app
product{'\n'}• The App Store disclosure sheet appears, then the
URL opens{'\n'}• Complete purchase on your website{'\n'}• No
onPurchaseUpdated callback{'\n'}• Report the returned token from
your server
</Text>
<Text style={styles.warningText}>
⚠️ iOS 16.0+ required{'\n'}
⚠️ iOS 17.4+ required{'\n'}
⚠️ Valid external URL needed{'\n'}
⚠️ Billing program mode is enabled
⚠️ External purchase entitlement must be enabled
</Text>
</>
) : (
Expand Down
7 changes: 4 additions & 3 deletions libraries/expo-iap/example/jest.setup.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,15 +101,16 @@ jest.mock('expo-iap', () => {
getReceiptDataIOS: jest.fn(),
isTransactionVerifiedIOS: jest.fn(),
getTransactionJwsIOS: jest.fn(),
presentExternalPurchaseLinkIOS: jest.fn(() =>
Promise.resolve({success: true}),
),
getAppTransactionIOS: jest.fn(),

// Cross-platform storefront helper
getStorefront: jest.fn(),
deepLinkToSubscriptions: jest.fn(() => Promise.resolve(true)),
openRedeemOfferCode: jest.fn(() => Promise.resolve(null)),
isExternalPurchaseLinkAvailable: jest.fn(() => Promise.resolve(false)),
openExternalPurchaseLink: jest.fn(() =>
Promise.resolve({status: 'unavailable', platform: 'ios'}),
),
verifyAppOwnership: jest.fn(),

// Android functions
Expand Down
20 changes: 20 additions & 0 deletions libraries/expo-iap/ios/ExpoIapModule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,26 @@ public final class ExpoIapModule: Module {
}
}

AsyncFunction("isExternalPurchaseLinkAvailable") { () async throws -> Bool in
try await IapException.bridging("isExternalPurchaseLinkAvailable") {
ExpoIapLog.payload("isExternalPurchaseLinkAvailable", payload: nil)
let isAvailable = try await OpenIapModule.shared.isExternalPurchaseLinkAvailable()
ExpoIapLog.result("isExternalPurchaseLinkAvailable", value: isAvailable)
return isAvailable
}
}

AsyncFunction("openExternalPurchaseLink") { (params: [String: Any]) async throws -> [String: Any] in
try await IapException.bridging("openExternalPurchaseLink") {
ExpoIapLog.payload("openExternalPurchaseLink", payload: params)
let request = try OpenIapSerialization.decode(object: params, as: ExternalPurchaseLinkRequest.self)
let result = try await OpenIapModule.shared.openExternalPurchaseLink(request)
let sanitized = ExpoIapHelper.sanitizeDictionary(OpenIapSerialization.encode(result))
ExpoIapLog.result("openExternalPurchaseLink", value: sanitized)
return sanitized
}
}

AsyncFunction("showManageSubscriptionsIOS") { () async throws -> [[String: Any]] in
try await IapException.bridging("showManageSubscriptionsIOS") {
ExpoIapLog.payload("showManageSubscriptionsIOS", payload: nil)
Expand Down
2 changes: 2 additions & 0 deletions libraries/expo-iap/src/ExpoIapModule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export type ExpoIapNativeModule = NativeEventModule &
| 'getTransactionJwsIOS'
| 'hasActiveSubscriptions'
| 'isEligibleForExternalPurchaseCustomLinkIOS'
| 'isExternalPurchaseLinkAvailable'
| 'isEligibleForIntroOfferIOS'
| 'isTransactionVerifiedIOS'
| 'latestTransactionIOS'
Expand All @@ -69,6 +70,7 @@ export type ExpoIapNativeModule = NativeEventModule &
| 'initConnection'
| 'isBillingProgramAvailableAndroid'
| 'launchExternalLinkAndroid'
| 'openExternalPurchaseLink'
| 'openRedeemOfferCode'
| 'presentExternalPurchaseLinkIOS'
| 'presentExternalPurchaseNoticeSheetIOS'
Expand Down
2 changes: 2 additions & 0 deletions libraries/expo-iap/src/__mocks__/expo-modules-core.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ const mockNativeModule = {
isTransactionVerifiedIOS: jest.fn(),
getTransactionJwsIOS: jest.fn(),
openRedeemOfferCode: jest.fn(async () => null),
isExternalPurchaseLinkAvailable: jest.fn(async () => false),
openExternalPurchaseLink: jest.fn(),
canPresentExternalPurchaseNoticeIOS: jest.fn(),
presentExternalPurchaseNoticeSheetIOS: jest.fn(),
presentExternalPurchaseLinkIOS: jest.fn(),
Expand Down
9 changes: 9 additions & 0 deletions libraries/expo-iap/src/__tests__/index.kepler.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import {
fetchProducts,
getAvailablePurchases,
isExternalPurchaseLinkAvailable,
openExternalPurchaseLink,
openRedeemOfferCode,
requestPurchase,
} from '../index.kepler';
Expand Down Expand Up @@ -122,6 +124,13 @@ describe('Amazon Vega public API', () => {
await expect(openRedeemOfferCode()).resolves.toBeNull();
});

it('reports external purchase links as unavailable', async () => {
await expect(isExternalPurchaseLinkAvailable()).resolves.toBe(false);
await expect(
openExternalPurchaseLink({url: 'https://example.com/buy'}),
).resolves.toEqual({status: 'unavailable', platform: 'android'});
});

it("rejects the removed 'inapp' product type", async () => {
await expect(
// @ts-expect-error the removed alias reaches the runtime check
Expand Down
Loading
Loading