[flutter] Firebase_core를 사용하여 플러터 앱에서 인앱 결제 구현하기
앱 개발에서 인앱 결제를 구현하는 것은 중요한 부분입니다. Firebase는 플러터 앱에서 인앱 결제를 간단하게 구현할 수 있는 도구 중 하나입니다. Firebase를 사용하여 플러터 앱에서 인앱 결제를 구현하는 방법에 대해 알아보겠습니다.
Firebase 설정하기
- Firebase 콘솔에 로그인하여 프로젝트를 생성합니다.
- Firebase 프로젝트 설정에서 인증 섹션으로 이동하고, Firebase SDK 구성 파일을 다운로드합니다.
- Flutter 프로젝트의 “android/app” 디렉토리에 다운로드한 Firebase SDK 구성 파일을 복사합니다.
Flutter 프로젝트에 Firebase_core 추가하기
pubspec.yaml
파일을 열고,firebase_core
패키지를 dependencies 섹션에 추가합니다.
dependencies:
flutter:
sdk: flutter
firebase_core: ^1.0.0
- 터미널에서 다음 명령어를 실행하여 패키지를 설치합니다.
flutter pub get
main.dart
파일에서firebase_core
패키지를 임포트합니다.
import 'package:firebase_core/firebase_core.dart';
main()
함수에서Firebase.initializeApp()
를 호출하여 Firebase를 초기화합니다.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
인앱 결제 사용하기
- Firebase 콘솔에서 앱 ID를 등록하여 인앱 결제를 사용할 수 있도록 설정합니다.
android/app/build.gradle
파일을 열고,dependencies
블록에 다음 코드를 추가합니다.
implementation 'com.android.support:multidex:1.0.3'
android/app/src/main/AndroidManifest.xml
파일을 열고,<application>
요소 안에 다음 코드를 추가합니다.
<meta-data
android:name="com.google.android.gms.wallet.api.enabled"
android:value="true" />
android/app/src/main/kotlin/com/example/app/MainActivity.kt
파일을 열고, 다음 코드를 추가합니다.
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
flutterEngine.plugins.add(FlutterInappPurchasePlugin())
}
}
-
Flutter 프로젝트의
lib
디렉토리에in_app_purchase
패키지를 생성하고, 필요한 파일들을 추가합니다. (예:in_app_purchase_service.dart
,in_app_purchase_listener.dart
등) -
in_app_purchase_service.dart
파일에 인앱 결제를 위한 서비스 로직을 작성합니다.
import 'package:in_app_purchase/in_app_purchase.dart';
class InAppPurchaseService {
InAppPurchaseConnection _connection = InAppPurchaseConnection.instance;
Future<List<ProductDetails>> getProducts() async {
const Set<String> _kProductIds = {'your_product_id'};
final ProductDetailsResponse response = await _connection.queryProductDetails(_kProductIds);
if (response.notFoundIDs.isNotEmpty) {
// Product IDs not found
}
return response.productDetails;
}
Future<bool> buyProduct(ProductDetails product) async {
final PurchaseParam purchaseParam = PurchaseParam(productDetails: product);
bool available = await _connection.isAvailable();
if (!available) {
// In-app purchase not available
return false;
}
PurchaseDetails purchase = await _connection.buyNonConsumable(purchaseParam);
if (purchase.status == PurchaseStatus.error) {
// Purchase failed
return false;
}
if (purchase.status == PurchaseStatus.purchased) {
// Purchase success
return true;
}
return false;
}
Future<void> restorePurchases() async {
await _connection.restorePurchases();
}
}
- 이제 인앱 결제를 사용할 위젯에서
InAppPurchaseService
를 인스턴스화하고 사용할 수 있습니다.
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'in_app_purchase/in_app_purchase_service.dart';
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Firebase In-App Purchase',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
final InAppPurchaseService inAppPurchaseService = InAppPurchaseService();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Firebase In-App Purchase'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
child: Text('Buy Now'),
onPressed: () {
// Buy product logic
},
),
ElevatedButton(
child: Text('Restore Purchases'),
onPressed: () {
// Restore purchases logic
},
),
],
),
),
);
}
}
이제 Firebase와 함께 플러터 앱에서 인앱 결제를 쉽게 구현할 수 있습니다. Firebase를 사용하여 인앱 결제를 구현하려는 경우 위의 단계를 따라 진행하시면 됩니다.