Flutter应用内购买插件tabby_flutter_inapp_sdk的使用
Tabby Flutter SDK
Use the Tabby checkout in your Flutter app.
Requirements
- Dart SDK:
">=2.14.0 <3.0.0"
- Flutter:
">=2.5.0"
- Android:
minSdkVersion 17
and add support forandroidx
(see AndroidX Migration to migrate an existing app) - iOS:
--ios-language swift
, Xcode version>= 12
Getting Started
Add flutter_inappwebview
as a dependency in your pubspec.yaml
file.
On iOS
Please make sure you’ve added the following keys in your Info.plist
:
<key>NSCameraUsageDescription</key>
<string>This allows Tabby to take a photo</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>This allows Tabby to select a photo</string>
On Android
Please make sure you’ve added the following permissions in your AndroidManifest.xml
:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application ...>
<!-- Add a provider to be able to upload a user id photo -->
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.flutter_inappwebview.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
</application>
Usage
1. Initialize Tabby SDK
We recommend initializing the Tabby SDK in the main.dart
file:
import 'package:tabby_flutter_inapp_sdk/tabby_flutter_inapp_sdk.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
TabbySDK().setup(
withApiKey: 'YOUR_API_KEY', // Put here your API key, given by the Tabby integrations team
);
runApp(MyApp());
}
2. Create Checkout Session
Create a checkout session with the required payload:
import 'package:tabby_flutter_inapp_sdk/models/payment.dart';
import 'package:tabby_flutter_inapp_sdk/models/buyer.dart';
import 'package:tabby_flutter_inapp_sdk/models/buyer_history.dart';
import 'package:tabby_flutter_inapp_sdk/models/shipping_address.dart';
import 'package:tabby_flutter_inapp_sdk/models/order.dart';
import 'package:tabby_flutter_inapp_sdk/models/order_item.dart';
import 'package:tabby_flutter_inapp_sdk/models/order_history_item.dart';
import 'package:tabby_flutter_inapp_sdk/models/order_history_item_payment_method.dart';
import 'package:tabby_flutter_inapp_sdk/models/order_history_item_status.dart';
import 'package:tabby_flutter_inapp_sdk/models/currency.dart';
import 'package:tabby_flutter_inapp_sdk/models/lang.dart';
final mockPayload = Payment(
amount: '340',
currency: Currency.aed,
buyer: Buyer(
email: 'id.card.success@tabby.ai',
phone: '500000001',
name: 'Yazan Khalid',
dob: '2019-08-24',
),
buyerHistory: BuyerHistory(
loyaltyLevel: 0,
registeredSince: '2019-08-24T14:15:22Z',
wishlistCount: 0,
),
shippingAddress: const ShippingAddress(
city: 'string',
address: 'string',
zip: 'string',
),
order: Order(referenceId: 'id123', items: [
OrderItem(
title: 'Jersey',
description: 'Jersey',
quantity: 1,
unitPrice: '10.00',
referenceId: 'uuid',
productUrl: 'http://example.com',
category: 'clothes',
)
]),
orderHistory: [
OrderHistoryItem(
purchasedAt: '2019-08-24T14:15:22Z',
amount: '10.00',
paymentMethod: OrderHistoryItemPaymentMethod.card,
status: OrderHistoryItemStatus.newOne,
)
],
);
final session = await TabbySDK().createSession(TabbyCheckoutPayload(
merchantCode: 'ae', // pay attention, this might be different for different merchants
lang: Lang.en,
payment: mockPayload,
));
3. Open In-App Browser to Show Checkout
You can open the checkout in an in-app browser:
void openInAppBrowser() {
TabbyWebView.showWebView(
context: context,
webUrl: session.availableProducts.installments.webUrl,
onResult: (WebViewResult resultCode) {
print(resultCode.name);
// TODO: Process resultCode
},
);
}
Alternatively, you can use TabbyWebView
as an inline widget on your page:
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Tabby Checkout'),
),
body: TabbyWebView(
webUrl: session.availableProducts.installments.webUrl,
onResult: (WebViewResult resultCode) {
print(resultCode.name);
// TODO: Process resultCode
},
),
);
}
TabbyPresentationSnippet
To show the TabbyPresentationSnippet
, you can add it as an inline widget on your page:
TabbyPresentationSnippet(
price: mockPayload.amount,
currency: mockPayload.currency,
lang: lang,
)
Example
You can also check the example project.
Example Code
Here is a complete example of how to integrate the Tabby SDK in a Flutter app:
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:tabby_flutter/pages/checkout_page.dart';
import 'package:tabby_flutter/pages/home_page.dart';
import 'package:tabby_flutter_inapp_sdk/tabby_flutter_inapp_sdk.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
TabbySDK().setup(
withApiKey: 'YOUR_API_KEY', // Put here your API key, given by the Tabby integrations team
);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Tabby Flutter SDK Demo',
localizationsDelegates: const [
GlobalCupertinoLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: const [
Locale('en', ''),
Locale('ar', ''),
],
locale: const Locale('en', ''), // Use it for check Arabic locale
theme: ThemeData(
primarySwatch: Colors.green,
),
home: const HomePage(),
routes: {
'/home': (context) => const HomePage(),
'/checkout': (context) => const CheckoutPage(),
},
);
}
}
This example sets up the Tabby SDK, initializes it with your API key, and provides a basic navigation structure with two pages: HomePage
and CheckoutPage
. You can expand on this to fit your specific needs.
更多关于Flutter应用内购买插件tabby_flutter_inapp_sdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter应用内购买插件tabby_flutter_inapp_sdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter应用中使用tabby_flutter_inapp_sdk
插件来实现应用内购买的示例代码。这个插件通常用于处理应用内购买流程,包括产品展示、购买和恢复购买等。
首先,确保你已经在pubspec.yaml
文件中添加了tabby_flutter_inapp_sdk
依赖:
dependencies:
flutter:
sdk: flutter
tabby_flutter_inapp_sdk: ^最新版本号 # 请替换为实际版本号
然后运行flutter pub get
来安装依赖。
1. 初始化SDK
在应用启动时初始化SDK,通常在MainActivity.kt
(Android)和AppDelegate.swift
(iOS)中进行平台特定的初始化,然后在Flutter中调用初始化方法。
Android(MainActivity.kt)
package com.example.yourapp
import android.os.Bundle
import io.flutter.embedding.android.FlutterActivity
import com.tabby.sdk.Tabby
class MainActivity: FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Tabby.initialize(this, "YOUR_TABBY_PUBLIC_KEY")
}
}
iOS(AppDelegate.swift)
在AppDelegate.swift
中添加初始化代码:
import UIKit
import Flutter
import TabbySDK
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
Tabby.shared.initialize(withPublicKey: "YOUR_TABBY_PUBLIC_KEY")
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
2. 在Flutter中调用SDK
接下来,在Flutter代码中调用tabby_flutter_inapp_sdk
提供的API。
导入插件
import 'package:tabby_flutter_inapp_sdk/tabby_flutter_inapp_sdk.dart';
初始化SDK
在应用启动时调用初始化方法:
void initTabby() async {
try {
await TabbyFlutter.initialize();
print("Tabby SDK initialized successfully.");
} catch (e) {
print("Failed to initialize Tabby SDK: $e");
}
}
获取产品列表
void fetchProducts() async {
try {
List<Product> products = await TabbyFlutter.fetchProducts(["product_id_1", "product_id_2"]);
products.forEach((product) {
print("Product: ${product.identifier}, Price: ${product.price}, Localized Title: ${product.localizedTitle}");
});
} catch (e) {
print("Failed to fetch products: $e");
}
}
购买产品
void purchaseProduct(String productId) async {
try {
Purchase purchase = await TabbyFlutter.purchase(productId);
print("Purchase successful: ${purchase.transactionIdentifier}");
} catch (e) {
print("Failed to purchase product: $e");
}
}
恢复购买
void restorePurchases() async {
try {
List<Purchase> purchases = await TabbyFlutter.restorePurchases();
purchases.forEach((purchase) {
print("Restored Purchase: ${purchase.transactionIdentifier}, Product ID: ${purchase.productIdentifier}");
});
} catch (e) {
print("Failed to restore purchases: $e");
}
}
3. 完整示例
下面是一个完整的Flutter页面示例,展示了如何初始化SDK、获取产品列表、购买产品和恢复购买:
import 'package:flutter/material.dart';
import 'package:tabby_flutter_inapp_sdk/tabby_flutter_inapp_sdk.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter In-App Purchase Demo',
home: InAppPurchaseDemo(),
);
}
}
class InAppPurchaseDemo extends StatefulWidget {
@override
_InAppPurchaseDemoState createState() => _InAppPurchaseDemoState();
}
class _InAppPurchaseDemoState extends State<InAppPurchaseDemo> {
@override
void initState() {
super.initState();
initTabby();
}
void initTabby() async {
try {
await TabbyFlutter.initialize();
print("Tabby SDK initialized successfully.");
fetchProducts();
} catch (e) {
print("Failed to initialize Tabby SDK: $e");
}
}
void fetchProducts() async {
try {
List<Product> products = await TabbyFlutter.fetchProducts(["product_id_1", "product_id_2"]);
// You can set state here to update UI with product list
} catch (e) {
print("Failed to fetch products: $e");
}
}
void purchaseProduct(String productId) async {
try {
Purchase purchase = await TabbyFlutter.purchase(productId);
print("Purchase successful: ${purchase.transactionIdentifier}");
// Update UI to reflect purchase status
} catch (e) {
print("Failed to purchase product: $e");
}
}
void restorePurchases() async {
try {
List<Purchase> purchases = await TabbyFlutter.restorePurchases();
// Update UI to reflect restored purchases
} catch (e) {
print("Failed to restore purchases: $e");
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('In-App Purchase Demo'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
ElevatedButton(
onPressed: () => purchaseProduct("product_id_1"),
child: Text('Purchase Product 1'),
),
ElevatedButton(
onPressed: () => restorePurchases(),
child: Text('Restore Purchases'),
),
],
),
),
);
}
}
确保将product_id_1
和product_id_2
替换为你实际的产品ID。
这个示例展示了如何使用tabby_flutter_inapp_sdk
插件进行应用内购买的基本流程。在实际应用中,你可能需要处理更多的状态管理和用户交互逻辑。