KhaasSorena / coinbase-java

Coinbase API v1 library for Java

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Coinbase Android SDK

Platform SDK version License

An easy way to buy, sell, send, and accept bitcoin through the Coinbase API.

This library is a wrapper around the Coinbase JSON API. It supports OAuth 2.0 for performing actions on other people's accounts.

Working with the SDK:

Other resources:

Installation

Using Maven

Add the following dependency to your project's Maven pom.xml:

<dependency>
	<groupId>com.coinbase</groupId>
	<artifactId>coinbase-android</artifactId>
	<version>3.0.0</version>
</dependency>

The library will automatically be pulled from Maven Central.

Using Gradle

dependencies {
    compile 'com.coinbase:coinbase-android:3.0.0'
}

Manual

You can build this library aar and all its dependencies to a folder as follows:

git clone git@github.com:coinbase/coinbase-java.git
./gradlew coinbase-java:assembleRelease
mv coinbase-java/build/outputs/aar/coinbase-java-release.aar $YOUR_JAR_DIRECTORY

Usage

Basic setup (only accessing public data)

Configure coinbase object to access public data.

// Set up Coinbase object for public data access only
val coinbase = CoinbaseBuilder.withPublicDataAccess(applicationContext).build()

// Get any of public data resource and request data from it
coinbase.currenciesResource.supportedCurrencies.enqueue(callback)

When 'coinbase' instance is setup for public data access you can use these resources:

  1. currenciesResource
  2. exchangeRatesResource
  3. pricesResource
  4. currenciesResource

OAuth 2.0 Authentication (accessing user's account data)

Start by creating a new OAuth 2.0 application. Register redirect url under Permitted Redirect URIs. This URL will be used after successful authorization. It should be an URL that your application is capable to handle, so auth result delivered back to your app.

After you create OAuth 2.0 application, go to application web page that will have an address like https://www.coinbase.com/oauth/applications/{your_app_id}. Copy Client Id and Client Secret to your android application.

Your android application can now be authorized to access user account data:

// Set up Coinbase object to access user data
val coinbase = CoinbaseBuilder.withClientIdAndSecret(applicationContext, clientId, clientSecret).build()

// Begin OAuth 2.0 flow with web sign in
coinbase.beginAuthorization(activityContext, redirectUri, scopes)

// Get result of web authorization as an intent with mentioned redirectUri. Complete OAuth 2.0 flow
override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        if (intent == null) return
        coinbase.completeAuthorizationRx(intent)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe { showProgress() }
                .doFinally { hideProgress() }
                .subscribe(subscriber)
}

After authorization suceseed, you can call methods on coinbase similar to the ones described in the Wallet Endpoints documentation. For example:

coinbase.userResource.getAuthInfo.enqueue(callback);

Examples

Get User currencies accounts

// get user accounts asynchronously.
coinbase.accountResource.getAccounts().enqueue(object: Callback<PagedResponse<Account>> {

    override fun onSuccess(result: PagedResponse<Account>?) {
            TODO("Process accounts data")
    }

    override fun onFailure(t: Throwable?) {
        TODO("process error")
    }
})

Get a specific account.

coinbase.accountResource.getAccount(accountId).enqueue(callback)

The account name can be changed with

coinbase.accountResource.updateAccount(accountId, newName).enqueue(callback)

Also, an account can be deleted

coinbase.accountResource.deleteAccount(accountId).enqueue(callback)

Send bitcoin

val sendMoneyRequest = SendMoneyRequest("user2@example.com", "0.01", "BTC")
coinbase.transactionsResource.sendMoney(accountId, twoFactorAuthToken, sendMoneyRequest).enqueue(callback)

The to value can be a bitcoin address and a description (notes) can be attached to the money. The description is only visible on Coinbase (not on the general bitcoin network).

val sendMoneyRequest = SendMoneyRequest("user2@example.com", "2.25", "USD")
sendMoneyRequest.setDescription("Thanks for the coffee!")
coinbase.transactionsResource.sendMoney(accountId, twoFactorAuthToken, sendMoneyRequest).enqueue(callback)

Request bitcoin

This will send an email to the recipient, requesting payment, and give them an easy way to pay.

// Synchronous calls are used for simplicity
val moneyRequest = MoneyRequest("user2@example.com", "100", "USD")
moneyRequest.setDescription("Invoice for window cleaning")
val moneyRequest = coinbase.transactionsResource.requestMoney(accountId, moneyRequest).execute().data

coinbase.transactionsResource.resendMoneyRequest(accountId, moneyRequest.id).execute()

coinbase.transactionsResource.cancelRequest(accountId, moneyRequest.id).execute()

// From the other side

coinbase.transactionsResource.completeRequest(accountId, transactionId).execute()

List your current transactions

By default sorted in descending order by createdAt, 30 transactions per page

// Synchronous call is used for simplicity
var transactions = coinbase.transactionsResource.listTransactions(accountId).execute().data
transactions[0].id

Transactions will always have an id attribute which is the primary way to identify them through the Coinbase API.

Get transaction details

This will fetch the details/status of a transaction that was made within Coinbase

// Synchronous call is used for simplicity
val t = coinbase.transactionsResource.showTransaction(accountId, transactionId).execute().data
t.status; // Transaction.STATUS_PENDING

Buy or Sell bitcoin

Buying and selling bitcoin requires you to add a payment method through the web app first.

Then you can call buy or sell and pass a quantity of bitcoin you want to buy.

val transferOrder = TransferOrderBody("0.01", "BTC", paymentMethodId)
// Synchronous call is used for simplicity
coinbase.buysResource.placeBuyOrder(accountId,transferOrder).execute()
val transferOrder = TransferOrderBody("0.01", "BTC", paymentMethodId)
// Synchronous call is used for simplicity
coinbase.sellsResource.placeSellOrder(accountId, transferOrder).execute()

Listing Buy/Sell History

You can use listBuys, listSells to view past buys and sells.

coinbase.buysResource.listBuys(accountId).enqueue(callback)
coinbase.sellsResource.listSells(accountId).enqueue(callback)

Check out the sample app with example of how to use the SDK (both async and Rx).

Proguard setup

If you are using proguard, include following lines to the application proguard properties file.

-dontwarn okio.**
-dontwarn retrofit2.**

Security Notes

When creating an API Key, make sure you only grant it the permissions necessary for your application to function.

You should take precautions to store your API key securely in your application. How to do this is application specific, but it's something you should research if you have never done this before.

Testing

If you'd like to contribute code or modify this library, you can run the test suite with:

./gradlew :coinbase-java:test

Contributing

  1. Fork this repo and make changes in your own copy
  2. Add Git pre-commit hook by executing ./add_precommit_git_hook.sh. This will add Checkstyle and pmd checks before commit
  3. Add a test if applicable and run the existing tests with ./gradlew :coinbase-java:test to make sure they pass
  4. Commit your changes and push to your fork git push origin master
  5. Create a new pull request and submit it back to us!

About

Coinbase API v1 library for Java

License:Apache License 2.0


Languages

Language:Java 92.8%Language:Kotlin 7.0%Language:Shell 0.2%