/
main.dart
541 lines (502 loc) · 18.2 KB
/
main.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
import 'dart:async';
import 'dart:convert';
import 'dart:developer';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_paystack_payment/flutter_paystack_payment.dart';
import 'package:http/http.dart' as http;
// To get started quickly, change this to your heroku deployment of
// https://github.com/PaystackHQ/sample-charge-card-backend
// Step 1. Visit https://github.com/PaystackHQ/sample-charge-card-backend
// Step 2. Click "Deploy to heroku"
// Step 3. Login with your heroku credentials or create a free heroku account
// Step 4. Provide your secret key and an email with which to start all test transactions
// Step 5. Replace {YOUR_BACKEND_URL} below with the url generated by heroku (format https://some-url.herokuapp.com)
String backendUrl = '{YOUR_BACKEND_URL}';
// Set this to a public key that matches the secret key you supplied while creating the heroku instance
String paystackPublicKey = 'pk_live_bba533691a6907c84d78a5c54a2133bdd430f445';
const String appName = 'Paystack Example';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: appName,
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final _scaffoldKey = GlobalKey<ScaffoldState>();
final _formKey = GlobalKey<FormState>();
final _verticalSizeBox = const SizedBox(height: 20.0);
final _horizontalSizeBox = const SizedBox(width: 10.0);
final plugin = PaystackPayment();
final _border = Container(
width: double.infinity,
height: 1.0,
color: Colors.red,
);
int _radioValue = 0;
CheckoutMethod _method = CheckoutMethod.selectable;
bool _inProgress = false;
String? _cardNumber;
String? _cvv;
int? _expiryMonth;
int? _expiryYear;
@override
void initState() {
plugin.initialize(publicKey: paystackPublicKey);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(title: const Text(appName)),
body: Container(
padding: const EdgeInsets.all(20.0),
child: Form(
key: _formKey,
child: SingleChildScrollView(
child: ListBody(
children: <Widget>[
Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
const Expanded(
child: Text('Initalize transaction from:'),
),
Expanded(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
RadioListTile<int>(
value: 0,
groupValue: _radioValue,
onChanged: _handleRadioValueChanged,
title: const Text('Local'),
),
RadioListTile<int>(
value: 1,
groupValue: _radioValue,
onChanged: _handleRadioValueChanged,
title: const Text('Server'),
),
]),
)
],
),
_border,
_verticalSizeBox,
TextFormField(
decoration: const InputDecoration(
border: UnderlineInputBorder(),
labelText: 'Card number',
),
onSaved: (String? value) => _cardNumber = value,
),
_verticalSizeBox,
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expanded(
child: TextFormField(
decoration: const InputDecoration(
border: UnderlineInputBorder(),
labelText: 'CVV',
),
onSaved: (String? value) => _cvv = value,
),
),
_horizontalSizeBox,
Expanded(
child: TextFormField(
decoration: const InputDecoration(
border: UnderlineInputBorder(),
labelText: 'Expiry Month',
),
onSaved: (String? value) =>
_expiryMonth = int.tryParse(value ?? ""),
),
),
_horizontalSizeBox,
Expanded(
child: TextFormField(
decoration: const InputDecoration(
border: UnderlineInputBorder(),
labelText: 'Expiry Year',
),
onSaved: (String? value) =>
_expiryYear = int.tryParse(value ?? ""),
),
)
],
),
_verticalSizeBox,
Theme(
data: Theme.of(context).copyWith(
primaryColorLight: Colors.white,
primaryColorDark: navyBlue,
textTheme: Theme.of(context).textTheme.copyWith(
bodyMedium: const TextStyle(
color: lightBlue,
),
),
colorScheme:
ColorScheme.fromSwatch().copyWith(secondary: green),
),
child: Builder(
builder: (context) {
return _inProgress
? Container(
alignment: Alignment.center,
height: 50.0,
child: kIsWeb
? const CircularProgressIndicator()
: Platform.isIOS
? const CupertinoActivityIndicator()
: const CircularProgressIndicator(),
)
: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
_getPlatformButton(
'Charge Card', () => _startAfreshCharge()),
_verticalSizeBox,
_border,
const SizedBox(
height: 40.0,
),
Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Flexible(
flex: 3,
child: DropdownButtonHideUnderline(
child: InputDecorator(
decoration: const InputDecoration(
border: OutlineInputBorder(),
isDense: true,
hintText: 'Checkout method',
),
child: DropdownButton<CheckoutMethod>(
value: _method,
isDense: true,
onChanged: (CheckoutMethod? value) {
if (value != null) {
setState(() => _method = value);
}
},
items: banks.map((String value) {
return DropdownMenuItem<
CheckoutMethod>(
value:
_parseStringToMethod(value),
child: Text(value),
);
}).toList(),
),
),
),
),
_horizontalSizeBox,
Flexible(
flex: 2,
child: SizedBox(
width: double.infinity,
child: _getPlatformButton(
'Checkout',
() => _handleCheckout(context),
),
),
),
],
)
],
);
},
),
)
],
),
),
),
),
);
}
void _handleRadioValueChanged(int? value) {
if (value != null) setState(() => _radioValue = value);
}
_handleCheckout(BuildContext? context) async {
if (_method != CheckoutMethod.card && _isLocal) {
_showMessage('Select server initialization method at the top');
return;
}
setState(() => _inProgress = true);
_formKey.currentState?.save();
Charge charge = Charge()
..amount = 20 * 100 // In base currency
..email = 'customer@email.com'
..card = _getCardFromUI();
if (!_isLocal) {
var accessCode = await _fetchAccessCodeFrmServer(_getReference());
charge.accessCode = accessCode;
} else {
charge.reference = _getReference();
}
try {
CheckoutResponse response = await plugin.checkout(
context!,
method: _method,
charge: charge,
fullscreen: false,
logo: const MyLogo(),
);
log('Response = $response');
setState(() => _inProgress = false);
_updateStatus(response.reference, '$response');
} catch (e) {
setState(() => _inProgress = false);
_showMessage("Check console for error");
rethrow;
}
}
_startAfreshCharge() async {
_formKey.currentState?.save();
Charge charge = Charge();
charge.card = _getCardFromUI();
setState(() => _inProgress = true);
if (_isLocal) {
// Set transaction params directly in app (note that these params
// are only used if an access_code is not set. In debug mode,
// setting them after setting an access code would throw an exception
charge
..amount = 20 * 100 // In base currency
..email = 'customer@email.com'
..reference = _getReference()
..putCustomField('Charged From', 'Flutter SDK');
// _getReference();
log(charge.reference!);
_chargeCard(charge, scanCard: true);
} else {
// Perform transaction/initialize on Paystack server to get an access code
// documentation: https://developers.paystack.co/reference#initialize-a-transaction
charge.accessCode = await _fetchAccessCodeFrmServer(_getReference());
_chargeCard(charge, scanCard: true);
}
}
_chargeCard(Charge charge, {required bool scanCard}) async {
final response =
await plugin.chargeCard(context, charge: charge, scanCard: scanCard);
log(response.reference!);
final reference = response.reference;
// Checking if the transaction is successful
if (response.status) {
_verifyOnServer(reference);
return;
}
// The transaction failed. Checking if we should verify the transaction
if (response.verify) {
_verifyOnServer(reference);
} else {
setState(() => _inProgress = false);
_updateStatus(reference, response.message);
}
}
String _getReference() {
String platform;
if (!kIsWeb) {
if (Platform.isIOS) {
platform = 'iOS';
} else if (Platform.isLinux) {
platform = 'Linux';
} else if (Platform.isMacOS) {
platform = 'MacOS';
} else if (Platform.isFuchsia) {
platform = 'Fuchsia';
} else if (Platform.isWindows) {
platform = 'Windows';
} else {
platform = 'Android';
}
// platform = 'Unknown';
} else {
platform = "WEB";
}
return 'ChargedFrom${platform}_${DateTime.now().millisecondsSinceEpoch}';
}
PaymentCard _getCardFromUI() {
// Using just the must-required parameters.
return PaymentCard(
number: _cardNumber,
cvc: _cvv,
expiryMonth: _expiryMonth,
expiryYear: _expiryYear,
);
// Using Cascade notation (similar to Java's builder pattern)
// return PaymentCard(
// number: cardNumber,
// cvc: cvv,
// expiryMonth: expiryMonth,
// expiryYear: expiryYear)
// ..name = 'Segun Chukwuma Adamu'
// ..country = 'Nigeria'
// ..addressLine1 = 'Ikeja, Lagos'
// ..addressPostalCode = '100001';
// Using optional parameters
// return PaymentCard(
// number: cardNumber,
// cvc: cvv,
// expiryMonth: expiryMonth,
// expiryYear: expiryYear,
// name: 'Ismail Adebola Emeka',
// addressCountry: 'Nigeria',
// addressLine1: '90, Nnebisi Road, Asaba, Deleta State');
}
Widget _getPlatformButton(String string, Function() function) {
// is still in progress
Widget widget;
if (!kIsWeb) {
if (Platform.isIOS) {
widget = CupertinoButton(
onPressed: function,
padding: const EdgeInsets.symmetric(horizontal: 15.0),
color: CupertinoColors.activeBlue,
child: Text(
string,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
);
return widget;
} else {
widget = ElevatedButton(
onPressed: function,
child: Text(
string.toUpperCase(),
style: const TextStyle(fontSize: 17.0),
),
);
return widget;
}
} else {
widget = ElevatedButton(
onPressed: function,
child: Text(
string.toUpperCase(),
style: const TextStyle(fontSize: 17.0),
),
);
return widget;
}
}
Future<String?> _fetchAccessCodeFrmServer(String reference) async {
String url = 'https://sdgfortb.herokuapp.com/paystack/new-access-code';
String? accessCode;
try {
log("Access code url = $url");
http.Response response = await http.post(Uri.parse(url),
headers: {"Content-Type": "application/json"},
body: json.encode({
"email": "oreofesolarin@gmail.com",
"amount": 1000000,
// "reference": reference
}));
accessCode = response.body;
log('Response for access code = $accessCode');
} catch (e) {
setState(() => _inProgress = false);
_updateStatus(
reference,
'There was a problem getting a new access code form'
' the backend: $e');
}
return accessCode;
}
void _verifyOnServer(String? reference) async {
var head = {
"Authorization":
"Bearer sk_live_23f9d7b1689c5f7630e364b80359ae5cf730b2b1", // TODO Remove sensitive data
};
_updateStatus(reference, 'Verifying...');
String url = 'https://api.paystack.co/transaction/verify/$reference';
try {
http.Response response = await http.get(Uri.parse(url), headers: head);
var body = response.body;
_updateStatus(reference, body);
} catch (e) {
_updateStatus(
reference,
'There was a problem verifying %s on the backend: '
'$reference $e');
}
setState(() => _inProgress = false);
}
_updateStatus(String? reference, String message) {
_showMessage('Reference: $reference \n Response: $message',
const Duration(seconds: 7));
}
_showMessage(String message,
[Duration duration = const Duration(seconds: 4)]) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(message),
duration: duration,
action: SnackBarAction(
label: 'CLOSE',
onPressed: () =>
ScaffoldMessenger.of(context).removeCurrentSnackBar()),
));
}
bool get _isLocal => _radioValue == 0;
}
var banks = ['Selectable', 'Bank', 'Card'];
CheckoutMethod _parseStringToMethod(String string) {
CheckoutMethod method = CheckoutMethod.selectable;
switch (string) {
case 'Bank':
method = CheckoutMethod.bank;
break;
case 'Card':
method = CheckoutMethod.card;
break;
}
return method;
}
class MyLogo extends StatelessWidget {
const MyLogo({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: Colors.black,
),
alignment: Alignment.center,
padding: const EdgeInsets.all(10),
child: const Text(
"CO",
style: TextStyle(
color: Colors.white,
fontSize: 13,
fontWeight: FontWeight.bold,
),
),
);
}
}
const Color green = Color(0xFF3db76d);
const Color lightBlue = Color(0xFF34a5db);
const Color navyBlue = Color(0xFF031b33);