If you’re an app developer and want to add PayPal as a payment option in your Android application, then this is the article for you. In this step-by-step guide, we’ll walk you through the process of How To Integrate PayPal in Android app quickly and easily. We will cover everything from creating a PayPal account to configuring the payment button within your app. So let’s get started!
What is PayPal?
PayPal is an American business that was founded in 1998 that enables online payments and money transfers. One of the biggest online payment companies in the world is PayPal. the business that processes payments for internet retailers, auction sites, and other business users. It accepts 26 currencies from 193 different countries.
PayPal Android SDK:
PayPal offers its Android SDK so developers may integrate in-app payment methods for any services users utilize or purchases they make through your app. Mobile applications may easily accept payments via PayPal or credit cards thanks to the Android SDK. The funds will be immediately credited to your PayPal account.
Also Read | Set up the Android 14 SDK
Steps of How to Integrate PayPal in Android
Step 1.
Visit the PayPal Developer page and register to create a PayPal account.
The “Sign Up” button will launch the registration form. Register online by completing the form. Remember that only addresses in the United States and five-digit zip codes are necessary. The country code and city name fields are automatically filled in when you input a valid zip code for the USA.
After making a PayPal account, click the “Sign In” button in the top right corner of the PayPal developer website to sign in. To make an app, go to the “Dashboard” tab after signing in and click the “Create App” button.
Click the “Create App” button after completing the app creation form. It will generate your application and, by default, a Sandbox developer account for you that cannot be altered. You can, however, create other accounts to test your application. During the development period, your application will be tested using this account. It is referred to as a sandbox developer account because it is utilised for testing. This account may be upgraded to a production account for use with live applications in the future.
When you click the “Create app” button, an application with a “Client Id” and a “Secret” key will be created for you. Your Android application will utilise the “Client Id” to carry out transactions and the “Secret” key to validate them. Additionally, you can request the user’s consent before carrying out future direct transactions or accessing any of their PayPal account’s personal data, including their email address or date of birth.
Under the “My apps” menu, you can view all of your programmes.
Step 2.
Download the Github-hosted PayPal Android SDK.
The PayPal-Android-SDK-master.zip file should be unzipped, and the contents of the lib folder should be copied and pasted into the lib folder of your Android project. Note: If your project doesn’t have a lib folder already, you should create one.If it does, just paste the contents of the SDK’s lib folder into the existing lib folder. If your project’s lib folder already has “armeabi” and other similar directories, manually copy and paste their contents into the appropriate folders in your project’s lib folder.
In order to understand how the code is implemented, the SDK contains a sample Android application Run the programme to see its workflow and attempt to comprehend its code. It is properly described in the form of remarks so that anyone may comprehend it.
Open your Android project’s Android.manifest file now, and add the following elements there:
<!– for card.io card scanning –>
<uses-permissionandroid:name=“android.permission.CAMERA” /> <uses-permissionandroid:name=“android.permission.VIBRATE” />
<uses-featureandroid:name=“android.hardware.camera” android:required=“false/>
<uses-featureandroid:name=“android.hardware.camera.autofocus” android:required=“false” />
<!– for most things, including card.io & paypal –> <uses-permissionandroid:name=“android.permission.ACCESS_NETWORK_STATE”/> <uses-permissionandroid:name=“android.permission.INTERNET”/>
Step 3.
This SDK has three use scenarios.
1. Single Payment:
2. Future Payments:
3. Profile Sharing
1. Single Payment:
Get one instant payment from your application using a PayPal account, a debit card, or a credit card.
When you start a single payment, the SDK displays a user interface (UI) to collect your PayPal account information, credit card information, or debit card information, complete the transaction, and provide a proof of payment with a payment id so you can confirm the payment transaction. We may use PayPal’s web apis for payment verification by setting up our own server.
The user has the option of paying with a credit or debit card, PayPal, or both.
Inside the Activity
1. Create a PayPalConfigration Object :
[sourcecode language=”java” wraplines=”false” collapse=”false”]
private static PayPalConfiguration config = new PayPalConfiguration()
// Start with mock environment. When ready, switch to sandbox (ENVIRONMENT_SANDBOX)
// or live (ENVIRONMENT_PRODUCTION)
.environment(PayPalConfiguration.ENVIRONMENT_NO_NETWORK)
.clientId("<YOUR_CLIENT_ID>");
[/sourcecode]
2. Launch PayPalService at the commencement of your action and terminate it at its completion:
[sourcecode language=”java” wraplines=”false” collapse=”false”]
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, PayPalService.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
startService(intent);
}
@Override
public void onDestroy() {
stopService(new Intent(this, PayPalService.class));
super.onDestroy();
}
[/sourcecode]
3.Initiate the PaymentActivity intent and create the PayPalPayment object, for instance, when a button is pressed:
[sourcecode language=”java” wraplines=”false” collapse=”false”]
public void onBuyPressed(View pressed) {
// PAYMENT_INTENT_SALE will cause the payment to complete immediately.
// Change PAYMENT_INTENT_SALE to
// – PAYMENT_INTENT_AUTHORIZE to only authorize payment and capture funds later.
// – PAYMENT_INTENT_ORDER to create a payment for authorization and capture
// later via calls from your server.
PayPalPayment payment = new PayPalPayment(new BigDecimal("1.75"), "USD", "hipster jeans",
PayPalPayment.PAYMENT_INTENT_SALE);
Intent intent = new Intent(this, PaymentActivity.class);
// send the same configuration for restart resiliency
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, payment);
startActivityForResult(intent, 0);
}
[/sourcecode]
4. Implement onActivityResult():
[sourcecode language=”java” wraplines=”false” collapse=”false”]
@Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
Log.i("paymentExample", confirm.toJSONObject().toString(4));
// TODO: send ‘confirm’ to your server for verification.
// see https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/
// for more details.
} catch (JSONException e) {
Log.e("paymentExample", "an extremely unlikely failure occurred: ", e);
}
}
}
else if (resultCode == Activity.RESULT_CANCELED) {
Log.i("paymentExample", "The user canceled.");
}
else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
Log.i("paymentExample", "An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
}
}
[/sourcecode]
5. Send the payment receipt to your servers so they can check it and do anything else that needs to be done to finish your business.
2. Future Payments:
This section explains how to get a user’s express permission to use their PayPal account for future payments.
Prior to taking payments from a customer’s PayPal account, you must get their permission. In order to leverage PayPal for further payments, the PayPal Android SDK provides a user interface for your user to authenticate using their PayPal account and grant OAuth access token scope (UI).
An OAuth2 authorisation code is returned to your app in response. After obtaining the permission code for OAuth2 access and refresh tokens, your server will exchange it.
A Client Metadata ID will be required later when you begin a pre-consented payment. The PayPal Android SDK provides a Client Metadata ID. Send the client metadata ID and transaction details to your server. Your server uses its Client Metadata ID, OAuth2 credentials, and transaction information to create a payment.
Inside Your Activity Code
1. Create a PayPalConfiguration object. This object enables you to customise a number of SDK features.
[sourcecode language=”java” wraplines=”false” collapse=”false”]
private static PayPalConfiguration config = new PayPalConfiguration()
// Start with mock environment. When ready, switch to sandbox (ENVIRONMENT_SANDBOX)
// or live (ENVIRONMENT_PRODUCTION)
.environment(PayPalConfiguration.ENVIRONMENT_NO_NETWORK)
.clientId("<YOUR_CLIENT_ID>")
// You will need to set at least three properties about the merchant.
// These must match the information you gave PayPal when you registered your app. .merchantName("Hipster Store")
.merchantPrivacyPolicyUri(Uri.parse("https://www.example.com/privacy"))
.merchantUserAgreementUri(Uri.parse("https://www.example.com/legal"));
[/sourcecode]
2.When your activity is created, start the PayPalService, and when it is destroyed, end it:
[sourcecode language=”java” wraplines=”false” collapse=”false”]
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, PayPalService.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
startService(intent);
}
@Override
public void onDestroy() {
stopService(new Intent(this, PayPalService.class));
super.onDestroy();
}
[/sourcecode]
3. For instance, when a button is pushed, the PayPalFuturePaymentActivity will be launched:
[sourcecode language=”java” wraplines=”false” collapse=”false”]
public void onFuturePaymentPressed(View pressed) {
Intent intent = new Intent(SampleActivity.this, PayPalFuturePaymentActivity.class);
//For reliable restarts, always send the same configuration.
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
startActivityForResult(intent, REQUEST_CODE_FUTURE_PAYMENT);
}
[/sourcecode]
4. Implement onActivityResult():
[sourcecode language=”java” wraplines=”false” collapse=”false”]
@Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
PayPalAuthorization auth = data
.getParcelableExtra(PayPalFuturePaymentActivity.EXTRA_RESULT_AUTHORIZATION);
if (auth != null) {
try {
String authorization_code = auth.getAuthorizationCode();
sendAuthorizationToServer(auth);
} catch (JSONException e) {
Log.e("FuturePaymentExample", "an extremely unlikely failure occurred: ", e);
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.i("FuturePaymentExample", "The user canceled.");
} else if (resultCode == PayPalFuturePaymentActivity.RESULT_EXTRAS_INVALID) {
Log.i("FuturePaymentExample",
"Probably the attempt to previously start the PayPalService had an invalid PayPalConfiguration. Please see the docs.");
}
}
[/sourcecode]
5. Send your server the authorization answer to complete the process.
[sourcecode language=”java” wraplines=”false” collapse=”false”]
private void sendAuthorizationToServer(PayPalAuthorization authorization) {
// TODO:
// Send the authorization answer to your server, where the authorization code can be exchanged.
// for OAuth access and refresh tokens.
//
// Then, these tokens must be stored on your server so that your server code can process payments.
// for this user in the future.
}
[/sourcecode]
6.Get a Client Metadata ID:
Your mobile application needs a Client Metadata Id from the Mobile SDK to give to your server when starting a pre-consented payment (a “future payment”) from a mobile device. This Client Metadata ID must be contained in your server’s payment request to PayPal. PayPal uses this Client Metadata ID to verify that the payment is originating from a valid, user-consented device+application.
Example:
[sourcecode language=”java” wraplines=”false” collapse=”false”]
public void onFuturePaymentPurchasePressed(View pressed) {
// Get the Client Metadata ID from the SDK
String metadataId = PayPalConfiguration.getClientMetadataId(this);
// TODO: Send metadataId and transaction details to your server for processing with
// PayPal…
}
[/sourcecode]
Your server must include a PayPal-Client-Metadata-Id HTTP header with the Client Metadata ID value obtained from the SDK when it sends a payment request to PayPal.
Future Payments Server-Side Integration:
When a user grants your app permission to access their PayPal account, you can utilise that permission to get tokens that will allow you to create future payments from that user.
To exchange the authorization code for OAuth2 tokens and establish payments with an access token and a Metadata ID, see Future Payments Server-Side Integration.
3. Profile Sharing:
This section explains how to get a user’s express agreement to share their PayPal account’s profile information.
When your client connects in to PayPal and gives PayPal permission to share information with you:
To share information from a customer’s PayPal account, you must get their permission.
How it operates
- On the PayPal Developer site…
1. Identify the details that you want your clients to share with you.
- The PayPal Android SDK…
1. Displays UI to allow users to log in with their PayPal accounts.
2. Requests OAuth access token approval from the user before using PayPal for profile sharing.
3. Provides your app with an OAuth2 permission code.
Your app…
1. Indicates the necessary scopes in the SDK request
2. OAuth2 authorization code is transmitted by the SDK.
3. Click Advanced choices after selecting Log In with PayPal under APP CAPABILITIES.
4. Your server then contacts PayPal to request the pertinent client data using its OAuth2 tokens.
Indicate the Information You Would Like Shared On the PayPal Developer Site:
1. Log in to the PayPal Developer site.
2. Select your app.
3. Under APP CAPABILITIES select Log In with PayPal, and click Advanced options.
4. Under Information requested from customers select the items (“scope attributes”) you wish to have shared.
5. If you provide Privacy Policy and User Agreement URLs under Links shown on customer consent page, these will override the corresponding URLs that you provide below in the PayPalConfiguration object.
Obtain Customer Consent
1. Create a PayPalConfiguration object. Using this object, you can customise a number of SDK features, including:
[sourcecode language=”java” wraplines=”false” collapse=”false”]
private static PayPalConfiguration config = new PayPalConfiguration()
// Start with mock environment. When ready, switch to sandbox (ENVIRONMENT_SANDBOX)
// or live (ENVIRONMENT_PRODUCTION)
.environment(PayPalConfiguration.ENVIRONMENT_NO_NETWORK)
.clientId("<YOUR_CLIENT_ID>")
// You must set a minimum of three merchant information properties.
// These should match the data you submitted to PayPal when you registered your application.
.merchantName("Hipster Store")
.merchantPrivacyPolicyUri(Uri.parse("https://www.example.com/privacy"))
.merchantUserAgreementUri(Uri.parse("https://www.example.com/legal"));
[/sourcecode]
2. Start the PayPalService when the activity is created and terminate it when the activity is destroyed:
[sourcecode language=”java” wraplines=”false” collapse=”false”]
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, PayPalService.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
startService(intent);
}
@Override
public void onDestroy() {
stopService(new Intent(this, PayPalService.class));
super.onDestroy();
}
[/sourcecode]
3. Launch the PayPalProfileSharing activity, for example, when a button is pressed:
[sourcecode language=”java” wraplines=”false” collapse=”false”]
public void onProfileSharingPressed(View pressed) {
Intent intent = new Intent(SampleActivity.this, PayPalProfileSharingActivity.class);
// transmit the identical configuration for restart resilience
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
intent.putExtra(PayPalProfileSharingActivity.EXTRA_REQUESTED_SCOPES, getOauthScopes());
startActivityForResult(intent, REQUEST_CODE_PROFILE_SHARING);
}
[/sourcecode]
The PayPalOAuthScopes are initialised using a collection of scope names:
[sourcecode language=”java” wraplines=”false” collapse=”false”]
private PayPalOAuthScopes getOauthScopes() {
/* create the set of required scopes
* Note: see https://developer.paypal.com/docs/integration/direct/identity/attributes/ for mapping between the
* The attributes you choose for this app in the PayPal developer interface and the required scopes are displayed here.
*/
Set<String> scopes = new HashSet<String>(
Arrays.asList(PayPalOAuthScopes.PAYPAL_SCOPE_EMAIL, PayPalOAuthScopes.PAYPAL_SCOPE_ADDRESS) );
return new PayPalOAuthScopes(scopes);
}
[/sourcecode]
4. Implement onActivityResult():
[sourcecode language=”java” wraplines=”false” collapse=”false”]
@Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
PayPalAuthorization auth = data
.getParcelableExtra(PayPalProfileSharingActivity.EXTRA_RESULT_AUTHORIZATION);
if (auth != null) {
try {
String authorization_code = auth.getAuthorizationCode();
sendAuthorizationToServer(auth);
} catch (JSONException e) {
Log.e("ProfileSharingExample", "an extremely unlikely failure occurred: ", e);
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.i("ProfileSharingExample", "The user canceled.");
} else if (resultCode == PayPalProfileSharingActivity.RESULT_EXTRAS_INVALID) {
Log.i("ProfileSharingExample",
“Most likely, the PayPalService was previously attempted to start with an improper PayPal configuration. Please see the docs.");
}
}
[/sourcecode]
5.The final step requires you to relay the authorization answer to your server.
[sourcecode language=”java” wraplines=”false” collapse=”false”]
private void sendAuthorizationToServer(PayPalAuthorization authorization) {
// TODO:
// To exchange the authorisation code, send the authorization answer to your server.
// for OAuth access and refresh tokens.
//
// Then, your server needs to store these tokens so that the code on your server can use them.
// to get information about a user’s profile in the future.
}
[/sourcecode]
Profile Sharing Server Side Integration:
Read Profile Sharing Server-Side Integration to exchange the authorization code for OAuth2 tokens and retrieve the customer information from PayPal.
The Sandbox Environment:
PayPal provides a test environment, called Sandbox, using which a developer can mock transactions to test and debug his/her application.
You can test and debug your application without making any reference to actual PayPal users or their active PayPal accounts by using fictional Sandbox test accounts and the related authentication credentials. The Sandbox lets you operate your application in a safe environment and provides you a way to fine tune your PayPal routines before moving your product into production.
PayPal generates a mock transaction that functions precisely like a real transaction when you start a transaction utilising Sandbox test accounts.
The PayPal Sandbox environment comprises the following:
- The Sandbox Test Site (https://www.sandbox.paypal.com/)
- The Sandbox Accounts page (accessed through https://developer.paypal.com)
During your testing phase, create and manage your set of test accounts from the Sandbox Accounts page. Use the Sandbox test site to look at the transactions related to the calls you make with your test accounts. Log in to the Sandbox test site with the credentials from any of your test accounts to review the status of the mock transactions associated with that account.
PayPal Sandbox test site:
To access the PayPal Sandbox test site, log in using one of your Personal accounts. For instance, after creating the personal account “develope@gmail.com,” I was directed to the account details page shown below after logging in with it.
Going Live
Go live by moving your application to PayPal’s production environment once you have done developing and debugging it (including testing each PayPal API call in the Sandbox).
As soon as you have finished pushing your app to production, the PayPal SDK integration in your Android app will be finished as well.