Skip to content

Commit

Permalink
merge with payway v2
Browse files Browse the repository at this point in the history
  • Loading branch information
kechankrisna committed Nov 23, 2021
1 parent 4942f27 commit 5fd971f
Show file tree
Hide file tree
Showing 14 changed files with 194 additions and 72 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@

.packages
.pub/

*.env
build/
9 changes: 5 additions & 4 deletions example/lib/config.dart
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import 'package:aba_payment/aba_payment.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';

final ABAMerchant merchant = ABAMerchant(
merchantID: "mylekha",
merchantApiName: "pwmylekham",
merchantApiKey: "cea2a8308c634a458b983def9303781f",
baseApiUrl: "https://checkout-uat.payway.com.kh",
merchantID: dotenv.get('ABA_PAYWAY_MERCHANT_ID'),
merchantApiName: dotenv.get('ABA_PAYWAY_MERCHANT_NAME'),
merchantApiKey: dotenv.get('ABA_PAYWAY_API_KEY'),
baseApiUrl: dotenv.get('ABA_PAYWAY_API_URL'),
refererDomain: "https://mylekha.app",
);
5 changes: 4 additions & 1 deletion example/lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'screens/cart_screen.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';

void main() {
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await dotenv.load(fileName: ".env");
runApp(MyApp());
}

Expand Down
25 changes: 11 additions & 14 deletions example/lib/screens/cart_screen.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import 'package:aba_payment/aba_payment.dart';
import 'package:aba_payment/service/aba_client_helper.dart';
import 'package:aba_payment_example/models/item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import '../config.dart';
Expand All @@ -13,15 +11,15 @@ class CartScreen extends StatefulWidget {
class _CartScreenState extends State<CartScreen> {
bool _isLoading = false;
ABAMerchant _merchant = merchant;

double _total = 6.00;
double _shipping = 0.0;
String _firstname = "Miss";
String _lastname = "My Lekha";
String _phone = "010464144";
String _email = "[email protected]";
String _checkoutApiUrl = "http://127.0.0.1:8000/api/v1/app/checkout_page";
List<ItemModel> _items = [];
String _checkoutApiUrl =
"http://localhost/api/v1/integrate/payway/checkout_page";
List<ABATransactionItem> _items = [];

initialize() {
if (mounted) {
Expand All @@ -32,11 +30,10 @@ class _CartScreenState extends State<CartScreen> {
_lastname = "My Lekha";
_phone = "010464144";
_email = "[email protected]";
_checkoutApiUrl = "http://127.0.0.1:8000/api/v1/app/checkout_page";
_items = [
// ItemModel(name: "item 1", price: 1.00, quantity: 1),
// ItemModel(name: "item 2", price: 2.00, quantity: 2),
// ItemModel(name: "item 3", price: 3.00, quantity: 3),
ABATransactionItem(name: "item 1", price: 1, quantity: 1),
ABATransactionItem(name: "item 2", price: 2, quantity: 1),
ABATransactionItem(name: "item 3", price: 3, quantity: 1),
];
});
}
Expand All @@ -62,7 +59,7 @@ class _CartScreenState extends State<CartScreen> {
..._items.map(
(item) => ListTile(
title: Text("${item.name}"),
subtitle: Text("price: x${item.price}"),
subtitle: Text("price: x${item.price}\$"),
trailing: Text("${item.quantity}"),
),
),
Expand All @@ -77,7 +74,7 @@ class _CartScreenState extends State<CartScreen> {
lastname: _lastname,
email: _email,
phone: _phone,
items: [..._items.map((e) => e.toMap()).toList()],
items: _items,
checkoutApiUrl: _checkoutApiUrl,
merchant: _merchant,
onBeginCheckout: (transaction) {
Expand All @@ -103,9 +100,9 @@ class _CartScreenState extends State<CartScreen> {
// onPaymentFail: (transaction) {
// print("onPaymentFail ${transaction.toMap()}");
// },
// onPaymentSuccess: (transaction) {
// print("onPaymentSuccess ${transaction.toMap()}");
// },
onPaymentSuccess: (transaction) {
print("onPaymentSuccess ${transaction.toMap()}");
},
),
],
),
Expand Down
7 changes: 7 additions & 0 deletions example/pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,13 @@ packages:
description: flutter
source: sdk
version: "0.0.0"
flutter_dotenv:
dependency: "direct main"
description:
name: flutter_dotenv
url: "https://pub.dartlang.org"
source: hosted
version: "5.0.2"
flutter_easyloading:
dependency: "direct main"
description:
Expand Down
6 changes: 3 additions & 3 deletions example/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ dependencies:
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
flutter_dotenv: ^5.0.2

dev_dependencies:
flutter_test:
Expand All @@ -41,9 +42,8 @@ flutter:
uses-material-design: true

# To add assets to your application, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
assets:
- .env

# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
Expand Down
1 change: 1 addition & 0 deletions lib/model.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export './model/aba_mechant.dart';
export './model/aba_transaction.dart';
export './model/aba_transacition_item.dart';
export './model/aba_server_response.dart';
export './model/aba_payment.dart';
2 changes: 1 addition & 1 deletion lib/model/aba_server_response.dart
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class ABAServerResponse {

factory ABAServerResponse.fromMap(Map<String, dynamic> map) {
return ABAServerResponse(
status: int.tryParse("${map["status"]}"),
status: map["status"] is int ? map["status"] : -1,
description: map["description"],
qrString: map["qrString"],
qrImage: map["qrImage"],
Expand Down
35 changes: 35 additions & 0 deletions lib/model/aba_transacition_item.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
class ABATransactionItem {
String name;
double quantity;
double price;

ABATransactionItem({this.name, this.quantity, this.price});

factory ABATransactionItem.fromMap(Map<String, dynamic> map) {
return ABATransactionItem(
name: map["name"],
quantity: double.tryParse("${map["quantity"]}"),
price: double.tryParse("${map["price"]}"),
);
}

copyWith({
String name,
double quantity,
double price,
}) {
return ABATransactionItem(
name: name ?? this.name,
quantity: quantity ?? this.quantity,
price: price ?? this.price,
);
}

Map<String, dynamic> toMap() {
return {
"name": name,
"quantity": quantity,
"price": price,
};
}
}
92 changes: 59 additions & 33 deletions lib/model/aba_transaction.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import 'package:aba_payment/enumeration.dart';
import 'package:aba_payment/extension.dart';
import 'package:aba_payment/model/aba_mechant.dart';
import 'package:aba_payment/model/aba_payment.dart';
import 'package:aba_payment/model/aba_transacition_item.dart';
import 'package:aba_payment/service/aba_client_helper.dart';
import 'package:dio/dio.dart';
import 'package:intl/intl.dart';
Expand All @@ -12,10 +13,9 @@ import 'aba_server_response.dart';

class ABATransaction {
ABAMerchant merchant;
String reqTime;
String tranID;
double amount;
List<Map<String, dynamic>> items;
List<ABATransactionItem> items;
String hash;
String firstname;
String lastname;
Expand All @@ -29,10 +29,11 @@ class ABATransaction {
AcceptPaymentOption paymentOption;
double shipping;

String get reqTime => "${DateFormat("yMddHms").format(DateTime.now())}";

ABATransaction({
this.merchant,
this.tranID,
this.reqTime,
this.amount,
this.items,
this.hash,
Expand All @@ -53,7 +54,6 @@ class ABATransaction {
// var format = DateFormat("yMddHms").format(DateTime.now()); //2021 01 23 234559 OR 2021 11 07 132947
return ABATransaction(
merchant: merchant,
reqTime: "${DateFormat("yMddHms").format(DateTime.now())}",
tranID: "${(DateTime.now()).microsecondsSinceEpoch}",
amount: 0.00,
items: [],
Expand All @@ -70,10 +70,11 @@ class ABATransaction {
factory ABATransaction.fromMap(Map<String, dynamic> map) {
return ABATransaction(
merchant: ABAMerchant.fromMap(map),
reqTime: map['req_time'],
tranID: map["tran_id"],
amount: double.tryParse("${map["amount"]}"),
items: List.from(map['items'] ?? []).map((e) => Map.from(e)).toList(),
items: List.from(map['items'] ?? [])
.map((e) => ABATransactionItem.fromMap(e))
.toList(),
hash: map["hash"],
firstname: map["firstname"],
lastname: map["lastname"],
Expand All @@ -89,69 +90,84 @@ class ABATransaction {
);
}

double get totalPrice {
double result = 0;
this.items.fold(result, (pre, e) => result += e.price * e.quantity);
return result;
}

/// ### [toMap]
/// [return] map object
Map<String, dynamic> toMap() {
String _items =
items?.isNotEmpty == true ? base64Encode(utf8.encode("$items")) : "";
var currency = "USD";
var _shipping = "0.00";
var type = "purchase";
String _encodedItem = "";
if (this.items?.isNotEmpty == true) {
if (this.amount != this.totalPrice) {
ABAPayment.logger
.error("amount $amount is not equal totalPrice $totalPrice");
}
var itemText = [...this.items.map((e) => e.toMap()).toList()];
_encodedItem = base64Encode(json.encode(itemText).runes.toList());
// _encodedItem = "W3sibmFtZSI6InRlc3QiLCJxdWFudGl0eSI6MSwicHJpY2UiOjZ9XQ==";
ABAPayment.logger.info("itemText $itemText");
ABAPayment.logger.info("_encodedItem $_encodedItem");
}
var _currency = "USD";
var _type = "purchase";
String _hash = ABAClientHelper(merchant).getHash(
reqTime: reqTime,
tranID: tranID,
amount: "$amount",
items: _items,
shipping: "$_shipping",
items: _encodedItem,
shipping: "$shipping",
firstName: firstname,
lastName: lastname,
email: email,
phone: phone,
type: type,
type: _type,
paymentOption: paymentOption.toText,
currency: currency,
currency: _currency,
);
ABAPayment.logger.info("req_time $reqTime");
ABAPayment.logger.info("tran_id $tranID");
ABAPayment.logger.info("_hash $_hash");
ABAPayment.logger.info("_items $_items");
ABAPayment.logger.info("amount $amount");
var map = {
"req_time": reqTime,
"tran_id": tranID,
"amount": "$amount",
// "items": "$_items",
"items": "$_encodedItem",
"hash": "$_hash",
"firstname": "$firstname",
"lastname": "$lastname",
"phone": "$phone",
"email": "$email",
// "return_url": returnUrl,
// "continue_success_url": continueSuccessUrl ?? "",
// "return_params": returnParams ?? "",
"return_url": returnUrl,
"continue_success_url": continueSuccessUrl ?? "",
"return_params": returnParams ?? "",
// "return_params": {"tran_id": tranID, "status": 0},
// "phone_country_code": phoneCountryCode ?? "855",
// "PreAuth": preAuth,
"payment_option": "${paymentOption.toText}",
"shipping": "$_shipping",
"currency": "$currency",
"shipping": "$shipping",
"currency": "$_currency",
"merchant_id": "${merchant.merchantID}",
"type": type,
"type": _type,
};
return map;
}

/// ## `create transaction`
///
/// ## [create]
/// create a new trasaction
Future<ABAServerResponse> create() async {
var res = ABAServerResponse(status: 11);
Map<String, dynamic> map = this.toMap();
map["type"] = "purchase";
ABAPayment.logger.debug(map);
var formData = FormData.fromMap(map);
try {
var helper = ABAClientHelper(merchant);
var dio = helper.getDio();
Response<String> response = await dio.post("", data: formData);
Response<String> response = await dio.post("/purchase", data: formData);
// ABAPayment.logger.debug(response);
try {
var map = json.decode(response.data) as Map<String, dynamic>;
Expand All @@ -170,26 +186,36 @@ class ABATransaction {
return ABAServerResponse();
}

/// ## check transaction
///
/// ## [check]
/// check the current status of this transaction vai its id
Future<ABAServerResponse> check() async {
var res = ABAServerResponse(status: 11);
FormData form = FormData.fromMap({
"tran_id": tranID,
"hash":
ABAClientHelper(merchant).getHash(reqTime: reqTime, tranID: tranID),
});
var hash =
ABAClientHelper(merchant).getHash(reqTime: reqTime, tranID: tranID);
FormData form = FormData.fromMap({"tran_id": tranID, "hash": hash});
var helper = ABAClientHelper(merchant);
try {
Response<String> response =
await helper.getDio().post("/check-transaction", data: form);
var map = json.decode(response.data) as Map<String, dynamic>;
ABAPayment.logger.error("checkMap $map");
res = ABAServerResponse.fromMap(map);
if (res.status != 0) {
res.description = ABAClientHelper.handleTransactionResponse(res.status);
}
return res;
} catch (error, stacktrace) {
print("Exception occured: $error stackTrace: $stacktrace");
res.description = ABAClientHelper.handleResponseError(error);
}
return ABAServerResponse();
}

/// ## [validate]
/// will return true if transaction completed
/// otherwise false
Future<bool> validate() async {
var result = await this.check();
return (result?.status == 0);
}
}
Loading

0 comments on commit 5fd971f

Please sign in to comment.