Skip to content

Instantly share code, notes, and snippets.

@ResonantEdge
Created March 15, 2021 10:23
Show Gist options
  • Save ResonantEdge/e026e79ee444df81d6dd7a05306cd807 to your computer and use it in GitHub Desktop.
Save ResonantEdge/e026e79ee444df81d6dd7a05306cd807 to your computer and use it in GitHub Desktop.
Android Appetite Subscription
public class PaymentFragment extends Fragment {
// General
private Context paymentContext;
private Bundle bundle;
private Switch backgroundSwitch;
private ProgressBar progressBar;
private Button btnCreatePlan, btnBack;
private View paymentView;
private RelativeLayout monthFrame, yearFrame;
private SharedPreferences sharedpreferences;
private SharedPreferences.Editor mEditor;
private boolean backgroundValue;
// Firestore
private FirebaseFirestore firebaseFirestore;
private TextView errorMessage;
// Stripe
private Card cardToSave;
private EditText etCardHolderName, etCardHolderAddress, etCardNumber, etCVC;
private Spinner spinnerMonth, spinnerYear;
private String selectedMonth, selectedYear;
private int yearPosition, monthPosition;
// Data
private OnPaymentSubmit paymentSubmitListener;
private final static String TAG = PaymentFragment.class.getSimpleName();
public PaymentFragment() {
// Required empty public constructor
}
@SuppressLint("ClickableViewAccessibility")
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// Inflate the layout for this fragment
((MainActivity) Objects.requireNonNull(getActivity())).setActionBarTitle("You are almost set!");
if (paymentView != null) {
if (paymentView.getParent() != null)
((ViewGroup)paymentView.getParent()).removeView(paymentView);
return paymentView;
}
paymentView = inflater.inflate(R.layout.fragment_payment, container, false);
btnBack = paymentView.findViewById(R.id.button_back);
etCardHolderName = paymentView.findViewById(R.id.et_holder_name);
etCardHolderAddress = paymentView.findViewById(R.id.et_holder_addressLine);
spinnerMonth = paymentView.findViewById(R.id.month_spinner);
spinnerYear = paymentView.findViewById(R.id.year_spinner);
etCardNumber = paymentView.findViewById(R.id.et_card_number);
etCVC = paymentView.findViewById(R.id.et_ccv);
backgroundSwitch = paymentView.findViewById(R.id.switch_background);
monthFrame = paymentView.findViewById(R.id.month_spinner_frame);
yearFrame = paymentView.findViewById(R.id.year_spinner_frame);
ImageView ivCardType = paymentView.findViewById(R.id.card_type);
errorMessage = paymentView.findViewById(R.id.tv_failed_message);
btnCreatePlan = paymentView.findViewById(R.id.button_create);
progressBar = paymentView.findViewById(R.id.progress_bar);
progressBar.setVisibility(View.INVISIBLE);
ScrollView scrollView = paymentView.findViewById(R.id.scroll_view);
sharedpreferences = getContext().getSharedPreferences(getString(R.string.background), Context.MODE_PRIVATE);
mEditor = sharedpreferences.edit();
scrollView.setOnTouchListener((view, motionEvent) -> {
InputMethodManager imm = (InputMethodManager) paymentContext.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(paymentView.getWindowToken(), 0);
return false;
});
// Initialize Firebase
firebaseFirestore = FirebaseFirestore.getInstance();
bundle = getArguments();
createSpinners();
etCardNumber.addTextChangedListener(new CreditCardFormat(etCardNumber, ivCardType));
handleSwitch();
btnBack.setOnClickListener(view -> {
disableFields();
assert bundle != null;
bundle.putBoolean("direction", false);
bundle.putString("cardNumber", etCardNumber.getText().toString());
bundle.putString("cvc", etCVC.getText().toString());
bundle.putString("selectedMonth", selectedMonth);
bundle.putString("selectedYear", selectedYear);
paymentSubmitListener.onPaymentSubmit(bundle);
});
btnCreatePlan.setOnClickListener(view -> {
errorMessage.setVisibility(View.INVISIBLE);
if (!etCardNumber.getText().toString().isEmpty() && !etCardHolderAddress.getText().toString().isEmpty() && yearPosition != 0 &&
monthPosition != 0 && !etCVC.getText().toString().isEmpty()) buildCard();
if (etCardHolderName.getText().toString().isEmpty()) {
etCardNumber.setBackground(ContextCompat.getDrawable(paymentContext, R.drawable.edittext_bg_error));
} else {
etCardNumber.setBackground(ContextCompat.getDrawable(paymentContext, R.drawable.edittext_bg_grey));
}
if (etCardHolderAddress.getText().toString().isEmpty()) {
etCardHolderAddress.setBackground(ContextCompat.getDrawable(paymentContext, R.drawable.edittext_bg_error));
} else {
etCardHolderAddress.setBackground(ContextCompat.getDrawable(paymentContext, R.drawable.edittext_bg_grey));
}
if (etCardNumber.getText().toString().isEmpty()) {
etCardNumber.setBackground(ContextCompat.getDrawable(paymentContext, R.drawable.edittext_bg_error));
} else {
etCardNumber.setBackground(ContextCompat.getDrawable(paymentContext, R.drawable.edittext_bg_grey));
}
if (yearPosition == 0) {
yearFrame.setBackgroundResource(R.drawable.spinner_custom_error);
} else {
yearFrame.setBackgroundResource(R.drawable.spinner_custom);
}
if (monthPosition == 0) {
monthFrame.setBackgroundResource(R.drawable.spinner_custom_error);
} else {
monthFrame.setBackgroundResource(R.drawable.spinner_custom);
}
if (etCVC.getText().toString().isEmpty()) {
etCVC.setBackground(ContextCompat.getDrawable(paymentContext, R.drawable.edittext_bg_error));
} else {
etCVC.setBackground(ContextCompat.getDrawable(paymentContext, R.drawable.edittext_bg_grey));
}
Log.d(TAG, "onCreateView: background value = " + backgroundValue);
if (!backgroundValue) mEditor.putString(getString(R.string.background), "false");
else mEditor.putString(getString(R.string.background), "true");
mEditor.apply();
});
return paymentView;
}
private void buildCard() {
new HideSoftKeyboard(paymentContext, paymentView);
disableFields();
Card.Builder builder = new Card.Builder(etCardNumber.getText().toString(), Integer.valueOf(selectedMonth)
, Integer.valueOf(selectedYear), etCVC.getText().toString());
cardToSave = builder.build();
setBrand(builder);
validateCard();
}
private void validateCard() {
boolean validated = cardToSave.validateCard();
if (validated) {
((MainActivity) Objects.requireNonNull(getActivity())).setActionBarTitle("Validating credit card...");
getToken();
} else if (!cardToSave.validateNumber()) {
((MainActivity) Objects.requireNonNull(getActivity())).setActionBarTitle("Please try again");
errorMessage.setText(R.string.error_card_number);
enableFields();
} else if (!cardToSave.validateExpiryDate()) {
((MainActivity) Objects.requireNonNull(getActivity())).setActionBarTitle("Please try again");
errorMessage.setText(R.string.error_card_expiry);
enableFields();
} else if (!cardToSave.validateCVC()) {
((MainActivity) Objects.requireNonNull(getActivity())).setActionBarTitle("Please try again");
errorMessage.setText(R.string.error_card_cvc);
enableFields();
}
}
private void setBrand(Card.Builder builder) {
if (Objects.requireNonNull(cardToSave.getNumber()).startsWith("4")) builder.brand(Card.VISA);
else if (cardToSave.getNumber().startsWith("5")) builder.brand(Card.MASTERCARD);
else if (cardToSave.getNumber().startsWith("6")) builder.brand(Card.DISCOVER);
else if (cardToSave.getNumber().startsWith("37")) builder.brand(Card.AMERICAN_EXPRESS);
else builder.brand(Card.UNKNOWN);
}
private void getToken() {
((MainActivity) Objects.requireNonNull(getActivity())).setActionBarTitle("Creating your mealplan...");
Stripe stripe = new Stripe(paymentContext, getString(R.string.stripe_publishable_api));
Log.d(TAG, "validated. stripe: "+ stripe);
stripe.createToken(cardToSave, getString(R.string.stripe_publishable_api), new TokenCallback() {
@Override
public void onSuccess(@NonNull Token result) {
createMealplan(result);
}
@Override
public void onError(@NonNull Exception e) {
errorMessage.setText(e.toString());
((MainActivity) Objects.requireNonNull(getActivity())).setActionBarTitle("Please try again");
enableFields();
}
});
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void createMealplan(Token result) {
/*
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.GERMANY);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String timeStamp = sdf.format(new Date());
*/
ZoneId tz = ZoneId.systemDefault();
LocalDateTime localDateTime = LocalDateTime.now();
long seconds = localDateTime.atZone(tz).toEpochSecond();
int nanos = localDateTime.getNano();
Timestamp timestamp = new Timestamp(seconds, nanos);
ArrayList<Schedule> adjustedScheduleArrayList = new ArrayList<>();
ArrayList<Schedule> scheduleArrayList = bundle.getParcelableArrayList("schedule");
if (scheduleArrayList != null) adjustedScheduleArrayList = adjustTime(scheduleArrayList);
Map<String, Object> mealPlan = new HashMap<>();
mealPlan.put("userId", bundle.getString("userId"));
mealPlan.put("addressOne", bundle.getString("addressOne"));
mealPlan.put("addressTwo", bundle.getString("addressTwo"));
mealPlan.put("city", bundle.getString("city"));
mealPlan.put("postalCode", bundle.getString("postalCode"));
mealPlan.put("phone", bundle.getString("phone"));
mealPlan.put("instructions", bundle.getString("instructions"));
mealPlan.put("frequency", bundle.getString("frequency"));
mealPlan.put("schedule", adjustedScheduleArrayList);
mealPlan.put("restaurantId", bundle.getString("restaurantId"));
mealPlan.put("restaurantName", bundle.getString("restaurantName"));
mealPlan.put("restaurantAddress", bundle.getString("restaurantAddress"));
mealPlan.put("status", 1);
mealPlan.put("paymentToken", result.getId());
mealPlan.put("timeOfCreation", timestamp);
mealPlan.put("mpName", bundle.getString("mpName"));
mealPlan.put("planType", bundle.getInt("planType"));
mealPlan.put("planMenu", bundle.getParcelableArrayList("cartContent"));
firebaseFirestore.collection("Meal_Plans").add(mealPlan).addOnSuccessListener(documentReference -> {
Toast.makeText(paymentContext, "Mealplan created successfully", Toast.LENGTH_SHORT).show();
bundle.clear();
bundle.putBoolean("direction", true);
bundle.putString("planId", documentReference.getId());
onButtonPressed(bundle);
}).addOnFailureListener(e -> {
errorMessage.setText(e.getMessage());
enableFields();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment