Step 1. Add the JitPack repository to your build file
Add it in your root settings.gradle at the end of repositories:
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
mavenCentral()
maven { url 'https://jitpack.io' }
}
}
Add it in your settings.gradle.kts at the end of repositories:
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
mavenCentral()
maven { url = uri("https://jitpack.io") }
}
}
Add to pom.xml
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
Add it in your build.sbt at the end of resolvers:
resolvers += "jitpack" at "https://jitpack.io"
Add it in your project.clj at the end of repositories:
:repositories [["jitpack" "https://jitpack.io"]]
Step 2. Add the dependency
dependencies {
implementation 'com.github.inpossoft:stripe-android:v3.0.2'
}
dependencies {
implementation("com.github.inpossoft:stripe-android:v3.0.2")
}
<dependency>
<groupId>com.github.inpossoft</groupId>
<artifactId>stripe-android</artifactId>
<version>v3.0.2</version>
</dependency>
libraryDependencies += "com.github.inpossoft" % "stripe-android" % "v3.0.2"
:dependencies [[com.github.inpossoft/stripe-android "v3.0.2"]]
Stripe-android makes it easy to collect credit card information without having sensitive details touch your server.
These Stripe Android bindings can be used to generate tokens in your Android application. If you are building an Android application that charges a credit card, you should use stripe-android to make sure you don't pass credit card information to your server (and, so, are PCI compliant).
No need to clone the repository or download any files -- just add this line to your app's build.gradle
inside the dependencies
section:
compile 'com.stripe:stripe-android:3.0.1'
Note: We recommend that you don't use compile 'com.stripe:stripe-android:+
, as future versions of the SDK may not maintain full backwards compatibility. When such a change occurs, a major version number change will accompany it.
Note - as Google has stopped supporting Eclipse for Android Development, we will no longer be actively testing the project's compatibility within Eclipse. You may still clone and include the library as you would any other Android library project.
If you're planning on optimizing your app with ProGuard, make sure that you exclude the Stripe bindings. You can do this by adding the following to your app's proguard.cfg
file:
-keep class com.stripe.** { *; }
You can add a widget to your apps that easily handles the UI states for collecting card data.
First, add the CardInputWidget to your layout.
<com.stripe.android.view.CardInputWidget
android:id="@+id/card_input_widget"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
Note: the minimum width for this widget is 320dp. The widget also requires an ID to ensure proper layout on rotation, so if you don't do this, we assign one for you when the object is instantiated.
Once this widget is in your layout, you can read the Card
object simply by asking the widget. You'll be given a null
object if the card data is invalid according to our client-side checks.
Card cardToSave = mCardInputWidget.getCard();
if (cardToSave == null) {
mErrorDialogHandler.showError("Invalid Card Data");
return;
}
Once you have a non-null Card
object, you can call createToken.
A publishable key is required to identify your website when communicating with Stripe. Remember to replace the test key with your live key in production.
You can get all your keys from your account page. This tutorial explains this flow in more detail.
new Stripe(context, "YOUR_PUBLISHABLE_KEY");
or
new Stripe(context).setDefaultPublishableKey("YOUR_PUBLISHABLE_KEY");
createToken converts sensitive card data to a single-use token which you can safely pass to your server to charge the user. The tutorial explains this flow in more detail.
stripe.createToken(
new Card("4242424242424242", 12, 2013, "123"),
tokenCallback
);
The first argument to createToken is a Card object. A Card contains the following fields:
The following field is optional but recommended to help prevent fraud:
The following fields are entirely optional — they cannot result in a token creation failing:
The second argument tokenCallback is a callback you provide to handle responses from Stripe. It should send the token to your server for processing onSuccess, and notify the user onError.
Here's a sample implementation of the token callback:
stripe.createToken(
card,
new TokenCallback() {
public void onSuccess(Token token) {
// Send token to your own web service
MyServer.chargeToken(token);
}
public void onError(Exception error) {
Toast.makeText(getContext(),
error.getLocalizedMessage(),
Toast.LENGTH_LONG).show();
}
}
);
createToken
is an asynchronous call – it returns immediately and invokes the callback on the UI thread when it receives a response from Stripe's servers.
The createTokenSynchronous
method allows you to handle threading on your own, using any IO framework you choose. In particular, you can now create a token using RxJava or an IntentService. Note: do not call this method on the main thread or your app will crash!
Observable<Token> tokenObservable =
Observable.fromCallable(
new Callable<Token>() {
@Override
public Token call() throws Exception {
// When executed, this method will conduct i/o on whatever thread it is run on
return stripe.createTokenSynchronous(cardToCharge);
}
});
tokenObservable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(
new Action0() {
@Override
public void call() {
// Show a progress dialog if you prefer
showProgressDialog();
}
})
.doOnUnsubscribe(
new Action0() {
@Override
public void call() {
// Close the progress dialog if you opened one
closeProgressDialog();
}
})
.subscribe(
new Action1<Token>() {
@Override
public void call(Token token) {
// Send token to your own web service
MyServer.chargeToken(token);
}
},
new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
// Tell the user about the error
handleError(throwable.getLocalizedMessage());
}
});
You can invoke the following from your code (where cardToSave
is some Card object that you have created.)
Intent tokenServiceIntent = TokenIntentService.createTokenIntent(
mActivity,
cardToSave.getNumber(),
cardToSave.getExpMonth(),
cardToSave.getExpYear(),
cardToSave.getCVC(),
mPublishableKey);
mActivity.startService(tokenServiceIntent);
Your IntentService can then perform the following in its onHandleIntent
method.
@Override
protected void onHandleIntent(Intent intent) {
String errorMessage = null;
Token token = null;
if (intent != null) {
String cardNumber = intent.getStringExtra(EXTRA_CARD_NUMBER);
Integer month = (Integer) intent.getExtras().get(EXTRA_MONTH);
Integer year = (Integer) intent.getExtras().get(EXTRA_YEAR);
String cvc = intent.getStringExtra(EXTRA_CVC);
String publishableKey = intent.getStringExtra(EXTRA_PUBLISHABLE_KEY);
Card card = new Card(cardNumber, month, year, cvc);
Stripe stripe = new Stripe();
try {
token = stripe.createTokenSynchronous(card, publishableKey);
} catch (StripeException stripeEx) {
errorMessage = stripeEx.getLocalizedMessage();
}
}
Intent localIntent = new Intent(TOKEN_ACTION);
if (token != null) {
// extract whatever information you want from your Token object
localIntent.putExtra(STRIPE_CARD_LAST_FOUR, token.getCard().getLast4());
localIntent.putExtra(STRIPE_CARD_TOKEN_ID, token.getId());
}
if (errorMessage != null) {
localIntent.putExtra(STRIPE_ERROR_MESSAGE, errorMessage);
}
// Broadcasts the Intent to receivers in this app.
LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);
}
Registering a local BroadcastReceiver in your activity then allows you to handle the results.
private class TokenBroadcastReceiver extends BroadcastReceiver {
private TokenBroadcastReceiver() { }
@Override
public void onReceive(Context context, Intent intent) {
mProgressDialogController.finishProgress();
if (intent == null) {
return;
}
if (intent.hasExtra(TokenIntentService.STRIPE_ERROR_MESSAGE)) {
// handle your error!
return;
}
if (intent.hasExtra(TokenIntentService.STRIPE_CARD_TOKEN_ID) &&
intent.hasExtra(TokenIntentService.STRIPE_CARD_LAST_FOUR)) {
// handle your resulting token here
}
}
}
}
The Card object allows you to validate user input before you send the information to Stripe.
Checks that the number is formatted correctly and passes the Luhn check.
Checks whether or not the expiration date represents an actual month in the future.
Checks whether or not the supplied number could be a valid verification code.
Convenience method to validate card number, expiry date and CVC.
The bindings for retrieving information about a token has been removed from the Android SDK because only older Stripe accounts (from early 2014) can perform this operation with a public key. If you still need this functionality, make sure to use the last version of the Android bindings that contained this functionality by setting your version in the build.gradle
file as follows.
// Using older bindings to have access to requestToken
compile 'com.stripe:stripe-android:1.1.1'
build.gradle
file at the top of the stripe-android
repository.Import -> General -> Existing Projects into Workspace
, and browsing to the stripe-android
folder.The example application ships with a sample publishable key, but if you want to test with your own Stripe account, you can replace the value of PUBLISHABLE_KEY in DependencyHandler with your test key.
Three different ways of creating tokens are shown, with all the Stripe-specific logic needed for each separated into the three controllers, AsyncTaskTokenController, RxTokenController, and IntentServiceTokenController.