-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathCardFragment.java
More file actions
801 lines (681 loc) · 30.9 KB
/
CardFragment.java
File metadata and controls
801 lines (681 loc) · 30.9 KB
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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
package com.flutterwave.raveandroid.card;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.SwitchCompat;
import androidx.fragment.app.Fragment;
import com.flutterwave.raveandroid.R;
import com.flutterwave.raveandroid.RavePayActivity;
import com.flutterwave.raveandroid.RavePayInitializer;
import com.flutterwave.raveandroid.ViewObject;
import com.flutterwave.raveandroid.card.savedcards.SavedCardsActivity;
import com.flutterwave.raveandroid.card.savedcards.SavedCardsFragment;
import com.flutterwave.raveandroid.data.PhoneNumberObfuscator;
import com.flutterwave.raveandroid.data.events.FeeDisplayResponseEvent;
import com.flutterwave.raveandroid.di.modules.CardUiModule;
import com.flutterwave.raveandroid.rave_core.models.SavedCard;
import com.flutterwave.raveandroid.rave_java_commons.Payload;
import com.flutterwave.raveandroid.rave_logger.events.StartTypingEvent;
import com.flutterwave.raveandroid.rave_presentation.data.AddressDetails;
import com.flutterwave.raveandroid.rave_presentation.data.events.ErrorEvent;
import com.flutterwave.raveandroid.rave_remote.responses.SaveCardResponse;
import com.flutterwave.raveutils.verification.AVSVBVFragment;
import com.flutterwave.raveutils.verification.OTPFragment;
import com.flutterwave.raveutils.verification.PinFragment;
import com.flutterwave.raveutils.verification.RaveVerificationUtils;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import javax.inject.Inject;
import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.ADDRESS_DETAILS_REQUEST_CODE;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.MANUAL_CARD_CHARGE;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.OTP_REQUEST_CODE;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.PIN_REQUEST_CODE;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.SAVED_CARD_CHARGE;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.WEB_VERIFICATION_REQUEST_CODE;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.fieldAmount;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.fieldCardExpiry;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.fieldCvv;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.fieldEmail;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.fieldPhone;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.fieldcardNoStripped;
/**
* A simple {@link Fragment} subclass.
*/
public class CardFragment extends Fragment implements View.OnClickListener, CardUiContract.View, View.OnFocusChangeListener {
@Inject
CardUiPresenter presenter;
int chargeType = MANUAL_CARD_CHARGE;
@Inject
PhoneNumberObfuscator phoneNumberObfuscator;
private static final int FOR_SAVED_CARDS = 777;
private static final String STATE_PRESENTER_SAVEDCARDS = "presenter_saved_cards";
public static final String INTENT_SENDER = "cardFrag";
private static final String RAVEPAY = "ravepay";
private View v;
TextView useASavedCardTv;
private Button payButton;
private TextView pcidss_tv;
private AlertDialog dialog;
private TextInputLayout cvvTil;
private TextInputEditText cvvTv;
private TextInputLayout emailTil;
private TextInputLayout cardNoTil;
private TextInputEditText emailEt;
private ProgressDialog progessDialog;
private TextInputLayout amountTil;
private TextInputEditText amountEt;
private String flwRef;
private Payload payLoad;
private String authModel;
private TextInputEditText cardNoTv;
private TextInputLayout cardExpiryTil;
private TextInputEditText cardExpiryTv;
private SwitchCompat saveCardSwitch;
private FrameLayout progressContainer;
private RavePayInitializer ravePayInitializer;
private boolean shouldISaveThisCard = false;
Boolean hasSavedCards = false;
private LinearLayout saveNewCardLayout;
private EditText saveCardEmailEt;
private EditText saveCardPhoneNoEt;
private TextInputLayout saveCardEmailTil;
private TextInputLayout saveCardPhoneNoTil;
private String responseAsJsonString;
private SavedCard selectedSavedCard;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(STATE_PRESENTER_SAVEDCARDS)) {
Type savedCardsListType = new TypeToken<List<SavedCard>>() {
}.getType();
try {
presenter.savedCards = (new Gson()).fromJson(savedInstanceState.getString
(STATE_PRESENTER_SAVEDCARDS),
savedCardsListType);
} catch (Exception ignore) {
}
}
}
injectComponents();
v = inflater.inflate(R.layout.rave_sdk_fragment_card, container, false);
initializeViews();
pcidss_tv.setMovementMethod(LinkMovementMethod.getInstance());
setListeners();
initializePresenter();
return v;
}
private void injectComponents() {
if (getActivity() != null) {
((RavePayActivity) getActivity()).getRaveUiComponent()
.plus(new CardUiModule(this))
.inject(this);
}
}
private void initializePresenter() {
if (getActivity() != null) {
ravePayInitializer = ((RavePayActivity) getActivity()).getRavePayInitializer();
Log.d("okh", ravePayInitializer.isStaging() + " staging");
presenter.init(ravePayInitializer);
}
}
private void setListeners() {
cardExpiryTv.addTextChangedListener(new ExpiryWatcher());
payButton.setOnClickListener(this);
useASavedCardTv.setOnClickListener(this);
cardExpiryTv.setOnFocusChangeListener(this);
cardNoTv.setOnFocusChangeListener(this);
amountEt.setOnFocusChangeListener(this);
emailEt.setOnFocusChangeListener(this);
cvvTv.setOnFocusChangeListener(this);
saveCardSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
saveNewCardLayout.setVisibility(VISIBLE);
shouldISaveThisCard = true;
} else {
saveNewCardLayout.setVisibility(View.GONE);
shouldISaveThisCard = false;
}
}
});
}
private void onSavedCardSelected(SavedCard savedCard) {
selectedSavedCard = savedCard;
chargeType = SAVED_CARD_CHARGE;
presenter.processSavedCardTransaction(savedCard, ravePayInitializer);
}
private void initializeViews() {
progressContainer = v.findViewById(R.id.rave_progressContainer);
pcidss_tv = v.findViewById(R.id.rave_pcidss_compliant_tv);
saveCardSwitch = v.findViewById(R.id.rave_saveCardSwitch);
cardExpiryTil = v.findViewById(R.id.rave_cardExpiryTil);
cardExpiryTv = v.findViewById(R.id.rave_cardExpiryTv);
payButton = v.findViewById(R.id.rave_payButton);
cardNoTil = v.findViewById(R.id.rave_cardNoTil);
amountTil = v.findViewById(R.id.rave_amountTil);
emailTil = v.findViewById(R.id.rave_emailTil);
cardNoTv = v.findViewById(R.id.rave_cardNoTv);
amountEt = v.findViewById(R.id.rave_amountEt);
emailEt = v.findViewById(R.id.rave_emailEt);
cvvTil = v.findViewById(R.id.rave_cvvTil);
cvvTv = v.findViewById(R.id.rave_cvvTv);
useASavedCardTv = v.findViewById(R.id.rave_use_saved_card_tv);
useASavedCardTv.setVisibility(GONE);
saveCardSwitch = v.findViewById(R.id.rave_saveCardSwitch);
saveCardPhoneNoEt = v.findViewById(R.id.save_card_phoneNoTV);
saveCardEmailEt = v.findViewById(R.id.save_card_emailTv);
saveCardPhoneNoTil = v.findViewById(R.id.save_card_phoneNoTil);
saveCardEmailTil = v.findViewById(R.id.save_card_emailTil);
saveNewCardLayout = v.findViewById(R.id.rave_layout_for_saving_card);
}
@Override
public void onClick(View view) {
int i = view.getId();
if (i == R.id.rave_payButton) {
clearErrors();
collectData();
}
if (i == R.id.rave_use_saved_card_tv) {
if (!hasSavedCards) {
showToast("You have no saved Cards");
} else {
clearErrors();
collectDataForSavedCardCharge();
}
}
}
private void collectDataForSavedCardCharge() {
HashMap<String, ViewObject> dataHashMap = new HashMap<>();
dataHashMap.put(fieldAmount, new ViewObject(amountTil.getId(), amountEt.getText().toString(), TextInputLayout.class));
dataHashMap.put(fieldEmail, new ViewObject(emailTil.getId(), emailEt.getText().toString(), TextInputLayout.class));
presenter.onDataForSavedCardChargeCollected(dataHashMap, ravePayInitializer);
}
private void collectData() {
HashMap<String, ViewObject> dataHashMap = new HashMap<>();
dataHashMap.put(fieldAmount, new ViewObject(amountTil.getId(), amountEt.getText().toString(), TextInputLayout.class));
dataHashMap.put(fieldEmail, new ViewObject(emailTil.getId(), emailEt.getText().toString(), TextInputLayout.class));
dataHashMap.put(fieldCvv, new ViewObject(cvvTil.getId(), cvvTv.getText().toString(), TextInputLayout.class));
dataHashMap.put(fieldCardExpiry, new ViewObject(cardExpiryTil.getId(), cardExpiryTv.getText().toString(), TextInputLayout.class));
dataHashMap.put(fieldcardNoStripped, new ViewObject(cardNoTil.getId(), cardNoTv.getText().toString(), TextInputLayout.class));
dataHashMap.put(fieldPhone, new ViewObject(saveCardPhoneNoTil.getId(), saveCardPhoneNoEt.getText().toString(), TextInputLayout.class));
presenter.onDataCollected(dataHashMap);
}
private void clearErrors() {
cardExpiryTil.setErrorEnabled(false);
cardNoTil.setErrorEnabled(false);
amountTil.setErrorEnabled(false);
emailTil.setErrorEnabled(false);
cvvTil.setErrorEnabled(false);
cardExpiryTil.setError(null);
amountTil.setError(null);
emailTil.setError(null);
cardNoTil.setError(null);
cvvTil.setError(null);
}
@Override
public void onValidationSuccessful(HashMap<String, ViewObject> dataHashMap) {
chargeType = MANUAL_CARD_CHARGE;
presenter.processTransaction(dataHashMap, ravePayInitializer);
}
@Override
public void showFieldError(int viewID, String message, Class<?> viewType) {
if (viewType == TextInputLayout.class) {
TextInputLayout view = v.findViewById(viewID);
view.setError(message);
} else if (viewType == EditText.class) {
EditText view = v.findViewById(viewID);
view.setError(message);
}
}
@Override
public void onEmailValidated(String emailToSet, int visibility) {
emailTil.setVisibility(visibility);
emailEt.setText(emailToSet);
saveCardEmailEt.setText(emailToSet);
}
@Override
public void onAmountValidated(String amountToSet, int visibility) {
amountTil.setVisibility(visibility);
amountEt.setText(amountToSet);
}
@Override
public void onResume() {
super.onResume();
if (presenter == null) {
presenter = new CardUiPresenter(this);
}
presenter.onAttachView(this);
}
@Override
public void onDetach() {
super.onDetach();
if (presenter != null) {
presenter.onDetachView();
}
}
/**
* Show/Hide a progress dialog (general purpose)
*
* @param active = status of progress indicator
*/
@Override
public void showProgressIndicator(boolean active) {
try {
if (getActivity().isFinishing()) {
return;
}
if (progessDialog == null) {
progessDialog = new ProgressDialog(getActivity());
progessDialog.setCanceledOnTouchOutside(false);
progessDialog.setMessage(getResources().getString(R.string.wait));
}
if (active && !progessDialog.isShowing()) {
progessDialog.show();
} else {
progessDialog.dismiss();
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
/**
* Called when there's a non fatal error in payment. Shows a toast with the error message
*
* @param errorMessage = response message to display
*/
@Override
public void onPaymentError(String errorMessage) {
dismissDialog();
presenter.logEvent(new ErrorEvent(errorMessage).getEvent(), ravePayInitializer.getPublicKey());
Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_LONG).show();
}
/**
* Called when a pin suggested auth model is required.
* It shows a dialog that receives the pin and sends the payment payload
*
* @param payload = Contains card payment details
*/
@Override
public void collectCardPin(final Payload payload) {
this.payLoad = payload; //added so as to get back in onActivityResult
new RaveVerificationUtils(this, ravePayInitializer.isStaging(), ravePayInitializer.getPublicKey(), ravePayInitializer.getTheme())
.showPinScreen();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RavePayActivity.RESULT_SUCCESS) {
//just to be sure this v sent the receiving intent
switch (requestCode) {
case PIN_REQUEST_CODE:
String pin = data.getStringExtra(PinFragment.EXTRA_PIN);
presenter.chargeCardWithPinAuthModel(payLoad, pin, ravePayInitializer.getEncryptionKey());
break;
case ADDRESS_DETAILS_REQUEST_CODE:
String streetAddress = data.getStringExtra(AVSVBVFragment.EXTRA_ADDRESS);
String state = data.getStringExtra(AVSVBVFragment.EXTRA_STATE);
String city = data.getStringExtra(AVSVBVFragment.EXTRA_CITY);
String zipCode = data.getStringExtra(AVSVBVFragment.EXTRA_ZIPCODE);
String country = data.getStringExtra(AVSVBVFragment.EXTRA_COUNTRY);
AddressDetails address = new AddressDetails(streetAddress, city, state, zipCode, country);
presenter.chargeCardWithAddressDetails(payLoad, address, ravePayInitializer.getEncryptionKey(), authModel);
break;
case WEB_VERIFICATION_REQUEST_CODE:
presenter.requeryTx(flwRef, ravePayInitializer.getPublicKey());
break;
case OTP_REQUEST_CODE:
String otp = data.getStringExtra(OTPFragment.EXTRA_OTP);
if (data.getBooleanExtra(OTPFragment.IS_SAVED_CARD_CHARGE, false)) {
payLoad.setOtp(otp);
presenter.chargeSavedCard(payLoad, ravePayInitializer.getEncryptionKey());
} else
presenter.validateCardCharge(flwRef, otp, ravePayInitializer.getPublicKey());
break;
case FOR_SAVED_CARDS:
if (data.hasExtra(SavedCardsFragment.EXTRA_SAVED_CARDS)) {
SavedCard savedCardToCharge = new Gson().fromJson(
data.getStringExtra(SavedCardsFragment.EXTRA_SAVED_CARDS),
SavedCard.class);
onSavedCardSelected(savedCardToCharge);
}
presenter.checkForSavedCardsInMemory(ravePayInitializer);
break;
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
Type savedCardsListType = new TypeToken<List<SavedCard>>() {
}.getType();
outState.putString(STATE_PRESENTER_SAVEDCARDS,
(new Gson()).toJson(presenter.savedCards, savedCardsListType));
super.onSaveInstanceState(outState);
}
/**
* Displays a toast with the message parameter
*
* @param message = text to display
*/
public void showToast(String message) {
Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
}
/**
* Hide all dialog if available
*/
private void dismissDialog() {
if (dialog != null && !dialog.isShowing()) {
dialog.dismiss();
}
}
/**
* If an OTP is required, this method shows the dialog that receives it
*
* @param flwRef
* @param message
*/
@Override
public void collectOtp(String flwRef, String message) {
this.flwRef = flwRef;
dismissDialog();
new RaveVerificationUtils(this, ravePayInitializer.isStaging(), ravePayInitializer.getPublicKey(), ravePayInitializer.getTheme())
.showOtpScreen(message);
}
public void showOTPLayoutForSavedCard(Payload payload, String authInstruction) {
this.payLoad = payload;
dismissDialog();
new RaveVerificationUtils(this, ravePayInitializer.isStaging(), ravePayInitializer.getPublicKey(), ravePayInitializer.getTheme())
.showOtpScreenForSavedCard(authInstruction);
}
@Override
public void showSavedCardsLayout(List<SavedCard> savedCardsList) {
Intent intent = new Intent(getContext(), SavedCardsActivity.class);
Type savedCardsListType = new TypeToken<List<SavedCard>>() {
}.getType();
intent.putExtra(SavedCardsFragment.EXTRA_SAVED_CARDS,
(new Gson()).toJson(savedCardsList, savedCardsListType));
intent.putExtra(SavedCardsActivity.ACTIVITY_MOTIVE, SavedCardsFragment.SAVED_CARD_MOTIVE);
startActivityForResult(intent, FOR_SAVED_CARDS);
}
@Override
public void setHasSavedCards(boolean b) {
hasSavedCards = b;
if (b) useASavedCardTv.setVisibility(VISIBLE);
else useASavedCardTv.setVisibility(GONE);
}
/**
* Called when the auth model suggested is VBV. It opens a WebView
* that loads the authURL
*
* @param authenticationUrl URL to display in webview
* @param flwRef Reference of the payment transaction
*/
@Override
public void showWebPage(String authenticationUrl, String flwRef) {
this.flwRef = flwRef;
new RaveVerificationUtils(this, ravePayInitializer.isStaging(), ravePayInitializer.getPublicKey(), ravePayInitializer.getTheme())
.showWebpageVerificationScreen(authenticationUrl);
}
@Override
public void onPhoneNumberValidated(String phoneNumber) {
saveCardPhoneNoEt.setText(phoneNumber);
}
@Override
public void showCardSavingOption(boolean shouldShow) {
if (shouldShow) saveCardSwitch.setVisibility(VISIBLE);
else saveCardSwitch.setVisibility(GONE);
}
@Override
public void collectOtpForSaveCardCharge(Payload payload) {
String authInstruction = "Enter the one time password (OTP) sent to " +
phoneNumberObfuscator.obfuscatePhoneNumber(payload
.getPhonenumber());
showOTPLayoutForSavedCard(payload, authInstruction);
}
@Override
public void onCardSaveSuccessful(SaveCardResponse response, String phoneNumber) {
// Perform lookup of saved savedCards and save to phone storage
presenter.lookupSavedCards(ravePayInitializer.getPublicKey(), phoneNumber);
}
@Override
public void onCardSaveFailed(String message) {
showToast("Unable to save card:" + message);
presenter.setCardSaveInProgress(false);
Intent intent = new Intent();
intent.putExtra("response", responseAsJsonString);
if (getActivity() != null) {
getActivity().setResult(RavePayActivity.RESULT_SUCCESS, intent);
getActivity().finish();
}
}
@Override
public void onSavedCardsLookupSuccessful(List<SavedCard> cards, String phoneNumber) {
if (cards != null && cards.size() != 0) hasSavedCards = true;
//Save details to phone
presenter.saveCardToSharedPreferences(cards, phoneNumber, ravePayInitializer.getPublicKey());
// Save details in app memory
presenter.retrieveSavedCardsFromMemory(ravePayInitializer.getPhoneNumber(),
ravePayInitializer.getPublicKey());
presenter.setCardSaveInProgress(false);
if (responseAsJsonString != null) {
// If this is a lookup after successful charge
Intent intent = new Intent();
intent.putExtra("response", responseAsJsonString);
if (getActivity() != null) {
getActivity().setResult(RavePayActivity.RESULT_SUCCESS, intent);
getActivity().finish();
}
}
}
@Override
public void onSavedCardsLookupFailed(String message) {
Intent intent = new Intent();
intent.putExtra("response", responseAsJsonString);
if (responseAsJsonString != null) {// If this is after successful charge
if (getActivity() != null) {
getActivity().setResult(RavePayActivity.RESULT_SUCCESS, intent);
getActivity().finish();
}
}
}
/**
* Called after a fatal failure in a transaction. It closes all open dialogs
* and bottomsheets if any and send back the result of payment to the calling activity
*
* @param status = status of the transaction
* @param responseAsJsonString = full json response from the payment transaction
*/
@Override
public void onPaymentFailed(String status, String responseAsJsonString) {
dismissDialog();
Intent intent = new Intent();
intent.putExtra("response", responseAsJsonString);
if (getActivity() != null) {
((RavePayActivity) getActivity()).setRavePayResult(RavePayActivity.RESULT_ERROR, intent);
getActivity().finish();
}
}
/**
* Called after a successful transaction occurs. It closes all open dialogs
* and bottomsheets if any and send back the result of payment to the calling activity
*
* @param status = status of the transaction
* @param flwRef = reference of the payment transaction
* @param responseAsJSONString = full json response from the payment transaction
*/
@Override
public void onPaymentSuccessful(String status, String flwRef, String responseAsJSONString) {
this.responseAsJsonString = responseAsJSONString;
dismissDialog();
if (shouldISaveThisCard && flwRef != null) {
presenter.setCardSaveInProgress(true);
presenter.saveCardToRave(
ravePayInitializer.getPhoneNumber(),
ravePayInitializer.getEmail(),
flwRef,
ravePayInitializer.getPublicKey()
);
}
if (!presenter.isCardSaveInProgress()) {
Intent intent = new Intent();
intent.putExtra("response", responseAsJSONString);
if (getActivity() != null) {
((RavePayActivity) getActivity()).setRavePayResult(RavePayActivity.RESULT_SUCCESS, intent);
getActivity().finish();
}
}// else, result will be delivered after card save [in onCardSaveSuccessful()]
}
/**
* Displays the error message from a failed fetch fee request
*
* @param errorMessage = error message
*/
@Override
public void onFetchFeeError(String errorMessage) {
presenter.logEvent(new ErrorEvent(errorMessage).getEvent(), ravePayInitializer.getPublicKey());
showToast(errorMessage);
}
/**
* @param chargeAmount = Total amount to be charged (transaction fees incuded)
* @param payload = Object that contains the payment info (Contains card payment details)
*/
@Override
public void onTransactionFeeFetched(String chargeAmount, final Payload payload, String fee) {
if (getActivity() != null) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(getResources().getString(R.string.charge) + " " + chargeAmount + " " + ravePayInitializer.getCurrency() + getResources().getString(R.string.askToContinue));
builder.setPositiveButton(getResources().getString(R.string.yes), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
presenter.logEvent(new FeeDisplayResponseEvent(true).getEvent(), ravePayInitializer.getPublicKey());
if (chargeType == MANUAL_CARD_CHARGE) {
presenter.chargeCard(payload, ravePayInitializer.getEncryptionKey());
} else if (chargeType == SAVED_CARD_CHARGE) {
payload.setSavedCardDetails(selectedSavedCard);
presenter.chargeSavedCard(payload, ravePayInitializer.getEncryptionKey());
}
}
}).setNegativeButton(getResources().getString(R.string.no), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
presenter.logEvent(new FeeDisplayResponseEvent(false).getEvent(), ravePayInitializer.getPublicKey());
}
});
builder.show();
}
}
@Override
public void collectCardAddressDetails(final Payload payload, String authModel) {
this.payLoad = payload;
this.authModel = authModel;
new RaveVerificationUtils(this, ravePayInitializer.isStaging(), ravePayInitializer.getPublicKey(), ravePayInitializer.getTheme())
.showAddressScreen();
}
private class ExpiryWatcher implements TextWatcher {
private final Calendar calendar;
private final SimpleDateFormat simpleDateFormat;
private String lastInput = "";
public ExpiryWatcher() {
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("MM/yy");
}
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
String input = editable.toString();
String cardExpiryToSet = cardExpiryTv.getText().toString() + "/";
try {
calendar.setTime(simpleDateFormat.parse(input));
} catch (ParseException e) {
if (editable.length() == 2 && !lastInput.endsWith("/")) {
int month = Integer.parseInt(input);
if (month <= 12) {
cardExpiryTv.setText(cardExpiryToSet);
cardExpiryTv.setSelection(cardExpiryTv.getText().toString().length());
} else {
cardExpiryTv.setText(getResources().getString(R.string.defaultCardExpiry));
cardExpiryTv.setSelection(cardExpiryTv.getText().toString().length());
}
} else if (editable.length() == 2 && lastInput.endsWith("/")) {
try {
int month = Integer.parseInt(input);
if (month <= 12) {
cardExpiryTv.setText(cardExpiryTv.getText().toString().substring(0, 1));
cardExpiryTv.setSelection(cardExpiryTv.getText().toString().length());
} else {
cardExpiryTv.setText(getResources().getString(R.string.defaultCardExpiry));
cardExpiryTv.setSelection(cardExpiryTv.getText().toString().length());
}
} catch (NumberFormatException ex) {
cardExpiryTv.setText(input.replace("/", ""));
cardExpiryTv.setSelection(cardExpiryTv.getText().toString().length());
} catch (Resources.NotFoundException ex) {
ex.printStackTrace();
}
} else if (editable.length() == 1) {
int month = Integer.parseInt(input);
if (month > 1) {
cardExpiryTv.setText("0" + cardExpiryTv.getText().toString() + "/");
cardExpiryTv.setSelection(cardExpiryTv.getText().toString().length());
}
}
}
lastInput = cardExpiryTv.getText().toString();
}
}
@Override
public void onFocusChange(View view, boolean hasFocus) {
int i = view.getId();
String fieldName = "";
if (i == R.id.rave_cvvTv) {
fieldName = "CVV";
} else if (i == R.id.rave_amountEt) {
fieldName = "Amount";
} else if (i == R.id.rave_emailEt) {
fieldName = "Email";
} else if (i == R.id.rave_cardNoTv) {
fieldName = "Card Number";
} else if (i == R.id.rave_cardExpiryTv) {
fieldName = "Card Expiry";
}
if (hasFocus) {
presenter.logEvent(new StartTypingEvent(fieldName).getEvent(), ravePayInitializer.getPublicKey());
}
}
}