tuna_sdk 0.1.0 tuna_sdk: ^0.1.0 copied to clipboard
Tuna Gateway SDK.
// ignore_for_file: avoid_print
import 'package:flutter/material.dart';
import 'package:tuna_sdk/tuna_sdk.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:dio/dio.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final Dio _dio = Dio();
late final ThreeDS _threeDS;
late final String _sessionid;
late final Tuna _tuna;
//-------------// Edit this data //-------------//
final String _env = "prod";
final CustomerData _customer = CustomerData("14", "test@tuna.uy");
final String _partnerUniqueId = "666";
final CardData _cardData = CardData(cardNumber: "xxxx", cardHolderName: "Card Holder", expirationMonth: 3, expirationYear: 2032, cvv: "200");
//Sensible data
final String _appToken = "xxxxxx";
final String _account = "xxxxxxx";
//Sensible data
//-------------// Edit this data //-------------//
Future<void> startPaymentTransaction() async {
_tuna = await Tuna.create(_appToken, _account, _customer, _partnerUniqueId, env: _env);
_sessionid = _tuna.sessionID;
var generateResponse = await _tuna.tokenizer.generate(_cardData);
_threeDS = ThreeDS(
(message) async {
if (message == "Data collection ready") {
var initResponse = await callInit(generateResponse, _cardData);
var threeDSInfo = ThreeDSInfo.fromJson(initResponse["methods"][0]["threeDSInfo"]);
_threeDS.loadChallengeFrame(threeDSInfo);
_tuna.doStatusLongPolling((statusPollResult) {
if (statusPollResult.code == 1) {
if (statusPollResult.paymentMethodConfirmed) {
if (statusPollResult.paymentApproved ?? false) {
print("Payment approved!");
} else {
print("Payment refused");
}
} else {
print("Error");
}
} else {
print("Error");
}
}, initResponse["methods"][0]["methodId"], initResponse["paymentKey"]);
}
},
);
_threeDS.loadDataCollectionFrame(generateResponse.authenticationInformation!.accessToken!, generateResponse.authenticationInformation!.deviceDataCollectionUrl!);
}
Future<dynamic> callInit(GenerateResponse generateResponse, CardData cardData) async {
try {
Response response = await _dio.post(
'https://engine.tunagateway.com/api/Payment/Init',
options: Options(
headers: {
'accept': 'application/json',
'x-tuna-account': _account,
'x-tuna-apptoken': _appToken,
'Content-Type': 'application/json',
'Idempotency-Key': 'YzHfUsJHm73412df',
},
),
data: {
"PartnerUniqueID": _partnerUniqueId,
"TokenSession": _sessionid,
"Customer": {"Email": _customer.email, "ID": _customer.id, "Document": "160.756.340-10", "DocumentType": "CPF"},
"FrontData": {"SessionID": "3ca3cc8ff8eac0093a4097de219f2a8c", "Origin": "WEBSITE", "IpAddress": "172.18.0.1", "CookiesAccepted": true},
"PaymentItems": {
"Items": [
{
"Amount": 10,
"ProductDescription": "Sample Product",
"ItemQuantity": 1,
"CategoryName": "simple",
"AntiFraud": {"Ean": "24-WB04"}
}
]
},
"PaymentData": {
"Countrycode": "BR",
"DeliveryAddress": {
"Street": "Sample Street",
"Number": "288",
"City": "Salvador",
"State": "BA",
"Country": "BR",
"PostalCode": "41341-545",
"Phone": "(71)999999929"
},
"SalesChannel": "ECOMMERCE",
"Amount": 10,
"PaymentMethods": [
{
"PaymentMethodType": "1",
"Amount": 10,
"Installments": 1,
"cardInfo": {
"CardNumber": cardData.cardNumber,
"CardHolderName": cardData.cardHolderName,
"BrandName": generateResponse.brand,
"ExpirationMonth": cardData.expirationMonth,
"ExpirationYear": cardData.expirationYear,
"Token": generateResponse.token,
"TokenProvider": "Tuna",
"TokenSingleUse": cardData.singleUse,
"SaveCard": !(cardData.singleUse ?? true),
"BillingInfo": {"Document": "160.756.340-10", "DocumentType": "CPF", "Address": {}}
},
"AuthenticationInformation": {
"Code": _sessionid,
"ReferenceId": generateResponse.authenticationInformation!.referenceId!,
"TransactionId": generateResponse.authenticationInformation!.transactionId!
}
}
]
}
},
);
return response.data;
} catch (error, stacktrace) {
print('Error: $error, Stacktrace: $stacktrace');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: FutureBuilder(
future: startPaymentTransaction(),
builder: (context, AsyncSnapshot<dynamic> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(),
);
} else {
if (snapshot.hasError) {
return const Center(
child: Text('Ocorreu um erro ao carregar os dados.'),
);
} else {
return WebViewWidget(controller: _threeDS.webViewController);
}
}
},
));
}
}