Integrate PayPal Account to your Android Application
When considering a mobile apps, most of the application required payment
gateway functions in order to make the users of the app for the payment
functionality
1. It can be used to update the license of the application.
2. It can be used to buy credits to do some fun stuff like playing game and sticker purchasing
3. It can be used to make payment for e-portal app, where you can buy goods
Basically nowadays in mobile app Paypal, Google Wallet are popularly used.
So in our Global Messenger Mobile app as I specified in my previous post we have used PayPal Payment Gateway to facilitate the user of the application to make their license update payments
Here we start on how to integrate PayPal gateway with your android app...
Follow the steps
1. https://github.com/paypal/PayPal-Android-SDK
direct to this github link and download as a zip.
You can find this link through
5. In this step i will explain how you get the unique client id for your app, this client id need to be used in the code, i will explain in the following steps on how to use the client id
Lets move on to get the client id..
Once you created the app, you will get a Client ID under Rest API section.
5. Go to your android project and add these permissions and activity in your Manifest file
Permissions
==========
<!-- for credit card i/o scanning -->
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.VIBRATE" />
<!-- for most things, including card.io & paypal -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
Features
==========
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false" />
Activities - Inside application tag
==========
<service android:name="com.paypal.android.sdk.payments.PayPalService"
android:exported="false" />
<activity android:name="com.paypal.android.sdk.payments.PaymentActivity" />
<activity android:name="com.paypal.android.sdk.payments.LoginActivity" />
<activity android:name="com.paypal.android.sdk.payments.PaymentMethodActivity" />
<activity android:name="com.paypal.android.sdk.payments.PaymentConfirmActivity" />
<activity android:name="com.paypal.android.sdk.payments.PayPalFuturePaymentActivity" />
<activity android:name="com.paypal.android.sdk.payments.FuturePaymentConsentActivity" />
<activity android:name="com.paypal.android.sdk.payments.FuturePaymentInfoActivity" />
<activity
android:name="io.card.payment.CardIOActivity"
android:configChanges="keyboardHidden|orientation" />
<activity android:name="io.card.payment.DataEntryActivity" />
6.Lets Move to the coding
Create an activity called PaymentInfo.java and Layout with the layout name activity_payment_info.xml
In our app we have created the Payment Info Page like this
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:drawableLeft="@drawable/ic_paypal2"
android:onClick="onBuyPressed"
android:text="@string/paymentWay1"
/>
In PaymentInfo.java (Refer Note 2 in the bottom of this post)
private static final String TAG = "paymentExample";
/**
* - Set to PaymentActivity.ENVIRONMENT_PRODUCTION to move real money.
*
* - Set to PaymentActivity.ENVIRONMENT_SANDBOX to use your test credentials
* from https://developer.paypal.com
*
* - Set to PayPalConfiguration.ENVIRONMENT_NO_NETWORK to kick the tires
* without communicating to PayPal's servers.
*/
private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_SANDBOX;
//use the client id that you get from the above 4.5 step
private static final String CONFIG_CLIENT_ID = "DNbETD96Y77Gk2wyDYXK9kzgmUS4ES*************************";
private static final int REQUEST_CODE_PAYMENT = 1;
Inside Oncreate activity have the code like this
Intent intent = new Intent(this, PayPalService.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
startService(intent);
The Code to Button onclick event
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.
*
* Also, to include additional payment details and an item list, see getStuffToBuy() below.
*/
PayPalPayment thingToBuy = getThingToBuy(PayPalPayment.PAYMENT_INTENT_SALE);
Intent intent = new Intent(SampleActivity.this, PaymentActivity.class);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
startActivityForResult(intent, REQUEST_CODE_PAYMENT);
}
The Code to have the product details, here i have Hard coded the price and other details
private PayPalPayment getThingToRenew(String paymentIntent) {
return new PayPalPayment(new BigDecimal(0.99), "USD",
"1 Year License", paymentIntent);
}
The App provided number
private void addAppProvidedNumber(PayPalPayment paypalPayment) {
final String phoneNo = read(file2);
ShippingAddress phoneNumber = new ShippingAddress()
.recipientName(phoneNo);
paypalPayment.providedShippingAddress(phoneNumber);
}
Enable retrieval of shipping addresses from buyer's PayPal account
private void enablePhoneNumberRetrieval(PayPalPayment paypalPayment,
boolean enable) {
paypalPayment.enablePayPalShippingAddressesRetrieval(enable);
}
The Complete Code Will be Like This
package com.paypal.example.paypalandroidsdkexample;
import com.paypal.android.sdk.payments.PayPalAuthorization;
import com.paypal.android.sdk.payments.PayPalConfiguration;
import com.paypal.android.sdk.payments.PayPalFuturePaymentActivity;
import com.paypal.android.sdk.payments.PayPalItem;
import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PayPalPaymentDetails;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;
import com.paypal.android.sdk.payments.ShippingAddress;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import org.json.JSONException;
import java.math.BigDecimal;
public class PaymentInfo extends Activity {
1. It can be used to update the license of the application.
2. It can be used to buy credits to do some fun stuff like playing game and sticker purchasing
3. It can be used to make payment for e-portal app, where you can buy goods
Basically nowadays in mobile app Paypal, Google Wallet are popularly used.
So in our Global Messenger Mobile app as I specified in my previous post we have used PayPal Payment Gateway to facilitate the user of the application to make their license update payments
Here we start on how to integrate PayPal gateway with your android app...
Follow the steps
1. https://github.com/paypal/PayPal-Android-SDK
direct to this github link and download as a zip.
You can find this link through
- Go to https://developer.paypal.com/
- Click Mobile SDK Displayed to First box
- Then You will direct to a page like below
- Select PayPal Android SDK link
2. Find the Library in Extracted downloaded folder
There are four folders and PayPalAndroidSDK.jar file
3. What you need to do next is
Go to your project in Eclipse IDE
Select Project -> Right Click-> Project Properties->On Left Panel Select Java Build Path-> Go to Libraries Tab -> Add External Jar
Select the PayPalAndroidSDK jar file you downloaded in first step
Once you added the library, drop down 'lib' in your project folder
Select PayPalAndroidSDK. right click-> Build path -> Add to build path
and copy other four folder that you have download in first step and past it under 'lib' folder in your android project
4. This step to proceed with PayPal developer Site(Refer Note 1 in the bottom of this post)
Second as Personal account for the Buyer/sender of the payment
(refer 4.3 step again)
Go to Sandbox-> Account as shown below in the image
On the right panel Click 'Create Account' Button
So here we want to create two accounts as I mentioned above
Lets Create the test account for Buyer first....(Personal Account)
Lets Create the test account for Seller first...(Business account)
Select the PayPalAndroidSDK jar file you downloaded in first step
Once you added the library, drop down 'lib' in your project folder
Select PayPalAndroidSDK. right click-> Build path -> Add to build path
and copy other four folder that you have download in first step and past it under 'lib' folder in your android project
4. This step to proceed with PayPal developer Site(Refer Note 1 in the bottom of this post)
- First Direct to https://developer.paypal.com/
- SignUp for the login credential or if you already have a PayPal account get use of that account login credential
- Once you logged in successfully select 'Dashboard' tab in top
- In here I have created two testing profiles as Sandbox accounts for testing purposes
Second as Personal account for the Buyer/sender of the payment
(refer 4.3 step again)
Go to Sandbox-> Account as shown below in the image
On the right panel Click 'Create Account' Button
So here we want to create two accounts as I mentioned above
Lets Create the test account for Buyer first....(Personal Account)
- Select country as 'United States' or any other , better if you create as United States
- Select the account type as 'Personal Account'
- Enter a dummy e-mail address for the testing purpose login. ex: mayuran26@andexp.com
- Enter the password, first name, last name and the dummy PayPal balance that you want. ex 2000.00 USD
- select as Bank verified account, Payment card is anything you can use and select a card type
- click 'Create Account' button
- so you have successfully created the personal account. you can see the created account as shown below
Lets Create the test account for Seller first...(Business account)
- Select country as 'United States' or any other , better if you create as United States
- Select the account type as 'Business Account'
- Enter a dummy e-mail address for the testing purpose login. ex: mayuranb26@andexp.com
- Enter the password, first name, last name and the dummy PayPal balance that you want. ex 2000.00 USD
- select either Bank verified account, Payment card is anything you can use and select a card type Ex: VISA
- Tick 'I want to add Log In with PayPal to my site' and add Display name, and some required urls. any url will be accepted.
- click 'Create Account' button
- so you have successfully created the personal account. you can see the created account profile as shown below
So finally by above shown steps we could create the Personal and Business accounts
5. In this step i will explain how you get the unique client id for your app, this client id need to be used in the code, i will explain in the following steps on how to use the client id
Lets move on to get the client id..
- Choose My apps menu under Application
- Click 'Create App' button on right side panel
- Enter your App Name (Name of the Android Project in Eclipse IDE)
- Select the Business account that you have created in previous step as a Sandbox Developer Account
Once you created the app, you will get a Client ID under Rest API section.
5. Go to your android project and add these permissions and activity in your Manifest file
Permissions
==========
<!-- for credit card i/o scanning -->
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.VIBRATE" />
<!-- for most things, including card.io & paypal -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
Features
==========
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false" />
Activities - Inside application tag
==========
<service android:name="com.paypal.android.sdk.payments.PayPalService"
android:exported="false" />
<activity android:name="com.paypal.android.sdk.payments.PaymentActivity" />
<activity android:name="com.paypal.android.sdk.payments.LoginActivity" />
<activity android:name="com.paypal.android.sdk.payments.PaymentMethodActivity" />
<activity android:name="com.paypal.android.sdk.payments.PaymentConfirmActivity" />
<activity android:name="com.paypal.android.sdk.payments.PayPalFuturePaymentActivity" />
<activity android:name="com.paypal.android.sdk.payments.FuturePaymentConsentActivity" />
<activity android:name="com.paypal.android.sdk.payments.FuturePaymentInfoActivity" />
<activity
android:name="io.card.payment.CardIOActivity"
android:configChanges="keyboardHidden|orientation" />
<activity android:name="io.card.payment.DataEntryActivity" />
6.Lets Move to the coding
Create an activity called PaymentInfo.java and Layout with the layout name activity_payment_info.xml
In our app we have created the Payment Info Page like this
The PayPal Button Click xml in activity_payment_info.xml is like
<Buttonandroid:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:drawableLeft="@drawable/ic_paypal2"
android:onClick="onBuyPressed"
android:text="@string/paymentWay1"
/>
In PaymentInfo.java (Refer Note 2 in the bottom of this post)
private static final String TAG = "paymentExample";
/**
* - Set to PaymentActivity.ENVIRONMENT_PRODUCTION to move real money.
*
* - Set to PaymentActivity.ENVIRONMENT_SANDBOX to use your test credentials
* from https://developer.paypal.com
*
* - Set to PayPalConfiguration.ENVIRONMENT_NO_NETWORK to kick the tires
* without communicating to PayPal's servers.
*/
private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_SANDBOX;
//use the client id that you get from the above 4.5 step
private static final String CONFIG_CLIENT_ID = "DNbETD96Y77Gk2wyDYXK9kzgmUS4ES*************************";
private static final int REQUEST_CODE_PAYMENT = 1;
By using the following code we are going to create PayPal Configuration details
private static PayPalConfiguration config = new PayPalConfiguration()
.environment(CONFIG_ENVIRONMENT)
.clientId(CONFIG_CLIENT_ID)
.merchantName("Hipster Store")
.merchantPrivacyPolicyUri(Uri.parse("https://www.example.com/privacy"))
.merchantUserAgreementUri(Uri.parse("https://www.example.com/legal"));
Inside Oncreate activity have the code like this
Intent intent = new Intent(this, PayPalService.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
startService(intent);
The Code to Button onclick event
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.
*
* Also, to include additional payment details and an item list, see getStuffToBuy() below.
*/
PayPalPayment thingToBuy = getThingToBuy(PayPalPayment.PAYMENT_INTENT_SALE);
Intent intent = new Intent(SampleActivity.this, PaymentActivity.class);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
startActivityForResult(intent, REQUEST_CODE_PAYMENT);
}
The Code to have the product details, here i have Hard coded the price and other details
private PayPalPayment getThingToRenew(String paymentIntent) {
return new PayPalPayment(new BigDecimal(0.99), "USD",
"1 Year License", paymentIntent);
}
The App provided number
private void addAppProvidedNumber(PayPalPayment paypalPayment) {
final String phoneNo = read(file2);
ShippingAddress phoneNumber = new ShippingAddress()
.recipientName(phoneNo);
paypalPayment.providedShippingAddress(phoneNumber);
}
Enable retrieval of shipping addresses from buyer's PayPal account
private void enablePhoneNumberRetrieval(PayPalPayment paypalPayment,
boolean enable) {
paypalPayment.enablePayPalShippingAddressesRetrieval(enable);
}
@SuppressWarnings("deprecation")
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PAYMENT) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm = data
.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
Log.i(TAG, confirm.toJSONObject().toString(4));
Log.i(TAG, confirm.getPayment().toJSONObject()
.toString(4));
AlertDialog ad = new AlertDialog.Builder(this).create();
ad.setCancelable(false); // This blocks the 'BACK' button
ad.setMessage("Payment Confirmation info received from PayPal");
ad.setButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
ad.show();
saveExpDate("2014-12-23");
} catch (JSONException e) {
Log.e(TAG, "an extremely unlikely failure occurred: ",
e);
}
}
}
else if (resultCode == Activity.RESULT_CANCELED) {
Log.i(TAG, "The user canceled.");
}
else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
Log.i(TAG,
"An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
}
}
// /
}
The Complete Code Will be Like This
package com.paypal.example.paypalandroidsdkexample;
import com.paypal.android.sdk.payments.PayPalAuthorization;
import com.paypal.android.sdk.payments.PayPalConfiguration;
import com.paypal.android.sdk.payments.PayPalFuturePaymentActivity;
import com.paypal.android.sdk.payments.PayPalItem;
import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PayPalPaymentDetails;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;
import com.paypal.android.sdk.payments.ShippingAddress;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import org.json.JSONException;
import java.math.BigDecimal;
private static final String TAG = "paymentExample";
private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_SANDBOX;
private static final String CONFIG_CLIENT_ID = "AdKzfhDNbETD96Y77Gk2wyDYXK9kzgmUS4ESA*********************";
private static final int REQUEST_CODE_PAYMENT = 1;
private static PayPalConfiguration config = new PayPalConfiguration()
.environment(CONFIG_ENVIRONMENT)
.clientId(CONFIG_CLIENT_ID)
.merchantName("Global Messenger")
.merchantPrivacyPolicyUri(
Uri.parse("http://sepwecom.preview.kyrondesign.com"))
.merchantUserAgreementUri(
Uri.parse("http://sepwecom.preview.kyrondesign.com"));
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment_info);
Intent intent = new Intent(this, PayPalService.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
startService(intent);
}
public void onBuyPressed(View pressed) {
PayPalPayment yearToRenew = getThingToRenew(PayPalPayment.PAYMENT_INTENT_SALE);
Intent intent = new Intent(PaymentInfo.this, PaymentActivity.class);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, yearToRenew);
startActivityForResult(intent, REQUEST_CODE_PAYMENT);
}
private PayPalPayment getThingToRenew(String paymentIntent) {
return new PayPalPayment(new BigDecimal(0.99), "USD",
" 1 Year License", paymentIntent);
}
private void addAppProvidedNumber(PayPalPayment paypalPayment) {
ShippingAddress phoneNumber = new ShippingAddress()
.recipientName("07878789787");
paypalPayment.providedShippingAddress(phoneNumber);
}
private void enablePhoneNumberRetrieval(PayPalPayment paypalPayment,
boolean enable) {
paypalPayment.enablePayPalShippingAddressesRetrieval(enable);
}
@SuppressWarnings("deprecation")
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PAYMENT) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm = data
.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
Log.i(TAG, confirm.toJSONObject().toString(4));
Log.i(TAG, confirm.getPayment().toJSONObject()
.toString(4));
AlertDialog ad = new AlertDialog.Builder(this).create();
ad.setCancelable(false); // This blocks the 'BACK' button
ad.setMessage("Payment Confirmation info received from PayPal");
ad.setButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
ad.show();
} catch (JSONException e) {
Log.e(TAG, "an extremely unlikely failure occurred: ",
e);
}
}
}
else if (resultCode == Activity.RESULT_CANCELED) {
Log.i(TAG, "The user canceled.");
}
else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
Log.i(TAG,
"An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
}
}
}
private void sendAuthorizationToServer(PayPalAuthorization authorization) {
}
@Override
public void onDestroy() {
// Stop service when done
stopService(new Intent(this, PayPalService.class));
super.onDestroy();
}
}
Note :
1. When you connect to PayPal websites and create test accounts ,mean while you creating some time session time out can occur this is in order to maintain the security of PayPal , therefore in that case you should login again
2. Here I have hard coded some value is not same as our app provides, for you easiness I have hard coded some values in the code
Note :
1. When you connect to PayPal websites and create test accounts ,mean while you creating some time session time out can occur this is in order to maintain the security of PayPal , therefore in that case you should login again
2. Here I have hard coded some value is not same as our app provides, for you easiness I have hard coded some values in the code
If any suggestions or question or doubts feel free to comment
Thank you
Total Page View
Stats For Free
No comments:
Post a Comment