| config | ||
| features | ||
| lib | ||
| spec | ||
| .gitignore | ||
| .travis.yml | ||
| bitpay-sdk.gemspec | ||
| Gemfile | ||
| LICENSE.md | ||
| Rakefile | ||
| README.md | ||
BitPay Library for Ruby

Powerful, flexible, lightweight interface to the BitPay Bitcoin Payment Gateway API.
Installation
gem install bitpay-sdk
In your Gemfile:
gem 'bitpay-sdk', :require => 'bitpay_sdk'
Or directly:
require 'bitpay_sdk'
Configuration
The bitpay client creates a cryptographically secure connection to your server by pairing an API code with keys generated by the library. The client can be initialized with pre-existing keys passed in as a pem file, or paired if initialized with a pem file and a tokens hash. Examples can be found in the cucumber step helpers.
Command-line Interface (CLI)
BitPay also provides a command-line interface (CLI) which can be used to generate client-side cryptographic credentials and for client pairing with the BitPay service. Generally speaking, this is the easiest way to pair your client. The library must be installed as a local gem.
gem install bitpay-client
Source code and documentation for the Ruby CLI can be found at https://github.com/bitpay/ruby-cli
Client Setup
Pairing with Bitpay.com
Most calls to the BitPay REST API require that your client is paired with the bitpay.com server. To pair with bitpay.com you need to have an approved merchant account.
Your client can be paired via the pos (point-of-sale) or merchant facade (or both). The pos facade allows for invoices to be created. The merchant facade has broader privileges to view all invoices, bills, and ledger entries, as well as to issue refunds. Consider the level of access required when you pair your client.
Pairing can be performed via two separate methods:
To initiate pairing from the server
Suited for POS clients where pre-authorized tokens are desirable
- Login to your account
- Navigate to bitpay.com/api-tokens (Dashboard > My Account > API Tokens)
- Create a new token and copy the pairing code.
- Use the bitpay command line tool to pair with bitpay.com
bitpay pair <pairing_code>
To initiate pairing from the client
Suited to API clients that need merchant facade access
- Use the BitPay command line interface to generate a pairing code:
bitpay pairorbitpay pair --testfor the BitPay test server - Login to your account via the provided pairing URL and select the appropriate label and facade.
$ bitpay pair
Pairing code for https://bitpay.com: 2mLZjPZ.
Visit the link below to pair your client and select a facade:
https://bitpay.com/api-access-request?pairingCode=2mLZjPZ
Pairing Programattically
If you are developing a client which requires built-in pairing capability, or have other reason not to use the CLI, you can pair programattically. The example below demonstrates this using a locally generated PEM file using OpenSSL and the irb tool.
$ gem install bitpay-sdk
Successfully installed bitpay-sdk-2.2.0
1 gem installed
$ openssl ecparam -genkey -name secp256k1 -noout -out bitpaykey.pem
$ irb
2.1.1 :001 > require 'bitpay_sdk'
=> true
2.1.1 :002 > client = BitPay::SDK::Client.new(api_uri: 'https://test.bitpay.com', pem: File.read('bitpaykey.pem'), insecure: true)
=> #<BitPay::SDK::Client:0x000000019c6d40 @pem="---... @tokens={}>
2.1.1 :003 > client.pair_client()
=> {"data"=>[{"policies"=>[{"policy"=>"id", "method"=>"inactive", "params"=>["Tf49SFeiUAtytFEW2EUqZgWj32nP51PK73M"]}], "token"=>"BKQyVdaGQZAArdkkSuvtZN5gcN2355c8vXLj5eFPkfuK", "dateCreated"=>1422474475162, "pairingExpiration"=>1422560875162, "pairingCode"=>"Vy76yTh"}]}
As with the client-initiated pairing example above, use the value from the pairingCode element to register for the appropriate facade
General Usage
Initialize the client
client = BitPay::SDK::Client.new(pem: File.read('bitpaykey.pem')
Optional parameters:
api_uri- specify a different api endpoint (e.g. 'https://test.bitpay.com'). Ensure no trailing slash.tokens- pass a stored hash of bitpay API tokensuser-agent- specify a custom user-agent valuedebug: true- enable HTTP request logging to $stdoutinsecure: true- disable HTTPs certificate validation (for local test environments)
Create a new bitcoin invoice
invoice = client.create_invoice (price: <price>, currency: <currency>)
With invoice creation, price and currency are the only required fields. If you are sending a customer from your website to make a purchase, setting redirectURL will redirect the customer to your website when the invoice is paid.
Response will be a hash with information on your newly created invoice. Send your customer to the url to complete payment:
{
"url": "https://bitpay.com/invoice?id=NKaqMuZWy3BAcP77RdkEEv",
"paymentUrls": {
"BIP21": "bitcoin:mvYRECDxKPaPHnjNz9ZxiTpbx29xYNoRy4?amount=0.3745",
"BIP72": "bitcoin:mvYRECDxKPaPHnjNz9ZxiTpbx29xYNoRy4?amount=0.3745&r=https://bitpay.com/i/NKaqMuZWy3BAcP77RdkEEv",
"BIP72b": "bitcoin:?r=https://bitpay.com/i/NKaqMuZWy3BAcP77RdkEEv",
"BIP73": "https://bitpay.com/i/NKaqMuZWy3BAcP77RdkEEv"
},
"status": "new",
"btcPrice": "0.3745",
"btcDue": "0.3745",
"price": 148,
"currency": "USD",
"exRates": {
"USD": 395.20000000000005
},
"invoiceTime": 1415987168612,
"expirationTime": 1415988068612,
"currentTime": 1415987168629,
"guid": "438e8237-fff1-483c-81b4-dc7dba28922a",
"id": "NKaqMuZWy3BAcP77RdkEEv",
"transactions": [
],
"btcPaid": "0.0000",
"rate": 395.2,
"exceptionStatus": false,
"token": "9kZgUXFb5AC6qMuLaMpP9WopbM8X2UjMhkphKKdaprRbSKgUJNE6JNTX8bGsmgxKKv",
"buyer": {
}
}
There are many options available when creating invoices, which are listed in the BitPay API documentation.
Get invoice status
The ruby library provides two methods for fetching an existing invoice:
# For authorized clients with a 'merchant' token
client.get_invoice(id: 'PvVhgBfA7wKPWhuVC24rJo')
# For non-authenticated clients (public facade)
# Returns the public subset of invoice fields
client.get_public_invoice(id: 'PvVhgBfA7wKPWhuVC24rJo')
Create a refund request
Clients with a merchant token can initiate a refund request for a paid invoice:
client.refund_invoice(id: '6pbV13VBZfGFJ8BBmXmLZ8', params: {amount: 10, currency: 'USD'})
Refund rules:
- Invoices cannot be refunded prior to 6 blockchain confirmations
- Invoices without
["flags"]["refundable"] == truemust specify abitcoinAddressparam (one was not provided as part of the transaction) - Invoices that are paid in full must specify an
amountandcurrencyparam to indicate the amount to be refunded
View Refund Requests
The ruby library provides two methods for viewing refund requests. Both require a merchant token.
# To get an array of all refunds against a specific invoice
client.get_all_refunds_for_invoice(id: 'PvVhgBfA7wKPWhuVC24rJo')
# To get a specific refund for a specific invoice
client.get_refund(id: 'JB49z2MsDH7FunczeyDS8j', request_id: '4evCrXq4EDXk4oqDXdWQhX')
Make a HTTP request directly against the REST API
For API tasks which lack a dedicated library method, BitPay provides a method that will automatically apply the proper cryptographic parameters to a request.
client.send_request("GET", "/invoices/JB49z2MsDH7FunczeyDS8j", facade: 'merchant')
Usage:
- Specify HTTP verb and REST endpoint
- Specifying a
facadewill fetch and apply the correspondingtoken - Alternatively provide a
tokenexplicitly - For
POSTrequests, theparamshash will be included as the message body
Testnet Usage
During development and testing, take advantage of the Bitcoin TestNet by passing a custom api_uri option on initialization:
BitPay::SDK::Client.new({api_uri: "https://test.bitpay.com/api"})
Note that in order to pair with testnet, you will need a pairing code from test.bitpay.com and will need to use the bitpay client with the --test option.
API Documentation
API Documentation is available on the BitPay site.
Running the Tests
In order to run the tests, you must have phantomjs installed and on your PATH.
The tests require that environment variables be set for the bitpay server, user name, and password. First run:
$ source ./spec/set_constants.sh https://test.bitpay.com <yourusername> <yourpassword>
$ bundle install
$ bundle exec rake
Tests are likely to run up against rate limiters on test.bitpay.com if used too frequently. Rake tasks which interact directly with BitPay will not run for the general public.
Note that because of rate-limits applied on the API endpoints, you may experience errors when the tests are run repeatedly in a short timeframe.
In addition to a full test suite, there is Travis integration for MRI 1.9, JRuby and Rubinius.
Found a bug?
Let us know! Send a pull request or a patch. Questions? Ask! We're here to help. We will respond to all filed issues.
Contributors
Click here to see a list of the contributors to this library.