tiefen_space_app/context/IapProvider.jsx

85 lines
2.1 KiB
JavaScript

import React, { useState, createContext, useContext, useEffect } from "react";
import { Platform } from "react-native";
import Purchases, { LOG_LEVEL } from "react-native-purchases";
import { AuthContext } from "../App";
import { get } from "../utils/storeInfo";
import Toast from "react-native-toast-message";
const IapContext = createContext();
export const IapProvider = ({ children }) => {
const [isReady, setIsReady] = useState(false);
const [packages, setPackages] = useState([]);
const { state } = useContext(AuthContext);
useEffect(() => {
const init = async () => {
if (Platform.OS === "ios" && state.isSignin) {
const account = await get("account");
await Purchases.configure({
apiKey: process.env.EXPO_PUBLIC_RC_APPLE_KEY,
appUserID: account.mid.toString(),
});
Purchases.setLogLevel(LOG_LEVEL.DEBUG);
await loadOfferings();
}
setIsReady(true);
};
init();
}, [state]);
const loadOfferings = async () => {
const offerings = await Purchases.getOfferings();
if (offerings.current) {
setPackages(offerings.current.availablePackages);
}
};
const purchasePackage = async (pack) => {
if (Platform.OS !== "ios") return;
try {
await Purchases.purchasePackage(pack);
} catch (e) {
console.error(e);
}
};
const getCustomerInformation = async () => {
if (Platform.OS !== "ios") return;
try {
const customerInfo = await Purchases.getCustomerInfo();
return customerInfo;
} catch (e) {
console.error(e);
}
};
const restorePurchases = async () => {
if (Platform.OS !== "ios") return;
try {
await Purchases.restorePurchases();
Toast.show({
type: "success",
text1: "恢复成功",
topOffset: 60,
});
} catch (e) {
console.error(e);
}
};
const value = {
packages,
purchasePackage,
getCustomerInformation,
restorePurchases,
};
if (!isReady) return <></>;
return <IapContext.Provider value={value}>{children}</IapContext.Provider>;
};
export const useIap = () => useContext(IapContext);