Skip to content
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

feat: useIap hook #9

Merged
merged 2 commits into from
Oct 27, 2024
Merged
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: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -398,3 +398,5 @@ export const finishTransaction = ({
}) || (() => Promise.reject(new Error('Unsupported Platform')))
)();
};

export * from './useIap';
2 changes: 1 addition & 1 deletion src/modules/ios.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import type {
} from '../types/ExpoIapIos.types';
import ExpoIapModule from '../ExpoIapModule';

type TransactionEvent = {
export type TransactionEvent = {
transaction?: TransactionSk2;
error?: PurchaseError;
};
Expand Down
188 changes: 188 additions & 0 deletions src/useIap.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
import {
endConnection,
initConnection,
purchaseErrorListener,
purchaseUpdatedListener,
transactionUpdatedIos,
getProducts,
getAvailablePurchases,
getPurchaseHistory,
getSubscriptions,
} from './';

import {useCallback, useEffect, useState} from 'react';
import {
Product,
ProductPurchase,
Purchase,
PurchaseError,
PurchaseResult,
SubscriptionProduct,
SubscriptionPurchase,
} from './ExpoIap.types';
import {TransactionEvent} from './modules/ios';
import {TransactionSk2} from './types/ExpoIapIos.types';
import {Subscription} from 'expo-modules-core';

type IAP_STATUS = {
connected: boolean;
products: Product[];
promotedProductsIOS: TransactionSk2[];
subscriptions: SubscriptionProduct[];
purchaseHistories: ProductPurchase[];
availablePurchases: ProductPurchase[];
currentPurchase?: ProductPurchase;
currentPurchaseError?: PurchaseError;
finishTransaction: ({
purchase,
isConsumable,
developerPayloadAndroid,
}: {
purchase: Purchase;
isConsumable?: boolean;
developerPayloadAndroid?: string;
}) => Promise<string | boolean | PurchaseResult | void>;
getAvailablePurchases: () => Promise<void>;
getPurchaseHistories: () => Promise<void>;
getProducts: (skus: string[]) => Promise<void>;
getSubscriptions: (skus: string[]) => Promise<void>;
};

let purchaseUpdateSubscription: Subscription;
let purchaseErrorSubscription: Subscription;
let promotedProductsSubscription: Subscription;

export function useIAP(): IAP_STATUS {
const [connected, setConnected] = useState<boolean>(false);
const [products, setProducts] = useState<Product[]>([]);
const [promotedProductsIOS, setPromotedProductsIOS] = useState<
TransactionSk2[]
>([]);
const [subscriptions, setSubscriptions] = useState<SubscriptionProduct[]>([]);
const [purchaseHistories, setPurchaseHistories] = useState<ProductPurchase[]>(
[],
);
const [availablePurchases, setAvailablePurchases] = useState<
ProductPurchase[]
>([]);
const [currentPurchase, setCurrentPurchase] = useState<ProductPurchase>();

const [currentPurchaseError, setCurrentPurchaseError] =
useState<PurchaseError>();

const requestProducts = useCallback(async (skus: string[]): Promise<void> => {
setProducts(await getProducts(skus));
}, []);

const requestSubscriptions = useCallback(
async (skus: string[]): Promise<void> => {
setSubscriptions(await getSubscriptions(skus));
},
[],
);

const requestAvailablePurchases = useCallback(async (): Promise<void> => {
setAvailablePurchases(await getAvailablePurchases());
}, []);

const requestPurchaseHistories = useCallback(async (): Promise<void> => {
setPurchaseHistories(await getPurchaseHistory());
}, []);

const finishTransaction = useCallback(
async ({
purchase,
isConsumable,
developerPayloadAndroid,
}: {
purchase: ProductPurchase;
isConsumable?: boolean;
developerPayloadAndroid?: string;
}): Promise<string | boolean | PurchaseResult | void> => {
try {
return await finishTransaction({
purchase,
isConsumable,
developerPayloadAndroid,
});
} catch (err) {
throw err;
} finally {
if (purchase.productId === currentPurchase?.productId) {
setCurrentPurchase(undefined);
}

if (purchase.productId === currentPurchaseError?.productId) {
setCurrentPurchaseError(undefined);
}
}
},
[
currentPurchase?.productId,
currentPurchaseError?.productId,
setCurrentPurchase,
setCurrentPurchaseError,
],
);

const initIapWithSubscriptions = useCallback(async (): Promise<void> => {
const result = await initConnection();

setConnected(result);

if (result) {
purchaseUpdateSubscription = purchaseUpdatedListener(
async (purchase: Purchase | SubscriptionPurchase) => {
setCurrentPurchaseError(undefined);
setCurrentPurchase(purchase);
},
);

purchaseErrorSubscription = purchaseErrorListener(
(error: PurchaseError) => {
setCurrentPurchase(undefined);
setCurrentPurchaseError(error);
},
);

promotedProductsSubscription = transactionUpdatedIos(
(event: TransactionEvent) => {
setPromotedProductsIOS((prevProducts) =>
event.transaction
? [...prevProducts, event.transaction]
: prevProducts,
);
},
);
}
}, []);

useEffect(() => {
initIapWithSubscriptions();

return (): void => {
if (purchaseUpdateSubscription) purchaseUpdateSubscription.remove();
if (purchaseErrorSubscription) purchaseErrorSubscription.remove();
if (promotedProductsSubscription) promotedProductsSubscription.remove();

endConnection();
setConnected(false);
};
}, [initIapWithSubscriptions]);

return {
connected,
products,
promotedProductsIOS,
subscriptions,
purchaseHistories,
finishTransaction,
availablePurchases,
currentPurchase,
currentPurchaseError,
getProducts: requestProducts,
getSubscriptions: requestSubscriptions,
getAvailablePurchases: requestAvailablePurchases,
getPurchaseHistories: requestPurchaseHistories,
};
}
Loading