+3

Paypal Service for Android

cara mengisi saldo paypal gratis.png

Paypal

PayPal is the faster, safer way to send money, make an online payment, receive money or set up a merchant account. PayPal Holdings, Inc. operates a worldwide online payments system. PayPal is one of the world's largest internet payment companies. So, nowadays it's another demanding feature for the commercial IT services & products.

Integrating Paypal Service With Android

The PayPal Android SDK makes it easy to add PayPal and credit card payments to mobile apps. The SDK supports two use cases for making payments - Single Payment and Future Payments - and a third use case for obtaining information about the customer - Profile Sharing. The steps of integrating paypal services in Android is summerized below.

Step-1: Paypal Account Setup For Development

You need a paypal account for development & testing which can be created in Paypal's developer site: https://developer.paypal.com/webapps/developer/applications

After creating & logging in the site you can see the page like below-

Screenshot 2015-10-22 02.59.55.png

Now, you can create your app here to sync with the paypal service. Before creating an app, for the security issue you need to acknowledge about several terms such as-

Credentials

Your mobile integration requires different client_id values for each environment: Test (Sandbox) and Live.

Your server integrations for verifying or creating payments will also require the corresponding client_secret for each client_id. You can obtain these PayPal API credentials by logging in the above site with your PayPal account.

Sandbox Environment

Once logged in on the Applications page, you will be assigned test credentials, including client_id, which will let you test your Android integration against the PayPal Sandbox. While testing your app, when logging in to PayPal in the SDK's UI you should use a personal Sandbox account email and password. I.e., not your Sandbox business credentials.

Live Environment

To obtain your live credentials, you will need to have a business account. If you don't yet have a business account, there is a link at the bottom of that same Applications page that will get you started. For the development work, you can test your project firstly you need to get a Client ID in Sandbox environment. Later, you can get the Client ID in Live environment as the similer procedure. There are options available for both.

Note: The Client IDs of Sandbox & Live Environment are different.

Step-2: Create App On Sandbox Environment For The Client ID

  1. On the developer's site, after logging with your paypal verified account you will see a button "Create App". After clicking this you will get a form to fill-up data for your app like below-

Screenshot 2015-10-22 03.22.31.png

After creating app you can see the application's dashboard like below-

Screenshot 2015-10-22 03.33.03.png

Now, you can get the Client ID from here to test in Sandbox Environment. You can store the ID in somewhere & let's make an Android sample app to test!

Step-3: Add the SDK to Your Android Project

  1. Create a new Android project.

  2. Go to https://github.com/paypal/PayPal-Android-SDK to download or clone this repo.

  3. Copy all the contents of the SDK libs directory into your project's libs directory. The path to these files is important; if it is not exactly correct, the SDK will not work.

  4. Add the open source license acknowledgments from acknowledgments.md to your app's acknowledgments.

Troubleshoot For Gradle

If you are using Gradle, copy SDK jar file into your project's libs directory, add as library to project, and finally copy the SDK folders containing the *.so files into src/main/jniLibs.

Step-4: Write Code In Your Android Project

After getting the client_id value you can create a sample app to test like following-

  1. Create activity_main.xml including following code:
		<LinearLayout
		    xmlns:android="http://schemas.android.com/apk/res/android"
    		xmlns:tools="http://schemas.android.com/tools"
    		android:layout_width="match_parent"
    		android:layout_height="match_parent"
    		tools:context=".MainActivity"
    		android:orientation="vertical"
    		android:padding="8dp"
    		android:background="@android:color/white">

    		<Button
        		android:id="@+id/buyItBtn"
        		android:layout_width="match_parent"
        		android:layout_height="wrap_content"
        		android:layout_marginTop="20dp"
        		android:onClick="onBuyPressed"
        		android:text="Buy Using Paypal"
        		android:textColor="@android:color/holo_blue_dark"/>

    		<Button
        		android:id="@+id/futurePaymentBtn"
        		android:layout_width="match_parent"
        		android:layout_height="wrap_content"
        		android:layout_marginTop="20dp"
        		android:onClick="onFuturePaymentPressed"
        		android:text="Future Payment Consent"
        		android:textColor="@android:color/holo_blue_dark"/>

    		<Button
        		android:id="@+id/futurePaymentPurchaseBtn"
        		android:layout_width="match_parent"
        		android:layout_height="wrap_content"
        		android:layout_marginTop="20dp"
        		android:onClick="onFuturePaymentPurchasePressed"
        		android:text="Future Payment Purchase"
        		android:textColor="@android:color/holo_blue_dark"/>

    		<Button
        		android:id="@+id/profileSharingBtn"
        		android:layout_width="match_parent"
        		android:layout_height="wrap_content"
        		android:layout_marginTop="20dp"
        		android:onClick="onProfileSharingPressed"
        		android:text="Profile Sharing Consent"
                android:textColor="@android:color/holo_blue_dark"/>
        </LinearLayout>
  1. Create MainActivity.java including following code:
	package <your package name>;

	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.PayPalOAuthScopes;
	import com.paypal.android.sdk.payments.PayPalPayment;
	import com.paypal.android.sdk.payments.PayPalProfileSharingActivity;
	import com.paypal.android.sdk.payments.PayPalService;
	import com.paypal.android.sdk.payments.PaymentActivity;
	import com.paypal.android.sdk.payments.PaymentConfirmation;

	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;
	import java.util.Arrays;
	import java.util.HashSet;
	import java.util.Set;

	public class MainActivity extends Activity {
	private static final String TAG = "paymentExample";
	private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_SANDBOX;

	// PayPalConfiguration.ENVIRONMENT_PRODUCTION  -- Live
	// PayPalConfiguration.ENVIRONMENT_SANDBOX -- Sandbox

	private static final String CONFIG_CLIENT_ID = "APP-BLA BLA BLA";

	private static final int REQUEST_CODE_PAYMENT = 1;
	private static final int REQUEST_CODE_FUTURE_PAYMENT = 2;
	private static final int REQUEST_CODE_PROFILE_SHARING = 3;

	private static PayPalConfiguration config = new PayPalConfiguration()
			.environment(CONFIG_ENVIRONMENT)
			.clientId(CONFIG_CLIENT_ID)
					// The following are only used in PayPalFuturePaymentActivity.
			.merchantName("Example Merchant")
			.merchantPrivacyPolicyUri(Uri.parse("https://www.example.com/privacy"))
			.merchantUserAgreementUri(Uri.parse("https://www.example.com/legal"));

	@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);
	}

	public void onBuyPressed(View pressed) {

		PayPalPayment thingToBuy = getThingToBuy(PayPalPayment.PAYMENT_INTENT_SALE);
		Intent intent = new Intent(MainActivity.this, PaymentActivity.class);
		// send the same configuration for restart resiliency
		intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
		intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
		startActivityForResult(intent, REQUEST_CODE_PAYMENT);
	}

	private PayPalPayment getThingToBuy(String paymentIntent) {
		return new PayPalPayment(new BigDecimal("1.75"), "USD", "sample item",
				paymentIntent);
	}

	public void onProfileSharingPressed(View pressed) {
		Intent intent = new Intent(MainActivity.this, PayPalProfileSharingActivity.class);

		// send the same configuration for restart resiliency
		intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);

		intent.putExtra(PayPalProfileSharingActivity.EXTRA_REQUESTED_SCOPES, getOauthScopes());

		startActivityForResult(intent, REQUEST_CODE_PROFILE_SHARING);
	}

	private PayPalOAuthScopes getOauthScopes() {

		Set<String> scopes = new HashSet<String>(
				Arrays.asList(PayPalOAuthScopes.PAYPAL_SCOPE_EMAIL, PayPalOAuthScopes.PAYPAL_SCOPE_ADDRESS) );
		return new PayPalOAuthScopes(scopes);
	}

	@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));

						Toast.makeText(
								getApplicationContext(),
								"PaymentConfirmation info received from PayPal", Toast.LENGTH_LONG)
								.show();

					} catch (JSONException e) {
						Log.e(TAG, "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");
			}
		} else if (requestCode == REQUEST_CODE_FUTURE_PAYMENT) {
			if (resultCode == Activity.RESULT_OK) {
				PayPalAuthorization auth =
						data.getParcelableExtra(PayPalFuturePaymentActivity.EXTRA_RESULT_AUTHORIZATION);
				if (auth != null) {
					try {
						Log.i("FuturePaymentExample", auth.toJSONObject().toString(4));

						String authorization_code = auth.getAuthorizationCode();
						Log.i("FuturePaymentExample", authorization_code);

						sendAuthorizationToServer(auth);
						Toast.makeText(
								getApplicationContext(),
								"Future Payment code received from PayPal", Toast.LENGTH_LONG)
								.show();

					} catch (JSONException e) {
						Log.e("FuturePaymentExample", "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 Invalid PayPalConfiguration");
			}
		} else if (requestCode == REQUEST_CODE_PROFILE_SHARING) {
			if (resultCode == Activity.RESULT_OK) {
				PayPalAuthorization auth =
						data.getParcelableExtra(PayPalProfileSharingActivity.EXTRA_RESULT_AUTHORIZATION);
				if (auth != null) {
					try {
						Log.i("ProfileSharingExample", auth.toJSONObject().toString(4));

						String authorization_code = auth.getAuthorizationCode();
						Log.i("ProfileSharingExample", authorization_code);

						sendAuthorizationToServer(auth);
						Toast.makeText(
								getApplicationContext(),
								"Profile Sharing code received from PayPal", Toast.LENGTH_LONG)
								.show();

					} catch (JSONException e) {
						Log.e("ProfileSharingExample", "Unlikely failure occurred: ", e);
					}
				}
			} else if (resultCode == Activity.RESULT_CANCELED) {
				Log.i("ProfileSharingExample", "The user canceled.");
			} else if (resultCode == PayPalFuturePaymentActivity.RESULT_EXTRAS_INVALID) {
				Log.i(
						"ProfileSharingExample",
						"Probably Invalid PayPalConfiguration.");
			}
		}
	}

	private void sendAuthorizationToServer(PayPalAuthorization authorization) {

	}

	public void onFuturePaymentPurchasePressed(View pressed) {
		// Get the Client Metadata ID from the SDK
		String metadataId = PayPalConfiguration.getClientMetadataId(this);

		Log.i("FuturePaymentExample", "Client Metadata ID: " + metadataId);

		// TODO: Send metadataId and transaction details to your server for processing with
		// PayPal...
		Toast.makeText(
				getApplicationContext(), "Client Metadata Id received from SDK", Toast.LENGTH_LONG)
				.show();
	}

	@Override
	public void onDestroy() {
		// Stop service when done
		stopService(new Intent(this, PayPalService.class));
		super.onDestroy();
		    }
		}

Here, you can change the environment in java as:

  • PayPalConfiguration.ENVIRONMENT_PRODUCTION to move real money.
  • PayPalConfiguration.ENVIRONMENT_SANDBOX to use your test credentials
  • PayPalConfiguration.ENVIRONMENT_NO_NETWORK to kick the tires without communicating to PayPal's servers.

Warning: Don't leave CONFIG_CLIENT_ID with invalid or blank Client ID, otherwise it causes RuntimeException.

  1. Update your AndroidManifest.xml as following:
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="<Your Package Name>"
        android:versionCode="1"
        android:versionName="1.0" >

        <uses-sdk
            android:minSdkVersion="8"
            android:targetSdkVersion="21" />

        <!-- for card.io card scanning -->
        <uses-permission android:name="android.permission.CAMERA" />
        <uses-permission android:name="android.permission.VIBRATE" />

        <uses-feature android:name="android.hardware.camera" android:required="false" />
        <uses-feature android:name="android.hardware.camera.autofocus" android:required="false" />

        <!-- for most things, including card.io & paypal -->
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
        <uses-permission android:name="android.permission.INTERNET"/>

        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name" >
            <activity
                android:name=".MainActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>

            <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="com.paypal.android.sdk.payments.PayPalProfileSharingActivity" />
            <activity android:name="com.paypal.android.sdk.payments.ProfileSharingConsentActivity" />

            <activity
                android:name="io.card.payment.CardIOActivity"
                android:configChanges="keyboardHidden|orientation" />
            <activity android:name="io.card.payment.DataEntryActivity" />

        </application>

    </manifest>

Step-5: Test The Sample App

After successfully build & run the project you can see the activities as below-

device-2015-10-22-133541.png device-2015-10-22-133612.png

**Facts about Paypal SDK **

paypal-hands2.jpg

  • PayPal Mobile SDKS provides sleek, native UI interface.
  • Support for 25 different currencies &190+ markets.
  • Extensive PayPal Security & Fraud protection mechanisms.
  • Returns a proof of payment – or transaction errors.
  • Identifies the user, and creates payment transaction.

**Enjoy! **


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí