Home / IOS Development / How to integrate Stripe Payment Gateway in Android App?

How to integrate Stripe Payment Gateway in Android App?



Through this Stripe payment gateway integration in Android guide, you will learn how to integrate stripe payment gateway into your Android application. Towards the end of this Stripe Android tutorial post, you will get the answer on how to integrate stripe payment gateway into the Android application and can accept payments from your Android app. Spent? Let’s get started.

Introduction

If you are developing a mobile app for your business, you must somehow accept payments in your application. Whether it’s a travel app or an e-commerce mobile app, you need to offer an option for customers to pay for the goods or services that your app offers.

To get it used, various payment portals are often used. There are now a large number of payment portals available in the market that allow you to process credit card transaction data via their APIs. But by integrating such a payment portal, you also put the responsibility for the security of credit card data on your shoulders, since the credit card data will pass through your mobile app.

Typically, when a mobile payment gateway is implemented in your app, the API should return a token from the server̵

7;s secure authenticated environment. This token represents the submitted card and is used for the actual transaction.

Now, if you want to integrate a payment portal to create commission-based transactions, there are only a few options available. And among these few options, Stripe is the best.

Stripe payment portals allow both individuals and businesses to accept payments via mobile apps. Stripe was initially launched in 2011 and now supports over 100 currencies, becoming one of the most popular payment gateways in the world.

In fact, you can learn more about Stripe, explained by one of our senior Android developers who shares their experience using Stripe as a payment gateway in one of the Android applications.

Now, if you’re an Android developer and are looking forward to learning how to integrate Stripe payment gateway into an Android application, the guide below will help you do just that.

Stripe Payment Gateway integration with commission-based transaction

We integrate the strip payment gateway, but in addition the client wants us to receive a commission on each transaction, and needs to connect to the user’s account for the commission.

We offer a commission-based solution that allows our customers to earn some amount for each transaction.

So here we will share the development steps as mentioned below for integration:

Step 1) for the developer: Add under two dependencies in the Gradle file to your project.

1) compile 'com.stripe:stripe-java:1.47.0'

2) compile 'com.stripe:stripe-android:1.0.4'

Step 2) To get the commission, you need to connect to the user account, and for that you need to get an authorization code.

To approve this code, you must have a client ID that you get through, and register your application on the strip.

This is a one-time process to obtain a client ID. This gives you access to the Stripe Connect settings.

Use this link to register your application with Stripe and start developing with Stripe Connect.

Here we show you how to register your platform (Platform means your application) after. Log in to the strip and register the platform.

click on Your account which appears at the top right of the dashboard. See the screenshot below.

picture1

The window will now be a pop-up window to register your platform. Click connect and you will have a screenshot to register your platform. See the screenshot below for more info.

picture2

Click on the register your platform button, and you will have one more window that moves to your final destination to register the platform. Just fill in all the information and press the Done button.

[[[[Developer Note We Experienced: You must enter URL and redirect URLs in https: // format. See the screenshot below.]

picture3

By filling out all of the above information, you will have a client ID that will be used to authorize your account.

Step 3) A process to obtain Stripe authentication code (OAuth 2.0) through client ID

To connect to the user’s account – the user must go through OAuth2.0 for a managed account. This entire authentication process is managed by Stripe. Replace the client ID text in this URL and open it in the browser.

For test and live mode for development you will get different client IDs, so take care of the client ID that is transmitted with the URL above.

Here are the steps to getting an authorization code:

3.1) After logging in, a user is redirected to the URL set, which is step 1.

www.yourredirectionurl.com/?scope=read_write&code=AUTHORIZATION_CODE

Here we get “AUTHORIZATION_CODE”.

3.2) This AUTHORIZATION_CODE must pass through the curl that returns “stripe_user_id

curl connect.stripe.com/oauth/token
-d client_secret = CLIENT_SECRET_KEY
-d code = AUTHORIZATION_CODE
-d grant_type = authorization code

In step 3.2) you may have questions about what is CLIENT_SECRET_KEY.

And how do you get it?

This is the key to the client who needs to get some of each transaction into their account. To get SECRET_KEY, click on API_KEYS which appears in the third position in the screenshot below. And use the Test Secret Key from all the entry keys.

picture4

3.3) You need to save this stripe_user_id and pass this stripe_user_id to get a commission. You just need to take test and live mode for development and make sure you change the secret key and client ID.

Based on customer requirements, we want you to share the XML file to get information about credit card number, expiration date, CVV number, transaction amount, transaction description and email for receipt.

XML file code



 

 



 



 



 



 





 



 

 



 



 





 

     

 



 





 



 





 



 



android:drawableLeft="@drawable/icon_calender"

android:drawablePadding="@dimen/scal_15dp"

android:hint="@string/edit_expirydate_hint"

android:imeOptions="actionNext"

android:inputType="number"

android:maxLength="10"

android:padding="@dimen/scal_10dp"

android:singleLine="true"

android:textAllCaps="false" />



 

 



 





 



 





 



 





 

 

3.3.2) With XML above, you get the above details, but if you want to scan your credit card, you should follow the method below for your Java class file.

private void scanCard() {
if (CardIOActivity.canReadCardWithCamera()) {
onScanPress();
isCardIo = true;
} else {
myUtility.setAlertMessage(getString(R.string.app_name), "Enter credit card information manual.");
}
}
public void onScanPress() {
Intent scanIntent = new Intent(this, CardIOActivity.class);

// customize these values to suit your needs.
scanIntent.putExtra(CardIOActivity.EXTRA_SCAN_EXPIRY, true);
scanIntent.putExtra(CardIOActivity.EXTRA_REQUIRE_EXPIRY, true); // default: false
scanIntent.putExtra(CardIOActivity.EXTRA_REQUIRE_CVV, false); // default: false
scanIntent.putExtra(CardIOActivity.EXTRA_REQUIRE_POSTAL_CODE, false); // default: false
scanIntent.putExtra(CardIOActivity.EXTRA_USE_CARDIO_LOGO, false);
scanIntent.putExtra(CardIOActivity.EXTRA_HIDE_CARDIO_LOGO, true);
scanIntent.putExtra(CardIOActivity.EXTRA_USE_PAYPAL_ACTIONBAR_ICON, false);
scanIntent.putExtra(CardIOActivity.EXTRA_GUIDE_COLOR, Color.parseColor("#33b5e5"));
// hides the manual entry button
// if set, developers should provide their own manual entry mechanism in the app
scanIntent.putExtra(CardIOActivity.EXTRA_SUPPRESS_MANUAL_ENTRY, true); // default: false
startActivityForResult(scanIntent, MY_SCAN_REQUEST_CODE);
}

3.3.3) To validate your credit card – use the method below in your Java class file.

private boolean isCardValid() {
cardNumber = editCardNumber.getText().toString().replace(" ", "");
cardCVC = editCvcNumber.getText().toString();
StringTokenizer tokens = new StringTokenizer(editEpiryDate.getText().toString(), "https://www.spaceotechnologies.com/");
cardExpMonth = Integer.parseInt(tokens.nextToken());
cardExpYear = Integer.parseInt(tokens.nextToken());
// Card card = new Card("4242424242424242", 12, 2016, "123");
Card card = new Card(cardNumber, cardExpMonth, cardExpYear, cardCVC);
boolean validation = card.validateCard();
if (validation) {
return true;
} else if (!card.validateNumber()) {

myUtility.setAlertMessage("Error", “The card number that you entered is invalid.”);
} else if (!card.validateExpiryDate()) {

myUtility.setAlertMessage("Error", “The expiration date that you entered is invalid.”);
} else if (!card.validateCVC()) {
myUtility.setAlertMessage("Error",”The CVC code that you entered is invalid.”);
} else {
myUtility.setAlertMessage("Error", “The card details that you entered are invalid.”);

}
return false;
}

3.3.4) After card validation, the next step is to get the stripe Token, and to get the stripe token, you need to add the code below to your java class file.

3.3.4.1) In the code there is a publishable key. You get the publishable key from API keys in your Stripe account. We want you to check the screen to step 3.2. Where you will be able to see the public key under SECRET_KEY.

According to Stripe’s recommendation, we retrieve the keys by making an API call to the https URL. The best practice is to store the keys in a secure database in encrypted form and at the user’s request decrypt it and send the keys to the user when making an API call for keys.

Now we need to call an API to get these keys from a secured server. For that we can have an https API call that gives us the publishable key from the server.

private String userPublishableKey = "";
private String userSecretKey = "";
/**
* This is standerd api call method which will get the user's key from server
**/
private void getUserKey() {
// Call api and get user publishable & secret key here and assign key value in userPublishableKey & userSecretKey

}

Card card = new Card(cardNumber, cardExpMonth, cardExpYear, cardCVC);
try {
Stripe stripe = new Stripe(userPublishableKey); stripe.createToken(
card,
publishableKey,
new TokenCallback() {
public void onSuccess(Token token) {
if (myUtility.checkInternetConnection())

sendCardToInfoToStripe(token.getId(), isLive);
else {
myUtility.setInternetAlertMessage();

}

}

public void onError(Exception error) {
myUtility.setAlertMessage("Error", error.getMessage());
}
});

3.3.4.1) In the case of the payment process without login, you will need to add the code below to open the Stripe web view dialog.

final Dialog dialog = new Dialog(ChargeCardActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_connect_alert_dialog_with_msg);
dialog.setCanceledOnTouchOutside(false);

TextView textDialog = (TextView) dialog.findViewById(R.id.textDialog);
textDialog.setText(getString(R.string.lbl_stripe_not_connected));
TextView textCancel = (TextView) dialog.findViewById(R.id.textCancel);
TextView textOk = (TextView) dialog.findViewById(R.id.textOk);
// if button is clicked, close the custom dialog
textCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
}
});

textOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
Intent intent = new Intent(ChargeCardActivity.this, WebviewPaymentActivity.class);
intent.putExtra(Constants.ISLIVE, isLive);
intent.putExtra(Constants.CARD_NUMBER, cardNumber);
intent.putExtra(Constants.CARD_CVC, cardCVC);
intent.putExtra(Constants.CARD_EXP_MONTH, cardExpMonth);
intent.putExtra(Constants.CARD_EXP_YEAR, cardExpYear);
intent.putExtra(Constants.CENT_AMOUNT, centAmount);
intent.putExtra(Constants.USER_DESCRIPTION, userDescription[bad code]);
intent.putExtra(Constants.USER_EMAIL, userEmail);
intent.putExtra(Constants.USER_CURRENCY, sessionManager.getStringDetail(Constants.USER_CURRENCY));
intent.putExtra(Constants.USER_PUBLISHABLE_KEY, userLivePublishableKey);
startActivity(intent);
}
});
dialog.show();

Custom_connect_alert_dialog_with_msg.xml
















3.4) This code below is to make your Stripe payment integration based on the commission transaction you want to enter.

In the code below, we have used cents 1000 as a total amount transaction and 100 as commission. You can also define the currency using the code below.

NOTE: As the stripe recommends that you do not store key data in the application, we store the key information in encrypted form in the database, and we make an https web API call to get the decrypted keys.

We get userSecretKey from an API call to the server.

private void sendCardToInfoToStripe(final String cardToken, final boolean isLive) {
userDescription = editRefDesc.getText().toString(); // Get User Description[bad code]
userEmail = editEmail.getText().toString(); // Get User Email Id
new Thread(new Runnable() {
@Override
public void run() {

Map chargeParams = new HashMap();
chargeParams.put("amount", 1000);
chargeParams.put("currency", "usd");
chargeParams.put("source", cardToken);
chargeParams.put("description", [Variable name]userDescription[bad code]);[Variable name]
chargeParams.put("receipt_email", userEmail);
chargeParams.put("application_fee", 100);
RequestOptions requestOptions;
requestOptions = RequestOptions.builder().setStripeAccount(sessionManager.getStringDetail(Stripe-user-id)).setApiKey(userSecretKey).build();

try {
Charge.create(chargeParams, requestOptions);
callSuccess();
} catch (final Exception e) {
myUtility.dismissDialog();
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
myUtility.setAlertMessage("Error", e.getMessage());
}
});
}
}
}).start();

}

Note for developer: The above codes have used a couple of common classes for general methods such as internet control, notification dialogs. We set here all common method codes.

Public class Utility{
public boolean checkInternetConnection() {

ConnectivityManager conMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
// ARE WE CONNECTED TO THE NET
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
return true;
} else {
return false;
}
}

public void setInternetAlertMessage() {
if (context == null)
return;

dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_alert_dialog);
dialog.setCanceledOnTouchOutside(false);
TextView textDialog = (TextView) dialog.findViewById(R.id.textDialog);
textDialog.setText(context.getString(R.string.msg_internet_connection));
textDialog.setPadding(15, 15, 15, 15);
textDialog.setGravity(Gravity.CENTER);

TextView textOk = (TextView) dialog.findViewById(R.id.textOk);
// if button is clicked, close the custom dialog
textOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();

}
});
dialog.show();
}
public void setAlertMessage(String title, String msg) {

if (context == null)
return;

dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_alert_dialog);
dialog.setCanceledOnTouchOutside(false);
TextView textDialog = (TextView) dialog.findViewById(R.id.textDialog);
textDialog.setText(msg);
textDialog.setPadding(15, 15, 15, 15);
textDialog.setGravity(Gravity.CENTER);

TextView textOk = (TextView) dialog.findViewById(R.id.textOk);
textOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();

}
});
dialog.show();
}
}

Note: Do all the steps carefully while moving the codes from Test to Live.

The challenging task was to get a user through the authentication, which can only be performed online. Thus, we enable a user to experience the same experience in native applications and managed all the redirection of a web, as we do not get callbacks from the strip SDK, and in the end we achieved this by observing the redirects.

We would like to share with the app owners that when they are in a situation of choosing a payment gateway or any of the payment services, it will be suggested to check the target group, and then apply for the payment gateway support for that region.

For example, if you need to pay from the Middle East or North Africa, Hyper Pay is one of the best payment gateway solutions, or if you are targeting the US, UK, Canada, Australia, Stripe Payment Gateway integration is the best solution. After that, we need to check the cost structure, the refund fees and the time used by the payment portal to transfer money to the bank account.

Frequently asked questions

What if an Android app does not redirect back to the app after you complete a PaymentIntent?

To resolve this, make sure that you have implemented a return_url in PaymentIntent and that the URL is in the AndroidManifest.xml file.

Is Stripe a good payment portal?

Currently, Stripe is one of the best online credit card providers, allowing businesses to build a customized e-commerce experience by leveraging the free API. It is easy to implement and offers security in the market to sellers and their customers.

Will my customers need a Stripe account to pay?

No. Your customers can complete the transactions with debit / credit cards. They do not need an individual Stripe account to complete the payment.

Do my customers want to know that I use the Stripe payment portal on my application?

Not necessarily. Your customers will not be able to know that you are using the Stripe payment gateway on your application.

Conclusion

Stripe makes a difference in the developer community through payment service integration, user-friendly documents and API. We had happily coded the Stripe integration in Android, and our recent development of mobile applications in Stripe gained 3,000 users in the first week of launch, 45,000 volumes of transactions that happened every day, and almost 100+ reviews and a 4.1 star rating on the Google Play Store. This application was in the top-rated apps in the finance category in the first quarter of 2016. We’d love to hear your words about Stripe Payment Gateway integration in Android and share your feedback.

Apart from this, if you have any Android app idea that you want to discuss with a leading Android app development company, you can connect it to us and we will guide you further.

This page was last modified on 15 October 2020, at 11:52.


Source link