Giter VIP home page Giter VIP logo

openpay-android's Introduction

Openpay-Android

Android library designed to facilitate the processing collect credit card information from a devices directly invoking our services without invoking the origin server.

Current version: v3.0.1

Benefits:

  • The card information does not have to pass through the origin server, it is sent directly to Openpay.
  • It is the easiest and fastest way to integrate a card registration module on a device.

Installation

  1. Download de latest SDK released version (https://github.com/open-pay/openpay-android/releases/download/3.0.1/openpay-android-release.aar).
  2. You must have installed the Android SDK with API Level 30.
  3. Add the openpay-android library (openpay-android-release.aar) to your project. (Look at this example if you don't known)
  4. Add the needed dependencies to your project:
dependencies {
        implementation 'com.android.support:support-fragment:28.0.0'
        implementation 'com.google.http-client:google-http-client:1.28.0'
        implementation 'com.google.http-client:google-http-client-android:1.28.0'
        implementation 'com.google.http-client:google-http-client-jackson2:1.28.0'
        implementation 'com.fasterxml.jackson.core:jackson-core:2.9.8'
        implementation 'org.slf4j:slf4j-log4j12:1.7.25'
        ...
}

Configuration

Before you can use openpay-android is necessary to configure: merchant id, public key and production Mode

The merchant id and public key were assigned when you created your account. With these data, Openpay can identify the account.

You must configure openpay when instatiate it:

	Openpay openpay = new Openpay("MERCHANT_ID", "PUBLIC_API_KEY", productionMode);

For Colombia:

	Openpay openpay = new Openpay("MERCHANT_ID", "PUBLIC_API_KEY", productionMode, OpCountry.COL);

For Peru:

	Openpay openpay = new Openpay("MERCHANT_ID", "PUBLIC_API_KEY", productionMode, OpCountry.PE);

Enable sandbox Mode

To test your implementation, there Sandox environment, which is enabled when you pass false value to parameter productionMode

Notes:
* Both MERCHANTID as PUBLIC_API_KEY, are obtained from the homepage of your account on the Openpay site.
* You should never use your private key along with the library, because it is visible on the client side.

Creating tokens

To create a token, you need to call the method Openpay.createToken():

openPay.createToken(CARD_OBJECT, OPERATION_CALLBACK);

Example of creating a token:

	Card card = new Card();
	card.holderName("Juan Perez Ramirez");
	card.cardNumber("4111111111111111");
	card.expirationMonth(12);
	card.expirationYear(20);
	card.cvv2("110");

	openpay.createToken(card, new OperationCallBack() {
				
				@Override
				public void onSuccess(OperationResult arg0) {
					//Handlo in success
				}
				
				@Override
				public void onError(OpenpayServiceException arg0) {
					//Handle Error
				}
				
				@Override
				public void onCommunicationError(ServiceUnavailableException arg0) {
					//Handle communication error
				}
			});	

The first parameter is a object containing information about the card, the last parameter define the methods that will be called after the operation was successful or failed (respectively). The result will be a token object. The definition of Token object find it here.

OperationCallBack methods

The OperationCallBack serve as handles of the result of the card creation.

onSuccess

This method is called when the card is successful created. Get a single parameter which is a OperationResult that contains the card object. Complete example of implementing a function onSuccess:

onSuccess(OperationResult operationResult)  {
		progressFragment.dismiss();
		this.clearData();
	    DialogFragment fragment = MessageDialogFragment.newInstance(R.string.card_added, this.getString(R.string.card_created));
        fragment.show(this.getFragmentManager(), this.getString(R.string.info));
}

onError

This method is called when occurs some error on creating a card. Get a single parameter of type OpenpayServiceException that contains the error code.

Complete example of implementing a function onError:

public void onError(OpenpayServiceException error) {
		error.printStackTrace();
		progressFragment.dismiss();
		int desc = 0;
		switch( error.getErrorCode()){
		 case 3001:
			 desc = R.string.declined;
			 break;
		 case 3002:
			 desc = R.string.expired;
			 break;
		 case 3003:
			 desc = R.string.insufficient_funds;
			 break;
		 case 3004:
			 desc = R.string.stolen_card;
			 break;
		 case 3005:
			 desc = R.string.suspected_fraud;
			 break;
			 
		 case 2002:
			 desc = R.string.already_exists;
			 break;
		default:
			desc = R.string.error_creating_card;
		}
		
		  DialogFragment fragment = MessageDialogFragment.newInstance(R.string.error, this.getString(desc));
	        fragment.show(this.getFragmentManager(), "Error");
	}

onCommunicationError

This method is called when the application cannot contact the Openpay server.

Card Validation Functions

Openpay-android also includes some utilities to validate a card.

Available methods are:

  • CardValidator.validateHolderName()
  • CardValidator.validateCVV()
  • CardValidator.validateExpiryDate()
  • CardValidator.validateNumber()

Number card validation

To validate a card number can use the method CardValidator.validateNumber().

This method receives as parameter a String with the card number to be validated and return one true / false if it is a valid card number and is accepted by Openpay. Example:

CardValidator.validateNumber("5555555555554444");

This method is very useful for determining whether a card number is valid and if a candidate for use with Openpay, so we recommend that you use before attempting create a card.

Examples:

OpenPay.card.validateCardNumber("5555555555554444"); // TRUE. Valid card number and accepted by OpenPay (MASTERCARD)

OpenPay.card.validateCardNumber("6011861883604117"); // FALSE. Number of valid card but not accepted by OpenPay (Discover)

Security Code Validation

To validate a security code is used the method CardValidator.validateCVV().

This method takes a cvv and card number as Strings and returns true / false if the string is valid. Example:

CardValidator.validateCVV("123", "5555555555554444"); // válido
CardValidator.validateCVV("1234", "5555555555554444"); // inválido
CardValidator.validateCVV("A23", "5555555555554444"); // inválido

Expiration date validation

For this purpose is used the method CardValidator.validateExpiryDate().

Receive two Integers as parameters to represent the month and year of expiry of the card. Returns true / false if the combination of both data, month and year, determine a valid expiration date. Example:

CardValidator.validateExpiryDate(1, 13); // inválido
CardValidator.validateExpiryDate(5, 15); // válido

Fraud detection using device data

OpenPay can use the device information of a transaction in order to better detect fraudulent transactions. To do this, add the following code to your activity or fragment, when collecting payment information:

String deviceIdString = openpay.getDeviceCollectorDefaultImpl().setup(activity);

This method generates an identifier for the customer's device data. This value needs to be stored during checkout, and sent to OpenPay when processing the charge.

The method takes one parameter:

Activity. The actual activity object.

Take a look at the openpay-android-example application to see everything put together.

openpay-android's People

Contributors

brunoriverapina avatar carloshe-perez avatar darkaz avatar ezhgnu avatar guillermo-delucio avatar hugohernandez avatar igrijalva avatar ismaelem avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

openpay-android's Issues

Generar cargos

Hola, he seguido los pasos y todo bien, pero ¿como puedo generar o que tipo de variable debo declarar para generar el cargo a tarjeta?

Gracias :)

minSdkVersion 19

Hi there,
I'm using your library as part of my project and wondered why minSdkVersion is set to 19? I had to change my project's minSdkVersion from 17 to 19.
Does your library have a limitation that requires to have minSdkVersion 19?
Thanks!

Integración con Firebase

Estoy, usando firebase en una app, ¿existe alguna forma de ligar openpay con firebase o de hacer los pagos desde Android?

Problemas cuando se genera el apk en debug y release

Cuando trato de instalar un apk en modo release la app crashea al momento de llegar a la parte de openpay. Pero si lo instalo en modo debug la app funciona sin problema. Mi pregunta aqui es si se necesita hacer una configuracion mas para openpay o el error es mio.

Source_id longuitud

Hola, estoy teniendo este error al momento de generar un cargo:
Uncaught OpenpayApiRequestError: source_id la longitud tiene que estar entre 0 y 25 in /app/vendor/openpay/sdk/data/OpenpayApiConnector.php:229

Es la respuesta de mi servidor después del método POST.
Estoy usando el SDK v2.0.3 de android.
Tengo entendido que el source id es el que se obtiene del Device_SessionId.

Estou corriendo el código en un Simulador de Android Studio.

¿Como lo puedo resolver?
Creo no es problema de mi servidor porque el código para IOS corre perfecto

Poibilidad de obtener tarjeta a partir de token previo

Hola,

He visto la documentación de la api, y no hay manera de recrear una tarjeta a partir de un token previo. Se puede implementar con el API Rest pero los suyo sería poder hacerlo desde el cliente.
En la librería de swift hay un método que es getTokenWithId en que pasas por parámetro un id token y te devuelve un token con la información de la tarjeta dentro.
Hay alguna manera de implementarlo?
Un saludo.

No deja agregar tarjeta cuando es productionMode = true

-Versión 2.0.3

Al intentar agregar una tarjeta y declarando Openpay(merchandId, apiKey, true), siendo productionMode = true, me regresa el siguiente error:

The api key or merchant id are invalid

Pero si pongo productionMode = false, se agrega correctamente.

device_session_id la longitud tiene que estar entre 0 y 32

I am getting this response from the openpay sandbox

{ http_code: 400,
error_code: 1001,
category: 'request',
description: 'device_session_id la longitud tiene que estar entre 0 y 32',
request_id: '02acc04c-09e0-4e2c-9358-25d4c9bd0ca7' }

The device_session_id variable is generated according to the openpay android sdk.

How can be this posible?

cambiar entre merchant y apikeys

Al parecer hay un problema en intentar usar diferentes apikeys en la misma sesión, no respeta la generación de un nuevo objeto openpay con diferentes datos, hay alguna forma de refrescar la instancia para que tome los nuevos datos y no utilice los anteriores?

Integracion con Flutter

Buenas! De casualidad hay un plugin de Openpay para integrar con Flutter? Actualmente existen 2 no oficiales, pero cuentan con funcionalidad básica / no suficiente para el ambiente de producción

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.