Flutter支付集成插件flutter_sslcommerz的使用
Flutter支付集成插件flutter_sslcommerz的使用
这是官方的SSLCommerz Flutter插件,用于Flutter应用程序的集成。目前它仅支持Android和iOS。
部署目标
- 对于iOS: 部署目标:11.0
- 对于Android: minSdkVersion 21
支付调用模板
初始化
首先,使用一些必需字段初始化sslcommerz SDK。
Sslcommerz sslcommerz = Sslcommerz(
initializer: SSLCommerzInitialization(
// ipn_url: "www.ipnurl.com", // 如果有有效的IPN URL,请填写,否则交易会失败
multi_card_name: "visa,master,bkash",
currency: SSLCurrencyType.BDT,
product_category: "Food",
sdkType: SSLCSdkType.TESTBOX, // 使用TESTBOX或LIVE
store_id: "your_store_id",
store_passwd: "your_store_password",
total_amount: "payment_amount",
tran_id: "custom_transaction_id"));
自定义支付
根据您的业务需求,可以添加以下信息:
添加EMI选项:
sslcommerz.addEMITransactionInitializer(
sslcemiTransactionInitializer: SSLCEMITransactionInitializer(
emi_options: 1));
添加配送信息:
sslcommerz.addShipmentInfoInitializer(
sslcShipmentInfoInitializer: SSLCShipmentInfoInitializer(
shipmentMethod: "yes",
numOfItems: 5,
shipmentDetails: ShipmentDetails(
shipAddress1: "Ship address 1",
shipCity: "Faridpur",
shipCountry: "Bangladesh",
shipName: "Ship name 1",
shipPostCode: "7860")));
添加客户信息:
sslcommerz.addCustomerInfoInitializer(
customerInfoInitializer: SSLCCustomerInfoInitializer(
customerState: "Chattogram",
customerName: "Abu Sayed Chowdhury",
customerEmail: "sayem227@gmail.com",
customerAddress1: "Chattogram",
customerCity: "Chattogram",
customerPostCode: "200",
customerCountry: "Bangladesh",
customerPhone: formData['phone']));
添加产品信息:
通用产品:
sslcommerz.addProductInitializer(
sslcProductInitializer:
SSLCProductInitializer(
productName: "Water Filter",
productCategory: "Widgets",
general: General(
general: "General Purpose",
productProfile: "Product Profile")));
非实体商品:
sslcommerz.addProductInitializer(
sslcProductInitializer:
SSLCProductInitializer.WithNonPhysicalGoodsProfile(
productName: "productName",
productCategory:"productCategory",
nonPhysicalGoods:
NonPhysicalGoods(productProfile: "Product profile",
nonPhysicalGoods:"non physical good"
)));
旅行类商品:
sslcommerz.addProductInitializer(
sslcProductInitializer:
SSLCProductInitializer.WithTravelVerticalProfile(
productName:"productName",
productCategory:"productCategory",
travelVertical:TravelVertical(
productProfile: "productProfile",
hotelName: "hotelName",
lengthOfStay: "lengthOfStay",
checkInTime: "checkInTime",
hotelCity: "hotelCity"
)));
电信类商品:
sslcommerz.addProductInitializer(
sslcProductInitializer:
SSLCProductInitializer.WithTelecomVerticalProfile(
productName: "productName",
productCategory: "productCategory",
telecomVertical: TelecomVertical(
productProfile: "productProfile",
productType: "productType",
topUpNumber: "topUpNumber",
countryTopUp: "countryTopUp"
)));
添加可选参数
sslcommerz.addAdditionalInitializer(
sslcAdditionalInitializer: SSLCAdditionalInitializer(
valueA: "value a ",
valueB: "value b",
valueC: "value c",
valueD: "value d"));
然后,调用sslcommerz.payNow();
来启动SDK完成支付过程。
完整示例代码
// ignore_for_file: deprecated_member_use
import 'package:flutter/material.dart';
import 'package:flutter_sslcommerz/model/SSLCAdditionalInitializer.dart';
import 'package:flutter_sslcommerz/model/SSLCCustomerInfoInitializer.dart';
import 'package:flutter_sslcommerz/model/SSLCEMITransactionInitializer.dart';
import 'package:flutter_sslcommerz/model/SSLCSdkType.dart';
import 'package:flutter_sslcommerz/model/SSLCShipmentInfoInitializer.dart';
import 'package:flutter_sslcommerz/model/SSLCTransactionInfoModel.dart';
import 'package:flutter_sslcommerz/model/SSLCommerzInitialization.dart';
import 'package:flutter_sslcommerz/model/SSLCurrencyType.dart';
import 'package:flutter_sslcommerz/sslcommerz.dart';
import 'package:fluttertoast/fluttertoast.dart';
enum SdkType { LIVE, TESTBOX }
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: SSLCommerzScreen(),
);
}
}
class SSLCommerzScreen extends StatefulWidget {
[@override](/user/override)
_SSLCommerzScreenState createState() => _SSLCommerzScreenState();
}
class _SSLCommerzScreenState extends State<SSLCommerzScreen> {
final _formKey = GlobalKey<FormState>();
final Map<String, dynamic> _formData = {};
SdkType _sdkType = SdkType.LIVE;
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('SSLCommerz')),
body: SingleChildScrollView(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
children: [
_buildTextField(
label: "Store ID",
initialValue: "demotest",
onSaved: (value) => _formData['store_id'] = value,
validator: _validateNotEmpty),
_buildTextField(
label: "Store Password",
initialValue: "qwerty",
onSaved: (value) => _formData['store_password'] = value,
validator: _validateNotEmpty),
_buildRadioButtons(),
_buildTextField(
label: "Phone Number",
keyboardType: TextInputType.phone,
onSaved: (value) => _formData['phone'] = value),
_buildTextField(
label: "Payment Amount",
initialValue: "10",
keyboardType: TextInputType.numberWithOptions(decimal: true),
onSaved: (value) =>
_formData['amount'] = double.tryParse(value ?? '0'),
validator: _validateNotEmpty),
_buildTextField(
label: "Enter Multi Card",
onSaved: (value) => _formData['multicard'] = value),
ElevatedButton(
child: Text("Pay now"),
onPressed: _onPayNowPressed,
),
],
),
),
),
);
}
Widget _buildTextField(
{required String label,
String? initialValue,
TextInputType keyboardType = TextInputType.text,
FormFieldSetter<String>? onSaved,
FormFieldValidator<String>? validator}) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
initialValue: initialValue,
keyboardType: keyboardType,
decoration: InputDecoration(
border: OutlineInputBorder(borderRadius: BorderRadius.circular(8.0)),
hintText: label,
),
onSaved: onSaved,
validator: validator,
),
);
}
Widget _buildRadioButtons() {
return Row(
children: [
_buildRadio(SdkType.TESTBOX, "TESTBOX"),
_buildRadio(SdkType.LIVE, "LIVE"),
],
);
}
Widget _buildRadio(SdkType type, String label) {
return Row(
children: [
Radio(
value: type,
groupValue: _sdkType,
activeColor: Colors.blue,
onChanged: (value) {
setState(() => _sdkType = value as SdkType);
},
),
Text(label),
],
);
}
String? _validateNotEmpty(String? value) {
return (value == null || value.isEmpty) ? "Please input value" : null;
}
Future<void> _onPayNowPressed() async {
if (_formKey.currentState != null && _formKey.currentState!.validate()) {
_formKey.currentState!.save();
_startSSLCommerzTransaction();
}
}
Future<void> _startSSLCommerzTransaction() async {
Sslcommerz sslcommerz = Sslcommerz(
initializer: SSLCommerzInitialization(
ipn_url: "www.ipnurl.com",
multi_card_name: _formData['multicard'],
currency: SSLCurrencyType.BDT,
product_category: "Food",
sdkType: _sdkType == SdkType.TESTBOX
? SSLCSdkType.TESTBOX
: SSLCSdkType.LIVE,
store_id: _formData['store_id'],
store_passwd: _formData['store_password'],
total_amount: _formData['amount'],
tran_id: "1231123131212",
),
);
sslcommerz
.addShipmentInfoInitializer(
sslcShipmentInfoInitializer: SSLCShipmentInfoInitializer(
shipmentMethod: "yes",
numOfItems: 5,
shipmentDetails: ShipmentDetails(
shipAddress1: "Ship address 1",
shipCity: "Faridpur",
shipCountry: "Bangladesh",
shipName: "Ship name 1",
shipPostCode: "7860"),
),
)
.addCustomerInfoInitializer(
customerInfoInitializer: SSLCCustomerInfoInitializer(
customerState: "Chattogram",
customerName: "Abu Sayed Chowdhury",
customerEmail: "abc@gmail.com",
customerAddress1: "Anderkilla",
customerCity: "Chattogram",
customerPostCode: "200",
customerCountry: "Bangladesh",
customerPhone: _formData['phone'],
),
)
.addEMITransactionInitializer(
sslcemiTransactionInitializer: SSLCEMITransactionInitializer(
emi_options: 1, emi_max_list_options: 9, emi_selected_inst: 0))
.addAdditionalInitializer(
sslcAdditionalInitializer: SSLCAdditionalInitializer(
valueA: "value a",
valueB: "value b",
valueC: "value c",
valueD: "value d",
extras: {"key": "key", "key2": "key2"},
),
);
SSLCTransactionInfoModel result = await sslcommerz.payNow();
_displayPaymentStatus(result);
}
void _displayPaymentStatus(SSLCTransactionInfoModel result) {
String message;
Color bgColor;
switch (result.status?.toLowerCase()) {
case "failed":
message = "Transaction Failed";
bgColor = Colors.red;
break;
case "closed":
message = "SDK Closed by User";
bgColor = Colors.orange;
break;
default:
message =
"Transaction ${result.status} - Amount: ${result.amount ?? 0}";
bgColor = Colors.green;
}
Fluttertoast.showToast(
msg: message,
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
backgroundColor: bgColor,
textColor: Colors.white,
fontSize: 16.0,
);
}
}
更多关于Flutter支付集成插件flutter_sslcommerz的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter支付集成插件flutter_sslcommerz的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter中集成支付插件flutter_sslcommerz
,可以实现对SSLCommerz支付网关的支持。以下是一个简单的代码示例,展示如何在Flutter应用中集成并使用flutter_sslcommerz
插件。
首先,确保你已经在pubspec.yaml
文件中添加了flutter_sslcommerz
依赖:
dependencies:
flutter:
sdk: flutter
flutter_sslcommerz: ^最新版本号 # 替换为实际的最新版本号
然后,运行flutter pub get
来安装依赖。
接下来,在你的Flutter应用中,你可以按照以下步骤来初始化并使用SSLCommerz支付。
- 导入包:
import 'package:flutter_sslcommerz/flutter_sslcommerz.dart';
- 配置SSLCommerz:
在应用的初始化部分(例如在main.dart
中),配置SSLCommerz:
void main() {
WidgetsFlutterBinding.ensureInitialized();
// 配置SSLCommerz
FlutterSslCommerz.instance.configure(
apiKey: '你的API_KEY', // 替换为你的API密钥
storeId: '你的STORE_ID', // 替换为你的商店ID
secretKey: '你的SECRET_KEY', // 替换为你的密钥
isSandbox: true, // 如果是测试环境,设置为true;生产环境设置为false
);
runApp(MyApp());
}
- 发起支付请求:
在你的支付页面上,创建一个按钮来触发支付流程,并处理支付结果。
import 'package:flutter/material.dart';
import 'package:flutter_sslcommerz/flutter_sslcommerz.dart';
class PaymentScreen extends StatefulWidget {
@override
_PaymentScreenState createState() => _PaymentScreenState();
}
class _PaymentScreenState extends State<PaymentScreen> {
void _initiatePayment() async {
try {
var response = await FlutterSslCommerz.instance.startPayment(
amount: 100.00, // 支付金额
currency: 'BDT', // 货币类型
transactionId: 'unique_transaction_id_${DateTime.now().millisecondsSinceEpoch}', // 交易ID,需要唯一
successUrl: 'https://yourapp.com/success', // 支付成功后的回调URL
failUrl: 'https://yourapp.com/fail', // 支付失败后的回调URL
customer: Customer(
name: 'John Doe',
email: 'john.doe@example.com',
phone: '01xxxxxxxxx',
address: '123 Main St',
),
shipping: Shipping(
name: 'John Doe',
email: 'john.doe@example.com',
phone: '01xxxxxxxxx',
address: '123 Main St',
),
productList: [
Product(
name: 'Product Name',
quantity: 1,
price: 100.00,
productId: 'product_123',
),
],
);
if (response.status == 'success') {
// 支付成功后的处理逻辑
print('Payment successful');
} else {
// 支付失败后的处理逻辑
print('Payment failed: ${response.message}');
}
} catch (e) {
// 错误处理
print('Error initiating payment: $e');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Payment Screen'),
),
body: Center(
child: ElevatedButton(
onPressed: _initiatePayment,
child: Text('Initiate Payment'),
),
),
);
}
}
class Customer {
String name;
String email;
String phone;
String address;
Customer({
required this.name,
required this.email,
required this.phone,
required this.address,
});
}
class Shipping {
String name;
String email;
String phone;
String address;
Shipping({
required this.name,
required this.email,
required this.phone,
required this.address,
});
}
class Product {
String name;
int quantity;
double price;
String productId;
Product({
required this.name,
required this.quantity,
required this.price,
required this.productId,
});
}
注意:
- 在实际应用中,请确保所有个人和交易信息的安全性。
- 替换示例代码中的API密钥、商店ID、回调URL等信息为你的实际值。
- 根据你的应用需求,调整支付页面和支付逻辑。
以上代码提供了一个基本的集成框架,你可以根据SSLCommerz的文档和API要求进一步定制和扩展功能。