TIL: RN | 인앱 결제 react-native-iap Hooks (함수 컴포넌트 사용 시) - 221206

Lumpen·2022년 12월 6일
1

RN인앱결제

목록 보기
12/16

iap Hooks

react native 를 함수 컴포넌트로 작성 시 hooks 로 iap를 사용해야 한다
Hooks가 훨씬 간단하게 구현되어있어서 오히려 좋다

App.tsx

import { requestPurchase, useIAP, withIAPContext } from 'react-native-iap';

const App = () => {
	const {
    products,
    currentPurchase,
    currentPurchaseError,
    finishTransaction,
    getProducts,
  } = useIAP();

	const handlePurchase = async (sku: string) => {
    await requestPurchase({ sku });
  };

	React.useEffect(() => {
    // ... listen to currentPurchaseError, to check if any error happened
    console.log(currentPurchaseError, 'currentPurchaseError');
  }, [currentPurchaseError]);

  React.useEffect(() => {
    // ... listen to currentPurchase, to check if the purchase went through
    console.log(currentPurchase, 'currentPurchase');
  }, [currentPurchase]);

	return (
			<Button
          title="Get the products"
          onPress={() => {
            getProducts({
              skus: [제품 ID],
            }).then(res => {
              console.log(res);
            });
          }}
        />
        {products.map(product => (
          <View key={product.productId}>
            <Text>{product.productId}</Text>

            <Button
              title="Buy"
              onPress={() => handlePurchase(product.productId)}
            />
          </View>
        ))}
	)
}


export default withIAPContext(App);

getProduct() 메소드 인자로 [{ skus: [app.id] }] 를 넘겨줘야 하는데
app id 는 앱 내 구입 아이템의 제품 ID를 문자열로 넘겨줘야 함

Apple Developer - App Store - 앱 내 구입 - 제품 ID

Get the products 버튼을 onPress 했을 경우 올바른 제품 ID를 넘겨준다면

product.productId 가 생성되어 제품 ID 가 화면에 출력되고

Buy 버튼이 생성됨

Buy 버튼은 handlePurchase 함수에 제품 ID 를 넘겨주어 구매할 수 있도록 하는데

apple login (Sandbox ID) 을 해서 구매할 수 있다

profile
떠돌이 생활을 하는. 실업자는 아니지만, 부랑 생활을 하는

0개의 댓글