Ejemplo de uso de la libreria de pagos de Paypal para Android

paypal_device
En uno de los proyectos Android del trabajo tenemos que incorporar pagos a través de Paypal.

La primera idea que hemos tenido ha sido intentar usar un componente webview que cargara el formulario Paypal, sin embargo la web no se mostraba todo lo bien que era de esperar.

Investigando alternativas, he visto que había una librería oficial de PayPal nativa para Android que facilita mucho las cosas, y con muy pocas lineas de código se puede crear un pago a través de este sistema.

El siguiente código es un ejemplo sencillo de uso, basado en el ejemplo que trae el SDK de Paypal. Le he limpiado el código dejando un solo ejemplo de uso (el pago sencillo), y lo he reconvertido para que use una tarea asíncrona en vez de un handler (no se porque, pero me resulta mas sencillo de usar).

La idea es que la librería debe inicializarse en segundo plano, ya que conectacon los servidores de Paypal. Una vez todo está ok, creamos un boton de pago, que al ser pulsado lanza una Activity que incorpora la propia librería pasando los datos del pedido, y esperamos su respuesta.

Para configurar el entorno de pruebas (sandbox) deberemos seguir las instrucciones de este manual.

package com.paypal.android.mplexample;

import java.math.BigDecimal;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Toast;

import com.paypal.android.MEP.CheckoutButton;
import com.paypal.android.MEP.PayPal;
import com.paypal.android.MEP.PayPalActivity;
import com.paypal.android.MEP.PayPalInvoiceData;
import com.paypal.android.MEP.PayPalInvoiceItem;
import com.paypal.android.MEP.PayPalPayment;

/**
 * Simple use example for the Paypal library
 *
 * @author http://francho.org
 *
 *         Based on the example provided by Paypal Android SDK
 *         https://www.x.com/community/ppx/sdks
 *
 */
public class CheckOutActivity extends Activity implements OnClickListener {

	private static final int REQUEST_PAY = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.main);

		InitPayPalLibraryAsyncTask task = new InitPayPalLibraryAsyncTask(this,
				this);

		task.execute();
	}

	public void onClick(View v) {
		PayPalPayment payment = getExampleSimplePayment();
		// Use checkout to create our Intent.
		Intent checkoutIntent = PayPal.getInstance().checkout(payment, this,
				new ResultDelegate());
		// Use the android's startActivityForResult() and pass in our Intent.
		// This will start the library.
		startActivityForResult(checkoutIntent, REQUEST_PAY);
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode != REQUEST_PAY) {
			return;
		}

		/**
		 * If you choose not to implement the PayPalResultDelegate, then you
		 * will receive the transaction results here. Below is a section of code
		 * that is commented out. This is an example of how to get result
		 * information for the transaction. The resultCode will tell you how the
		 * transaction ended and other information can be pulled from the Intent
		 * using getStringExtra.
		 */
		switch (resultCode) {
		case Activity.RESULT_OK:
			/*
			 * TODO
			 */
			break;
		case Activity.RESULT_CANCELED:
			/*
			 * TODO
			 */
			break;
		case PayPalActivity.RESULT_FAILURE:
			/*
			 * TODO
			 *
			 * resultInfo =
			 * data.getStringExtra(PayPalActivity.EXTRA_ERROR_MESSAGE);
			 * resultExtra = "Error ID: " +
			 * data.getStringExtra(PayPalActivity.EXTRA_ERROR_ID);
			 */
			break;
		}
	}

	private PayPalPayment getExampleSimplePayment() {
		// Create a basic PayPalPayment.
		PayPalPayment payment = new PayPalPayment();
		// Sets the currency type for this payment.
		payment.setCurrencyType("EUR");
		// Sets the recipient for the payment. This can also be a phone number.
		payment.setRecipient("example-merchant-1@paypal.com");
		// Sets the amount of the payment, not including tax and shipping
		// amounts.
		payment.setSubtotal(new BigDecimal("8.25"));
		// Sets the payment type. This can be PAYMENT_TYPE_GOODS,
		// PAYMENT_TYPE_SERVICE, PAYMENT_TYPE_PERSONAL, or PAYMENT_TYPE_NONE.
		payment.setPaymentType(PayPal.PAYMENT_TYPE_SERVICE);

		// PayPalInvoiceData can contain tax and shipping amounts. It also
		// contains an ArrayList of PayPalInvoiceItem which can
		// be filled out. These are not required for any transaction.
		PayPalInvoiceData invoice = new PayPalInvoiceData();
		// Sets the tax amount.
		invoice.setTax(new BigDecimal("1.25"));
		// Sets the shipping amount.
		invoice.setShipping(new BigDecimal("4.50"));

		// PayPalInvoiceItem has several parameters available to it. None of
		// these parameters is required.
		PayPalInvoiceItem item1 = new PayPalInvoiceItem();
		// Sets the name of the item.
		item1.setName("Pink Stuffed Bunny");
		// Sets the ID. This is any ID that you would like to have associated
		// with the item.
		item1.setID("87239");
		// Sets the total price which should be (quantity * unit price). The
		// total prices of all PayPalInvoiceItem should add up
		// to less than or equal the subtotal of the payment.
		item1.setTotalPrice(new BigDecimal("6.00"));
		// Sets the unit price.
		item1.setUnitPrice(new BigDecimal("2.00"));
		// Sets the quantity.
		item1.setQuantity(3);
		// Add the PayPalInvoiceItem to the PayPalInvoiceData. Alternatively,
		// you can create an ArrayList<PayPalInvoiceItem>
		// and pass it to the PayPalInvoiceData function setInvoiceItems().
		invoice.getInvoiceItems().add(item1);

		// Sets the PayPalPayment invoice data.
		payment.setInvoiceData(invoice);
		// Sets the merchant name. This is the name of your Application or
		// Company.
		payment.setMerchantName("The Gift Store");
		// Sets the description of the payment.
		payment.setDescription("Quite a simple payment");
		// Sets the Custom ID. This is any ID that you would like to have
		// associated with the payment.
		payment.setCustomID("8873482296");
		// Sets the Instant Payment Notification url. This url will be hit by
		// the PayPal server upon completion of the payment.
		payment.setIpnUrl("http://www.exampleapp.com/ipn");
		// Sets the memo. This memo will be part of the notification sent by
		// PayPal to the necessary parties.
		payment.setMemo("Hi! I'm making a memo for a simple payment.");

		return payment;
	}

	/**
	 * AsyncTask to init a simple Paypal buttom
	 *
	 * @author http://francho.org
	 *
	 */
	public class InitPayPalLibraryAsyncTask extends
			AsyncTask<Void, Void, Boolean> {
		// The PayPal server to be used - can also be ENV_NONE and ENV_LIVE
		private static final int PAYPAL_SERVER = PayPal.ENV_SANDBOX;
		// The ID of your application that you received from PayPal
		private static final String PAYPAL_APP_ID = "APP-80W284485P519543T";

		private Context context;
		private OnClickListener onClickListener;

		public InitPayPalLibraryAsyncTask(Context context,
				OnClickListener onClickListener) {
			this.context = context;
			this.onClickListener = onClickListener;
		}

		/**
		 * The hard task (requires connect with the server) will be do in
		 * background
		 */
		@Override
		protected Boolean doInBackground(Void... params) {
			PayPal pp = PayPal.getInstance();
			// If the library is already initialized, then we don't need to
			// initialize it again.
			if (pp == null) {
				// This is the main initialization call that takes in your
				// Context, the Application ID, and the server you would like to
				// connect to.
				pp = PayPal
						.initWithAppID(context, PAYPAL_APP_ID, PAYPAL_SERVER);

				// -- These are required settings.
				pp.setLanguage("es_ES"); // Sets the language for the library.
				// --

				// -- These are a few of the optional settings.
				// Sets the fees payer. If there are fees for the transaction,
				// this person will pay for them. Possible values are
				// FEEPAYER_SENDER,
				// FEEPAYER_PRIMARYRECEIVER, FEEPAYER_EACHRECEIVER, and
				// FEEPAYER_SECONDARYONLY.
				pp.setFeesPayer(PayPal.FEEPAYER_EACHRECEIVER);
				// Set to true if the transaction will require shipping.
				pp.setShippingEnabled(false);
				// Dynamic Amount Calculation allows you to set tax and shipping
				// amounts based on the user's shipping address. Shipping must
				// be
				// enabled for Dynamic Amount Calculation. This also requires
				// you to create a class that implements PaymentAdjuster and
				// Serializable.
				pp.setDynamicAmountCalculationEnabled(false);
				// --
			}

			return PayPal.getInstance().isLibraryInitialized();
		}

		/**
		 * When the library init is finished, setup the pay button
		 */
		@Override
		protected void onPostExecute(Boolean isLibraryInitOk) {
			if (isLibraryInitOk) {
				PayPal pp = PayPal.getInstance();

				CheckoutButton launchSimplePayment = pp.getCheckoutButton(
						context, PayPal.BUTTON_194x37, CheckoutButton.TEXT_PAY);
				// You'll need to have an OnClickListener for the
				// CheckoutButton. For this application, MPL_Example implements
				// OnClickListener and we
				// have the onClick() method below.
				launchSimplePayment.setOnClickListener(onClickListener);
				// The CheckoutButton is an android LinearLayout so we can add
				// it to our display like any other View.

				ViewGroup paypalLayout = (ViewGroup) findViewById(R.id.PayPalBtnContainer);

				paypalLayout.addView(launchSimplePayment);
			} else {
				Toast.makeText(context,
						"Error al inicializar la libreria de paypal",
						Toast.LENGTH_LONG);
			}
		}

	}

}

About these ads

Acerca de francho

Maño, unutopico, geek, artesano de software, aprendiz ágil, programador Android en activo, sysop retirado, linuxero de corazón, papá a tiempo completo... Más en francho.org/about

Publicado el 29 diciembre, 2010 en Android. Añade a favoritos el enlace permanente. 2 comentarios.

Seguir

Recibe cada nueva publicación en tu buzón de correo electrónico.

Únete a otros 957 seguidores

%d personas les gusta esto: