Compare commits
51 Commits
bug-issue-
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6e656cce74 | ||
|
|
ba65ccb2f4 | ||
|
|
fc8d920c27 | ||
|
|
e9e2c1cc5e | ||
|
|
019140f049 | ||
|
|
7c74b936e0 | ||
|
|
357aac7a10 | ||
|
|
4751c66a37 | ||
|
|
ff3bce79de | ||
|
|
0acbbb5312 | ||
|
|
774d3d59a1 | ||
|
|
e90e3a188c | ||
|
|
98b88617d0 | ||
|
|
4c5d8adfad | ||
|
|
986ab1e3d6 | ||
|
|
b789faf87d | ||
|
|
53411dca98 | ||
|
|
0ec4bb1105 | ||
|
|
c534b83c31 | ||
|
|
671fe5657b | ||
|
|
d8890fa31a | ||
|
|
5f3881f602 | ||
|
|
902b157a08 | ||
|
|
931cc446b2 | ||
|
|
ad9ea4e2cd | ||
|
|
aec7841782 | ||
|
|
3f10dfb13d | ||
|
|
0e2c78cada | ||
|
|
265556f23f | ||
|
|
763529b10a | ||
|
|
6447b18465 | ||
|
|
d2d22e33f6 | ||
|
|
d90d2dae49 | ||
|
|
2b248a4978 | ||
|
|
e4addd06e2 | ||
|
|
a9c4ec571a | ||
|
|
156113d24b | ||
|
|
d822eaf1f9 | ||
|
|
6ea17a7351 | ||
|
|
1b49252fa6 | ||
|
|
44ac2ec100 | ||
|
|
9809370c17 | ||
|
|
48cbc9d2a1 | ||
|
|
b45fbb2161 | ||
|
|
4563a8beb2 | ||
|
|
5ca3bd7e72 | ||
|
|
f113cef580 | ||
|
|
bfa5bc8c86 | ||
|
|
90b8f159db | ||
|
|
040f7c6f4f | ||
|
|
348f7a410e |
5
.gitignore
vendored
5
.gitignore
vendored
@ -7,4 +7,7 @@ pkg
|
||||
.ruby-gemset
|
||||
*.swo
|
||||
*.swp
|
||||
bitpaykey.pem
|
||||
bitpaykey.pem
|
||||
constants.txt
|
||||
coverage/
|
||||
.pem.data
|
||||
|
||||
@ -1,2 +1,5 @@
|
||||
sudo: false
|
||||
rvm:
|
||||
- 2.1.0
|
||||
- 2.1.10
|
||||
- 2.2.5
|
||||
- 2.3.1
|
||||
|
||||
24
CHANGELOG.md
Normal file
24
CHANGELOG.md
Normal file
@ -0,0 +1,24 @@
|
||||
# Change Log
|
||||
All notable changes to this project will be documented in this file.
|
||||
This project adheres to [Semantic Versioning](http://semver.org/).
|
||||
|
||||
## [2.4.4] - 2015-04-14
|
||||
### Changed
|
||||
- Separated key utilities into its own Gem
|
||||
|
||||
## [2.4.3] - 2015-04-13
|
||||
### Changed
|
||||
- Loosened production gem requirements from patch level to major level
|
||||
|
||||
## [2.4.2] - 2015-03-11
|
||||
### Fixed
|
||||
- GitHub issue 39: handling post paths that include a ? and require a token. A workaround exists for this issue.
|
||||
|
||||
## [2.4.1] - 2015-03-11
|
||||
### Fixed
|
||||
- GitHub issue 40: error for endpoints that did not return a 'data' field
|
||||
|
||||
## [2.4.0] - 2015-03-05
|
||||
### Changed
|
||||
- Add feature: Accept refunds
|
||||
- Fix Bug: Accept bitcoin payments like 0.003
|
||||
59
GUIDE.md
59
GUIDE.md
@ -29,7 +29,26 @@ Most calls to the BitPay REST API require that your client is paired with the bi
|
||||
|
||||
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.
|
||||
|
||||
_For development or quick deployment purposes, consider the [BitPay Ruby Command-Line Interface](https://github.com/bitpay/ruby-cli) to simplify the deployment process_
|
||||
### A quick note on keys
|
||||
|
||||
The BitPay client gem includes the BitPay KeyUtilities gem, which can be used to generate new public private key pairs which it returns in PEM format. However, there are no methods which save the keys anywhere, so it is your responsibility to store the PEM file somewhere secure.
|
||||
|
||||
### BitPay authentication
|
||||
|
||||
BitPay authentication depends on four parts:
|
||||
|
||||
1. An account on our servers.
|
||||
1. A token shared between the client and the server.
|
||||
1. A public key, shared between the client and the server.
|
||||
1. A private key, held exclusively by the client.
|
||||
|
||||
In order to complete authentication, you have to associate your private key with a token, and associate that token with an account. Once this authentication is complete, as long as you have the private key, you never have to authenticate again. The token you created will always be associated with that private key, so any time you create a new bitpay client object with that key, it is authenticated with BitPay. This is true whether you use the ruby-client, python client, or no client at all, the key is the important thing.
|
||||
|
||||
There are two ways to authenticate, from the client side or the server side. The Ruby Client supports both.
|
||||
|
||||
To pair from the server side, you log in to the BitPay server, navigate to dashboard/merchant/api-tokens, and create a new token. This creates a new token, which is associated with your account. It is not associated with a key, so we provide a pairing code that you can use as a one time secret to associate the token with a key. From the client side, you can use the client.pair_pos_client(<pairing_code>) method to associate that method with a key held by the client.
|
||||
|
||||
To pair from the client side, you use the client to call the /tokens endpoint on the server with no parameters. This creates a token on the server and associates that token with a public key. What it doesn't do is associate that token to an account (because we don't know what account to associate with). This call returns a pairing code, which is a one time secret that allows you to find the token you just created. In order to associate the token with an account, you log in to the BitPay server, and use the dashboard/merchant/api-tokens interface to associate the token with a specific account. And example of client side pairing is shown below.
|
||||
|
||||
### Pairing Programatically
|
||||
|
||||
@ -38,30 +57,31 @@ If you are developing a client with built-in pairing capability, you can pair pr
|
||||
* `pair_client()` will perform a client-initiated pairing, and will provide a pairing code that can be entered at https://bitpay.com/dashboard/merchant/api-tokens to assign either `merchant` or `pos` facade.
|
||||
* `pair_client('pairing_code')` will complete a server-initiated pairing, when provided a pre-generated pairing code from https://bitpay.com/dashboard/merchant/api-tokens. In this case, the `pos` facade will be automatically assigned.
|
||||
|
||||
The example below demonstrates this using a locally generated PEM file using OpenSSL and the irb tool.
|
||||
This is an example of creating a paired client with the BitPay toolset.
|
||||
|
||||
```bash
|
||||
$ 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)
|
||||
2.1.2 :002 > pem = BitPay::KeyUtils.generate_pem
|
||||
=> "-----BEGIN EC PRIVATE KEY-----\nMHQCAQEEIH8oSTRm8lVMTVOsDZleIB8AmkiuHnp+ctEknqeUmZahoAcGBSuBBAAK\noUQDQgAEbjhdKA+X8NEKgcbHhyJaBMvePV7Sj6AQuOMQzuZYdskdkPY1/jlfQwNG\n4GVd/zSw4uhfukw/SDBOEKlQGVAmxQ==\n-----END EC PRIVATE KEY-----\n"
|
||||
2.1.1 :002 > client = BitPay::SDK::Client.new(api_uri: 'https://test.bitpay.com', pem: pem)
|
||||
=> #<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 described above, using the value from the `pairingCode` element, visit https://test.bitpay.com/api-tokens and search to register for the appropriate facade
|
||||
As described above, using the value from the `pairingCode` element, visit https://test.bitpay.com/api-tokens and search to register for the appropriate facade. That client is now paired. As previously mentioned, you must save the pem string you generated in order to use the client again.
|
||||
|
||||
## General Usage
|
||||
|
||||
### Initialize the client
|
||||
|
||||
```ruby
|
||||
client = BitPay::SDK::Client.new(pem: File.read('bitpaykey.pem')
|
||||
client = BitPay::SDK::Client.new(pem: File.read('bitpaykey.pem'))
|
||||
```
|
||||
|
||||
Optional parameters:
|
||||
@ -74,7 +94,7 @@ Optional parameters:
|
||||
### Create a new bitcoin invoice
|
||||
|
||||
```ruby
|
||||
invoice = client.create_invoice (price: <price>, currency: <currency>)
|
||||
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.
|
||||
@ -154,15 +174,30 @@ 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')
|
||||
```
|
||||
### Cancel Refund Requests
|
||||
|
||||
Requires a `merchant` token.
|
||||
|
||||
```ruby
|
||||
client.cancel_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.
|
||||
For API tasks which lack a dedicated library method, BitPay provides methods that will automatically apply the proper cryptographic parameters to a request.
|
||||
|
||||
```ruby
|
||||
client.send_request("GET", "/invoices/JB49z2MsDH7FunczeyDS8j", facade: 'merchant')
|
||||
client.send_request("GET", "invoices/JB49z2MsDH7FunczeyDS8j", facade: 'merchant')
|
||||
## This request is identical to:
|
||||
token = client.get_token("merchant")
|
||||
client.get(path: "invoices/JB49z2MsDH7FunczeyDS8j", token: token)
|
||||
|
||||
## post requests are also possible
|
||||
token = client.get_token("merchant")
|
||||
client.post(path: "tokens", token: token, params: {facade: "pos"}) #returns a new token with pairing code
|
||||
## equivalent to
|
||||
client.send_request("POST", "tokens", facade: 'merchant', params: {facade: 'pos'})
|
||||
```
|
||||
|
||||
Usage:
|
||||
* Specify HTTP verb and REST endpoint
|
||||
* Specifying a `facade` will fetch and apply the corresponding `token`
|
||||
@ -187,10 +222,10 @@ API Documentation is available on the [BitPay site](https://bitpay.com/api).
|
||||
|
||||
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:
|
||||
The tests require that environment variables be set for the bitpay server, user name, password, an invoice id for refunds and a valid testnet bitcoin address for refunds. First run:
|
||||
|
||||
```bash
|
||||
$ source ./spec/set_constants.sh https://test.bitpay.com <yourusername> <yourpassword>
|
||||
$ source ./spec/set_constants.sh https://test.bitpay.com <yourusername> <yourpassword> <a-confirmed-invoice-id> <a-valid-testnet-address>
|
||||
$ bundle install
|
||||
$ bundle exec rake
|
||||
```
|
||||
|
||||
4
Gemfile
4
Gemfile
@ -1,6 +1,2 @@
|
||||
source 'https://rubygems.org'
|
||||
gemspec
|
||||
|
||||
platform :jruby do
|
||||
gem 'jruby-openssl'
|
||||
end
|
||||
13
README.md
13
README.md
@ -1,9 +1,16 @@
|
||||
# BitPay Library for Ruby [](http://travis-ci.org/bitpay/ruby-client) [](http://badge.fury.io/rb/bitpay-sdk)
|
||||
# BitPay Library for Ruby
|
||||
|
||||
[](https://raw.githubusercontent.com/bitpay/ruby-client/master/LICENSE.md)
|
||||
[](https://travis-ci.org/bitpay/ruby-client)
|
||||
[](https://rubygems.org/gems/bitpay-sdk)
|
||||
[](https://coveralls.io/r/bitpay/ruby-client?branch=master)
|
||||
[](https://codeclimate.com/github/bitpay/ruby-client)
|
||||
|
||||
Powerful, flexible, lightweight interface to the BitPay Bitcoin Payment Gateway API.
|
||||
|
||||
The `bitpay-sdk` gem provides all the programattic tools required to implement a ruby client application for the BitPay REST API. For developers who prefer the ease of command-line pairing during the development or deployment process, BitPay provides a complementary [Ruby CLI gem](https://github.com/bitpay/ruby-cli) which can be used in conjunction with this gem.
|
||||
The `bitpay-sdk` gem provides all the programattic tools required to implement a ruby client application for the BitPay REST API.
|
||||
|
||||
## [Getting Started »](http://dev.bitpay.com/guides/ruby.html)
|
||||
## [Getting Started »](https://github.com/bitpay/ruby-client/blob/master/GUIDE.md)
|
||||
|
||||
## 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.
|
||||
|
||||
3
Rakefile
3
Rakefile
@ -1,12 +1,9 @@
|
||||
require "bundler/gem_tasks"
|
||||
require 'rspec/core/rake_task'
|
||||
require 'capybara'
|
||||
require 'capybara/poltergeist'
|
||||
require 'mongo'
|
||||
require 'cucumber'
|
||||
require 'cucumber/rake/task'
|
||||
require_relative 'config/constants.rb'
|
||||
require_relative 'config/capybara.rb'
|
||||
|
||||
RSpec::Core::RakeTask.new(:spec)
|
||||
|
||||
|
||||
@ -17,19 +17,17 @@ Gem::Specification.new do |s|
|
||||
s.bindir = 'bin'
|
||||
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
|
||||
|
||||
s.add_dependency 'json', '1.8.1'
|
||||
s.add_dependency 'rack', '1.5.2'
|
||||
s.add_dependency 'ecdsa', '1.2.0'
|
||||
s.add_dependency 'bitpay-key-utils', '~>2.0.0'
|
||||
|
||||
s.add_development_dependency 'rake', '10.3.2'
|
||||
s.add_development_dependency 'rack', '~> 2.0'
|
||||
s.add_development_dependency 'rake', '12.0'
|
||||
s.add_development_dependency 'webmock', '1.18.0'
|
||||
s.add_development_dependency 'pry', '0.10.1'
|
||||
s.add_development_dependency 'pry-byebug', '2.0.0'
|
||||
s.add_development_dependency 'pry-rescue', '1.4.1'
|
||||
s.add_development_dependency 'capybara', '2.4.3'
|
||||
s.add_development_dependency 'cucumber', '1.3.17'
|
||||
s.add_development_dependency 'poltergeist', '1.5.1'
|
||||
s.add_development_dependency 'cucumber', '~> 1.3.17'
|
||||
s.add_development_dependency 'airborne', '0.0.20'
|
||||
s.add_development_dependency 'rspec', '3.1.0'
|
||||
s.add_development_dependency 'mongo', '1.11.1'
|
||||
s.add_development_dependency 'coveralls'
|
||||
end
|
||||
|
||||
@ -1,6 +0,0 @@
|
||||
Capybara.javascript_driver = :poltergeist
|
||||
Capybara.default_driver = :poltergeist
|
||||
Capybara.default_wait_time = 5
|
||||
Capybara.register_driver :poltergeist do |app|
|
||||
Capybara::Poltergeist::Driver.new(app, timeout: 60, js_errors: false, phantomjs_options: ['--ignore-ssl-errors=yes', '--ssl-protocol=TLSv1', '--web-security=false'])
|
||||
end
|
||||
@ -5,15 +5,8 @@
|
||||
# source ./spec/set_constants.sh https://test.bitpay.com testuser@gmail.com mypassword
|
||||
#
|
||||
|
||||
ROOT_ADDRESS = ENV['RCROOTADDRESS']
|
||||
TEST_USER = ENV['RCTESTUSER']
|
||||
TEST_PASS = ENV['RCTESTPASSWORD']
|
||||
DASHBOARD_URL = "#{ROOT_ADDRESS}/dashboard/merchant/home"
|
||||
APIURI = ENV['BITPAYAPI']
|
||||
|
||||
unless
|
||||
ROOT_ADDRESS &&
|
||||
TEST_USER &&
|
||||
TEST_PASS
|
||||
then
|
||||
raise "Missing configuration options - see constants.rb"
|
||||
end
|
||||
# Specify a bitpay txid which has 6+ confirmations. Default belongs to 'bitpayrubyclient@gmail.com' test account
|
||||
REFUND_TRANSACTION = ENV['REFUND_TRANSACTION']
|
||||
REFUND_ADDRESS = ENV['REFUND_ADDRESS']
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
@invoices
|
||||
Feature: creating an invoice
|
||||
The user won't get any money
|
||||
If they can't
|
||||
@ -10,9 +11,10 @@ Feature: creating an invoice
|
||||
When the user creates an invoice for <price> <currency>
|
||||
Then they should recieve an invoice in response for <price> <currency>
|
||||
Examples:
|
||||
| price | currency |
|
||||
| "5.23" | "USD" |
|
||||
| price | currency |
|
||||
| "5.23" | "USD" |
|
||||
| "10.21" | "EUR" |
|
||||
| "0.225" | "BTC" |
|
||||
|
||||
Scenario Outline: The invoice contains illegal characters
|
||||
When the user creates an invoice for <price> <currency>
|
||||
@ -20,7 +22,7 @@ Feature: creating an invoice
|
||||
Examples:
|
||||
| price | currency | message |
|
||||
| "5,023" | "USD" | "Price must be formatted as a float" |
|
||||
| "3.21" | "EaUR" | "Currency is invalid." |
|
||||
| "3.21" | "EaUR" | "Currency is invalid." |
|
||||
| "" | "USD" | "Price must be formatted as a float" |
|
||||
| "Ten" | "USD" | "Price must be formatted as a float" |
|
||||
| "10" | "" | "Currency is invalid." |
|
||||
|
||||
@ -5,11 +5,11 @@ Feature: pairing with bitpay
|
||||
|
||||
Scenario: the client has a correct pairing code
|
||||
Given the user pairs with BitPay with a valid pairing code
|
||||
Then the user is paired with BitPay
|
||||
|
||||
Then the user receives a require token from bitpay
|
||||
|
||||
Scenario: the client initiates pairing
|
||||
Given the user requests a client-side pairing
|
||||
Then they will receive a claim code
|
||||
Given the user performs a client-side pairing
|
||||
Then the user receives an inactive token from bitpay
|
||||
|
||||
Scenario Outline: the client has a bad pairing code
|
||||
Given the user fails to pair with a semantically <valid> code <code>
|
||||
@ -17,8 +17,3 @@ Feature: pairing with bitpay
|
||||
Examples:
|
||||
| valid | code | error | message |
|
||||
| invalid | "a1b2c3d4" | BitPay::ArgumentError | "pairing code is not legal" |
|
||||
|
||||
Scenario: the client has a bad port configuration to a closed port
|
||||
When the fails to pair with BitPay because of an incorrect port
|
||||
Then they will receive a BitPay::ConnectionError matching "Connection refused"
|
||||
|
||||
|
||||
23
features/refunds.feature
Normal file
23
features/refunds.feature
Normal file
@ -0,0 +1,23 @@
|
||||
@refunds
|
||||
Feature: issuing a refund
|
||||
The merchant wants to issue a refund
|
||||
So that they can serve their customers
|
||||
|
||||
Background:
|
||||
Given the user is authenticated with BitPay
|
||||
|
||||
Scenario: creating a refund
|
||||
Given the user creates a refund
|
||||
Then they will receive a refund id
|
||||
|
||||
Scenario: retrieving a refund
|
||||
Given the user requests a specific refund
|
||||
Then they will receive the refund
|
||||
|
||||
Scenario: retrieving all refunds
|
||||
Given the user requests all refunds for an invoice
|
||||
Then they will receive an array of refunds
|
||||
|
||||
Scenario: canceling a refund
|
||||
Given a properly formatted cancellation request
|
||||
Then the refund will be cancelled
|
||||
@ -2,6 +2,10 @@ Feature: retrieving an invoice
|
||||
The user may want to retrieve invoices
|
||||
So that they can view them
|
||||
|
||||
Scenario: The request is correct
|
||||
Scenario: Correct public request
|
||||
Given that a user knows an invoice id
|
||||
Then they can retrieve that invoice
|
||||
Then they can retrieve the public version of that invoice
|
||||
|
||||
Scenario: Correct merchant request
|
||||
Given that a user knows an invoice id
|
||||
Then they can retrieve the merchant-scoped version of that invoice
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
When(/^the user (?:tries to |)creates? an invoice (?:for|without) "(.*?)" (?:or |and |)"(.*?)"$/) do |price, currency|
|
||||
begin
|
||||
@response = @client.create_invoice(price: price, currency: currency)
|
||||
@response = @client.create_invoice(price: price, currency: currency, facade: 'merchant')
|
||||
rescue => error
|
||||
@error = error
|
||||
end
|
||||
@ -15,12 +15,17 @@ Given(/^there is an invalid token$/) do
|
||||
end
|
||||
|
||||
Given(/^that a user knows an invoice id$/) do
|
||||
client = new_client_from_stored_values
|
||||
@id = (client.create_invoice(price: 3, currency: "USD" ))['id']
|
||||
@client = new_client_from_stored_values
|
||||
@id = (@client.create_invoice(price: 3, currency: "USD", facade: 'merchant' ))['id']
|
||||
end
|
||||
|
||||
Then(/^they can retrieve that invoice$/) do
|
||||
invoice = BitPay::SDK::Client.new(api_uri: ROOT_ADDRESS, insecure: true).get_public_invoice(id: @id)
|
||||
Then(/^they can retrieve the public version of that invoice$/) do
|
||||
invoice = @client.get_public_invoice(id: @id)
|
||||
raise "That's the wrong invoice" unless invoice['id'] == @id
|
||||
end
|
||||
|
||||
Then(/^they can retrieve the merchant\-scoped version of that invoice$/) do
|
||||
invoice = @client.get_invoice(id: @id)
|
||||
raise "That's the wrong invoice" unless invoice['id'] == @id
|
||||
end
|
||||
|
||||
|
||||
@ -2,35 +2,25 @@
|
||||
@error = nil
|
||||
|
||||
When(/^the user pairs with BitPay(?: with a valid pairing code|)$/) do
|
||||
claim_code = get_claim_code_from_server
|
||||
pem = BitPay::KeyUtils.generate_pem
|
||||
@client = BitPay::SDK::Client.new(api_uri: ROOT_ADDRESS, pem: pem, insecure: true)
|
||||
@client = new_client_from_stored_values
|
||||
claim_code = get_claim_code_from_server @client
|
||||
sleep 1 # rate limit compliance
|
||||
@token = @client.pair_pos_client(claim_code)
|
||||
end
|
||||
|
||||
When(/^the fails to pair with BitPay because of an incorrect port$/) do
|
||||
pem = BitPay::KeyUtils.generate_pem
|
||||
address = ROOT_ADDRESS.split(':').slice(0,2).join(':') + ":999"
|
||||
client = BitPay::SDK::Client.new(api_uri: address, pem: pem, insecure: true)
|
||||
begin
|
||||
sleep 1 # rate limit compliance
|
||||
client.pair_pos_client("1ab2c34")
|
||||
raise "pairing unexpectedly worked"
|
||||
rescue => error
|
||||
@error = error
|
||||
true
|
||||
end
|
||||
end
|
||||
|
||||
Given(/^the user is authenticated with BitPay$/) do
|
||||
@client = new_client_from_stored_values
|
||||
raise "client not authenticated" unless client_has_tokens(@client)
|
||||
end
|
||||
|
||||
Given(/^the user is paired with BitPay$/) do
|
||||
raise "Client is not paired" unless @client.verify_tokens
|
||||
end
|
||||
|
||||
Then(/^the user receives an? ([A-z]+) token from bitpay$/) do |expected|
|
||||
actual = @token[0]["policies"][0]["method"]
|
||||
raise "Token not correct, #{actual} != #{expected}" unless actual == expected
|
||||
end
|
||||
|
||||
Given(/^the user has a bad pairing_code "(.*?)"$/) do |arg1|
|
||||
# This is a no-op, pairing codes are transient and never actually saved
|
||||
@ -38,7 +28,7 @@ end
|
||||
|
||||
Then(/^the user fails to pair with a semantically (?:in|)valid code "(.*?)"$/) do |code|
|
||||
pem = BitPay::KeyUtils.generate_pem
|
||||
client = BitPay::SDK::Client.new(api_uri: ROOT_ADDRESS, pem: pem, insecure: true)
|
||||
client = BitPay::SDK::Client.new(api_uri: APIURI, pem: pem, insecure: true)
|
||||
begin
|
||||
sleep 1 # rate limit compliance
|
||||
client.pair_pos_client(code)
|
||||
@ -53,13 +43,14 @@ Then(/^they will receive an? (.*?) matching "(.*?)"$/) do |error_class, error_me
|
||||
raise "Error: #{@error.class}, message: #{@error.message}" unless Object.const_get(error_class) == @error.class && @error.message.include?(error_message)
|
||||
end
|
||||
|
||||
Given(/^the user requests a client\-side pairing$/) do
|
||||
Given(/^the user performs a client\-side pairing$/) do
|
||||
sleep 1
|
||||
pem = BitPay::KeyUtils.generate_pem
|
||||
client = BitPay::SDK::Client.new(api_uri: ROOT_ADDRESS, pem: pem, insecure: true)
|
||||
@response = client.pair_client({})
|
||||
@client = BitPay::SDK::Client.new(api_uri: APIURI, pem: pem, insecure: true)
|
||||
@token = @client.pair_client({facade: 'merchant'})
|
||||
end
|
||||
|
||||
Then(/^they will receive a claim code$/) do
|
||||
expect(@response["data"].first["pairingCode"] ).not_to be_empty
|
||||
Then(/^the user has a merchant token$/) do
|
||||
tokens = {'merchant' => @token}
|
||||
raise "Merchant token not authorized" unless @client.verify_tokens(tokens: tokens)
|
||||
end
|
||||
|
||||
37
features/step_definitions/refund_steps.rb
Normal file
37
features/step_definitions/refund_steps.rb
Normal file
@ -0,0 +1,37 @@
|
||||
Given(/^the user creates a refund$/) do
|
||||
sleep(1)
|
||||
@response = @client.refund_invoice(id: REFUND_TRANSACTION, params: {amount: 1, currency: 'USD', bitcoinAddress: REFUND_ADDRESS})
|
||||
end
|
||||
|
||||
Then(/^they will receive a refund id$/) do
|
||||
@refund_id = @response["id"]
|
||||
expect(@refund_id).not_to be_empty
|
||||
end
|
||||
|
||||
Given(/^the user requests a specific refund$/) do
|
||||
@response = @client.get_refund(invoice_id: REFUND_TRANSACTION, request_id: @refund_id)
|
||||
end
|
||||
|
||||
Then(/^they will receive the refund$/) do
|
||||
expect(@response.first["status"]).not_to be_empty
|
||||
end
|
||||
|
||||
Given(/^the user requests all refunds for an invoice$/) do
|
||||
client = new_client_from_stored_values
|
||||
@response = client.get_all_refunds_for_invoice(id: REFUND_TRANSACTION)
|
||||
end
|
||||
|
||||
Then(/^they will receive an array of refunds$/) do
|
||||
expect(@response).to be_instance_of Array
|
||||
end
|
||||
|
||||
Given(/^a properly formatted cancellation request$/) do
|
||||
sleep(1)
|
||||
client = new_client_from_stored_values
|
||||
@refund_id = client.get_all_refunds_for_invoice(id: REFUND_TRANSACTION).first["id"]
|
||||
@response = client.cancel_refund(invoice_id: REFUND_TRANSACTION, request_id: @refund_id)
|
||||
end
|
||||
|
||||
Then(/^the refund will be cancelled$/) do
|
||||
expect(@response).to eq("Success")
|
||||
end
|
||||
@ -1,10 +1,8 @@
|
||||
require 'capybara/poltergeist'
|
||||
require 'pry'
|
||||
require 'fileutils'
|
||||
|
||||
require File.join File.dirname(__FILE__), '..', '..', 'lib', 'bitpay_sdk.rb'
|
||||
require_relative '../../config/constants.rb'
|
||||
require_relative '../../config/capybara.rb'
|
||||
|
||||
|
||||
module BitPay
|
||||
@ -16,60 +14,18 @@ module BitPay
|
||||
TOKEN_FILE_PATH = File.join(BITPAY_CREDENTIALS_DIR, TOKEN_FILE)
|
||||
end
|
||||
|
||||
# Lots of sleeps in here to deal with finicky transitions and PhantomJS
|
||||
def get_claim_code_from_server
|
||||
Capybara::visit ROOT_ADDRESS
|
||||
log_in unless logged_in
|
||||
Capybara::visit DASHBOARD_URL
|
||||
raise "Bad Login" unless Capybara.current_session.current_url == DASHBOARD_URL
|
||||
Capybara::visit "#{ROOT_ADDRESS}/api-tokens"
|
||||
Capybara::find(".token-access-new-button").find(".btn").find(".icon-plus", match: :first).trigger("click")
|
||||
sleep 0.50
|
||||
Capybara::find(".token-access-new-button-wrapper").find_by_id("token-new-form", visible: true).find(".btn").trigger("click")
|
||||
Capybara::find(".token-claimcode", match: :first).text
|
||||
end
|
||||
|
||||
def log_in
|
||||
Capybara::visit "#{ROOT_ADDRESS}/dashboard/login/"
|
||||
Capybara::fill_in 'email', :with => TEST_USER
|
||||
Capybara::fill_in 'password', :with => TEST_PASS
|
||||
Capybara::click_on('Login')
|
||||
Capybara::find(".ion-gear-a", match: :first)
|
||||
end
|
||||
|
||||
def new_paired_client
|
||||
claim_code = get_claim_code_from_server
|
||||
pem = BitPay::KeyUtils.generate_pem
|
||||
client = BitPay::SDK::Client.new(api_uri: ROOT_ADDRESS, pem: pem, insecure: true)
|
||||
client.pair_pos_client(claim_code)
|
||||
client
|
||||
end
|
||||
|
||||
def new_client_from_stored_values
|
||||
if File.file?(BitPay::PRIVATE_KEY_PATH) && File.file?(BitPay::TOKEN_FILE_PATH)
|
||||
token = get_token_from_file
|
||||
pem = File.read(BitPay::PRIVATE_KEY_PATH)
|
||||
client = BitPay::SDK::Client.new(pem: pem, tokens: token, insecure: true, api_uri: ROOT_ADDRESS )
|
||||
unless client.verify_tokens then
|
||||
raise "Locally stored tokens are invalid, please remove #{BitPay::TOKEN_FILE_PATH}" end
|
||||
else
|
||||
claim_code = get_claim_code_from_server
|
||||
pem = BitPay::KeyUtils.generate_pem
|
||||
client = BitPay::SDK::Client.new(api_uri: ROOT_ADDRESS, pem: pem, insecure: true)
|
||||
sleep 1 # rate limit compliance
|
||||
token = client.pair_pos_client(claim_code)
|
||||
FileUtils.mkdir_p(BitPay::BITPAY_CREDENTIALS_DIR)
|
||||
File.write(BitPay::PRIVATE_KEY_PATH, pem)
|
||||
File.write(BitPay::TOKEN_FILE_PATH, JSON.generate(token))
|
||||
end
|
||||
client
|
||||
pem = ENV['BITPAYPEM'].gsub("\\n", "\n")
|
||||
BitPay::SDK::Client.new(api_uri: APIURI, pem: pem, insecure: true)
|
||||
end
|
||||
|
||||
def get_token_from_file
|
||||
token = JSON.parse(File.read(BitPay::TOKEN_FILE_PATH))['data'][0]
|
||||
{token['facade'] => token['token']}
|
||||
def get_claim_code_from_server client
|
||||
token = client.get(path: "tokens")["data"].select{|tuple| tuple["merchant"]}.first.values.first
|
||||
client.post(path: "tokens", token: token, params: {facade: "pos"})["data"][0]["pairingCode"]
|
||||
end
|
||||
|
||||
def logged_in
|
||||
Capybara::has_link?('Dashboard')
|
||||
def client_has_tokens client
|
||||
data = client.get(path: "tokens")["data"]
|
||||
data.select{|tuple| tuple["pos"]}.any? && data.select{|tuple| tuple["merchant"]}.any?
|
||||
end
|
||||
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
# license Copyright 2011-2014 BitPay, Inc., MIT License
|
||||
# license Copyright 2011-2015 BitPay, Inc., MIT License
|
||||
# see http://opensource.org/licenses/MIT
|
||||
# or https://github.com/bitpay/php-bitpay-client/blob/master/LICENSE
|
||||
|
||||
@ -6,14 +6,15 @@ require 'uri'
|
||||
require 'net/https'
|
||||
require 'json'
|
||||
|
||||
require_relative 'key_utils'
|
||||
require 'bitpay_key_utils'
|
||||
require_relative 'rest_connector'
|
||||
|
||||
module BitPay
|
||||
# This class is used to instantiate a BitPay Client object. It is expected to be thread safe.
|
||||
#
|
||||
module SDK
|
||||
class Client
|
||||
|
||||
include BitPay::RestConnector
|
||||
# @return [Client]
|
||||
# @example
|
||||
# # Create a client with a pem file created by the bitpay client:
|
||||
@ -46,7 +47,8 @@ module BitPay
|
||||
# => Pass {pairingCode: 'WfD01d2'} to claim a server-initiated pairing code
|
||||
#
|
||||
def pair_client(params={})
|
||||
pairing_request(params)
|
||||
tokens = post(path: 'tokens', params: params)
|
||||
return tokens["data"]
|
||||
end
|
||||
|
||||
## Compatibility method for pos pairing
|
||||
@ -61,29 +63,99 @@ module BitPay
|
||||
# Defaults to pos facade, also works with merchant facade
|
||||
#
|
||||
def create_invoice(price:, currency:, facade: 'pos', params:{})
|
||||
raise BitPay::ArgumentError, "Illegal Argument: Price must be formatted as a float" unless ( price.is_a?(Numeric) || /^[[:digit:]]+(\.[[:digit:]]{2})?$/.match(price) )
|
||||
raise BitPay::ArgumentError, "Illegal Argument: Price must be formatted as a float" unless
|
||||
price.is_a?(Numeric) ||
|
||||
/^[[:digit:]]+(\.[[:digit:]]{2})?$/.match(price) ||
|
||||
currency == 'BTC' && /^[[:digit:]]+(\.[[:digit:]]{1,8})?$/.match(price)
|
||||
raise BitPay::ArgumentError, "Illegal Argument: Currency is invalid." unless /^[[:upper:]]{3}$/.match(currency)
|
||||
params.merge!({price: price, currency: currency})
|
||||
response = send_request("POST", "invoices", facade: facade, params: params)
|
||||
response["data"]
|
||||
token = get_token(facade)
|
||||
invoice = post(path: "invoices", token: token, params: params)
|
||||
invoice["data"]
|
||||
end
|
||||
|
||||
## Gets the privileged merchant-version of the invoice
|
||||
## Gets the privileged merchant-version of the invoice
|
||||
# Requires merchant facade token
|
||||
#
|
||||
def get_invoice(id:)
|
||||
token = get_token('merchant')
|
||||
invoice = get(path: "invoices/#{id}", token: token)
|
||||
invoice["data"]
|
||||
end
|
||||
|
||||
def get_invoices(params = {})
|
||||
token = get_token('merchant')
|
||||
invoice = get(path: "invoices", token: token, params: params)
|
||||
invoice["data"]
|
||||
end
|
||||
|
||||
## Gets the public version of the invoice
|
||||
def get_public_invoice(id:)
|
||||
invoice = get(path: "invoices/#{id}", public_request: true)
|
||||
invoice["data"]
|
||||
end
|
||||
|
||||
|
||||
## Refund paid BitPay invoice
|
||||
#
|
||||
# If invoice["data"]["flags"]["refundable"] == true the a refund address was
|
||||
# provided with the payment and the refund_address parameter is an optional override
|
||||
#
|
||||
# Amount and Currency are required fields for fully paid invoices but optional
|
||||
# for under or overpaid invoices which will otherwise be completely refunded
|
||||
#
|
||||
# Requires merchant facade token
|
||||
#
|
||||
def get_invoice(id:)
|
||||
response = send_request("GET", "invoices/#{id}", facade: 'merchant')
|
||||
response["data"]
|
||||
end
|
||||
|
||||
## Gets the public version of the invoice
|
||||
# @example
|
||||
# client.refund_invoice(id: 'JB49z2MsDH7FunczeyDS8j', params: {amount: 10, currency: 'USD', bitcoinAddress: '1Jtcygf8W3cEmtGgepggtjCxtmFFjrZwRV'})
|
||||
#
|
||||
def get_public_invoice(id:)
|
||||
request = Net::HTTP::Get.new("/invoices/#{id}")
|
||||
response = process_request(request)
|
||||
response["data"]
|
||||
def refund_invoice(id:, params:{})
|
||||
invoice = get_invoice(id: id)
|
||||
refund = post(path: "invoices/#{id}/refunds", token: invoice["token"], params: params)
|
||||
refund["data"]
|
||||
end
|
||||
|
||||
## Get All Refunds for Invoice
|
||||
# Returns an array of all refund requests for a specific invoice,
|
||||
#
|
||||
# Requires merchant facade token
|
||||
#
|
||||
# @example:
|
||||
# client.get_all_refunds_for_invoice(id: 'JB49z2MsDH7FunczeyDS8j')
|
||||
#
|
||||
def get_all_refunds_for_invoice(id:)
|
||||
urlpath = "invoices/#{id}/refunds"
|
||||
invoice = get_invoice(id: id)
|
||||
refunds = get(path: urlpath, token: invoice["token"])
|
||||
refunds["data"]
|
||||
end
|
||||
|
||||
## Get Refund
|
||||
# Requires merchant facade token
|
||||
#
|
||||
# @example:
|
||||
# client.get_refund(id: 'JB49z2MsDH7FunczeyDS8j', request_id: '4evCrXq4EDXk4oqDXdWQhX')
|
||||
#
|
||||
def get_refund(invoice_id:, request_id:)
|
||||
urlpath = "invoices/#{invoice_id}/refunds/#{request_id}"
|
||||
invoice = get_invoice(id: invoice_id)
|
||||
refund = get(path: urlpath, token: invoice["token"])
|
||||
refund["data"]
|
||||
end
|
||||
|
||||
## Cancel Refund
|
||||
# Requires merchant facade token
|
||||
#
|
||||
# @example:
|
||||
# client.cancel_refund(id: 'JB49z2MsDH7FunczeyDS8j', request_id: '4evCrXq4EDXk4oqDXdWQhX')
|
||||
#
|
||||
def cancel_refund(invoice_id:, request_id:)
|
||||
urlpath = "invoices/#{invoice_id}/refunds/#{request_id}"
|
||||
refund = get_refund(invoice_id: invoice_id, request_id: request_id)
|
||||
deletion = delete(path: urlpath, token: refund["token"])
|
||||
deletion["data"]
|
||||
end
|
||||
|
||||
## Checks that the passed tokens are valid by
|
||||
# comparing them to those that are authorized by the server
|
||||
#
|
||||
@ -95,116 +167,12 @@ module BitPay
|
||||
tokens.each{|key, value| return false if server_tokens[key] != value}
|
||||
return true
|
||||
end
|
||||
|
||||
## Generates REST request to api endpoint
|
||||
# => Defaults to merchant facade unless token or facade is explicitly provided
|
||||
#
|
||||
def send_request(verb, path, facade: 'merchant', params: {}, token: nil)
|
||||
token ||= get_token(facade)
|
||||
|
||||
# Verb-specific logic
|
||||
case verb.upcase
|
||||
when "GET"
|
||||
urlpath = '/' + path + '?token=' + token
|
||||
request = Net::HTTP::Get.new urlpath
|
||||
request['X-Signature'] = KeyUtils.sign(@uri.to_s + urlpath, @priv_key)
|
||||
|
||||
when "PUT"
|
||||
|
||||
when "POST" # Requires a GUID
|
||||
|
||||
urlpath = '/' + path
|
||||
request = Net::HTTP::Post.new urlpath
|
||||
params[:token] = token
|
||||
params[:guid] = SecureRandom.uuid
|
||||
params[:id] = @client_id
|
||||
request.body = params.to_json
|
||||
request['X-Signature'] = KeyUtils.sign(@uri.to_s + urlpath + request.body, @priv_key)
|
||||
|
||||
when "DELETE"
|
||||
|
||||
raise(BitPayError, "Invalid HTTP verb: #{verb.upcase}")
|
||||
end
|
||||
|
||||
# Build request headers and submit
|
||||
request['X-Identity'] = @pub_key
|
||||
|
||||
response = process_request(request)
|
||||
end
|
||||
|
||||
##### PRIVATE METHODS #####
|
||||
private
|
||||
|
||||
## Processes HTTP Request and returns parsed response
|
||||
# Otherwise throws error
|
||||
#
|
||||
def process_request(request)
|
||||
|
||||
request['User-Agent'] = @user_agent
|
||||
request['Content-Type'] = 'application/json'
|
||||
request['X-BitPay-Plugin-Info'] = 'Rubylib' + VERSION
|
||||
|
||||
begin
|
||||
response = @https.request request
|
||||
rescue => error
|
||||
raise BitPay::ConnectionError, "#{error.message}"
|
||||
end
|
||||
|
||||
if response.kind_of? Net::HTTPSuccess
|
||||
return JSON.parse(response.body)
|
||||
elsif JSON.parse(response.body)["error"]
|
||||
raise(BitPayError, "#{response.code}: #{JSON.parse(response.body)['error']}")
|
||||
else
|
||||
raise BitPayError, "#{response.code}: #{JSON.parse(response.body)}"
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
## Fetches the tokens hash from the server and
|
||||
# updates @tokens
|
||||
#
|
||||
def refresh_tokens
|
||||
urlpath = '/tokens'
|
||||
|
||||
request = Net::HTTP::Get.new(urlpath)
|
||||
request['X-Identity'] = @pub_key
|
||||
request['X-Signature'] = KeyUtils.sign(@uri.to_s + urlpath, @priv_key)
|
||||
|
||||
response = process_request(request)
|
||||
token_array = response["data"] || {}
|
||||
|
||||
tokens = {}
|
||||
token_array.each do |t|
|
||||
tokens[t.keys.first] = t.values.first
|
||||
end
|
||||
|
||||
@tokens = tokens
|
||||
return tokens
|
||||
|
||||
end
|
||||
|
||||
## Makes a request to /tokens for pairing
|
||||
# Adds passed params as post parameters
|
||||
# If empty params, retrieves server-generated pairing code
|
||||
# If pairingCode key/value is passed, will pair client ID to this account
|
||||
# Returns response hash
|
||||
#
|
||||
def pairing_request(params)
|
||||
urlpath = '/tokens'
|
||||
request = Net::HTTP::Post.new urlpath
|
||||
params[:guid] = SecureRandom.uuid
|
||||
params[:id] = @client_id
|
||||
request.body = params.to_json
|
||||
process_request(request)
|
||||
end
|
||||
|
||||
def get_token(facade)
|
||||
token = @tokens[facade] || refresh_tokens[facade] || raise(BitPayError, "Not authorized for facade: #{facade}")
|
||||
end
|
||||
|
||||
def verify_claim_code(claim_code)
|
||||
regex = /^[[:alnum:]]{7}$/
|
||||
matches = regex.match(claim_code)
|
||||
matches = regex.match(claim_code)
|
||||
!(matches.nil?)
|
||||
end
|
||||
end
|
||||
|
||||
@ -1,124 +0,0 @@
|
||||
# license Copyright 2011-2014 BitPay, Inc., MIT License
|
||||
# see http://opensource.org/licenses/MIT
|
||||
# or https://github.com/bitpay/php-bitpay-client/blob/master/LICENSE
|
||||
|
||||
require 'uri'
|
||||
require 'net/https'
|
||||
require 'json'
|
||||
require 'openssl'
|
||||
require 'ecdsa'
|
||||
require 'securerandom'
|
||||
require 'digest/sha2'
|
||||
require 'cgi'
|
||||
|
||||
module BitPay
|
||||
class KeyUtils
|
||||
class << self
|
||||
def nonce
|
||||
Time.now.utc.strftime('%Y%m%d%H%M%S%L')
|
||||
end
|
||||
|
||||
## Generates a new private key
|
||||
#
|
||||
|
||||
def generate_pem
|
||||
key = OpenSSL::PKey::EC.new("secp256k1")
|
||||
key.generate_key
|
||||
key.to_pem
|
||||
end
|
||||
|
||||
def create_key pem
|
||||
OpenSSL::PKey::EC.new(pem)
|
||||
end
|
||||
|
||||
def create_new_key
|
||||
key = OpenSSL::PKey::EC.new("secp256k1")
|
||||
key.generate_key
|
||||
key
|
||||
end
|
||||
|
||||
def get_private_key key
|
||||
key.private_key.to_int.to_s(16)
|
||||
end
|
||||
|
||||
def get_public_key key
|
||||
key.public_key.group.point_conversion_form = :compressed
|
||||
key.public_key.to_bn.to_s(16).downcase
|
||||
end
|
||||
|
||||
def get_private_key_from_pem pem
|
||||
raise BitPayError, MISSING_PEM unless pem
|
||||
key = OpenSSL::PKey::EC.new(pem)
|
||||
get_private_key key
|
||||
end
|
||||
|
||||
def get_public_key_from_pem pem
|
||||
raise BitPayError, MISSING_PEM unless pem
|
||||
key = OpenSSL::PKey::EC.new(pem)
|
||||
get_public_key key
|
||||
end
|
||||
|
||||
def generate_sin_from_pem pem
|
||||
#http://blog.bitpay.com/2014/07/01/bitauth-for-decentralized-authentication.html
|
||||
#https://en.bitcoin.it/wiki/Identity_protocol_v1
|
||||
|
||||
# NOTE: All Digests are calculated against the binary representation,
|
||||
# hence the requirement to use [].pack("H*") to convert to binary for each step
|
||||
|
||||
#Generate Private Key
|
||||
key = OpenSSL::PKey::EC.new pem
|
||||
key.public_key.group.point_conversion_form = :compressed
|
||||
public_key = key.public_key.to_bn.to_s(2)
|
||||
step_one = Digest::SHA256.hexdigest(public_key)
|
||||
step_two = Digest::RMD160.hexdigest([step_one].pack("H*"))
|
||||
step_three = "0F02" + step_two
|
||||
step_four_a = Digest::SHA256.hexdigest([step_three].pack("H*"))
|
||||
step_four = Digest::SHA256.hexdigest([step_four_a].pack("H*"))
|
||||
step_five = step_four[0..7]
|
||||
step_six = step_three + step_five
|
||||
encode_base58(step_six)
|
||||
end
|
||||
|
||||
|
||||
## Generate ECDSA signature
|
||||
# This is the last method that requires the ecdsa gem, which we would like to replace
|
||||
|
||||
def sign(message, privkey)
|
||||
group = ECDSA::Group::Secp256k1
|
||||
digest = Digest::SHA256.digest(message)
|
||||
signature = nil
|
||||
while signature.nil?
|
||||
temp_key = 1 + SecureRandom.random_number(group.order - 1)
|
||||
signature = ECDSA.sign(group, privkey.to_i(16), digest, temp_key)
|
||||
return ECDSA::Format::SignatureDerString.encode(signature).unpack("H*").first
|
||||
end
|
||||
end
|
||||
|
||||
########## Private Class Methods ################
|
||||
|
||||
## Base58 Encoding Method
|
||||
#
|
||||
private
|
||||
def encode_base58 (data)
|
||||
code_string = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
|
||||
base = 58
|
||||
x = data.hex
|
||||
output_string = ""
|
||||
|
||||
while x > 0 do
|
||||
remainder = x % base
|
||||
x = x / base
|
||||
output_string << code_string[remainder]
|
||||
end
|
||||
|
||||
pos = 0
|
||||
while data[pos,2] == "00" do
|
||||
output_string << code_string[0]
|
||||
pos += 2
|
||||
end
|
||||
|
||||
output_string.reverse()
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
106
lib/bitpay/rest_connector.rb
Normal file
106
lib/bitpay/rest_connector.rb
Normal file
@ -0,0 +1,106 @@
|
||||
# license Copyright 2011-2015 BitPay, Inc., MIT License
|
||||
# see http://opensource.org/licenses/MIT
|
||||
# or https://github.com/bitpay/php-bitpay-client/blob/master/LICENSE
|
||||
|
||||
module BitPay
|
||||
module RestConnector
|
||||
def send_request(verb, path, facade: 'merchant', params: {}, token: nil)
|
||||
token ||= get_token(facade)
|
||||
case verb.upcase
|
||||
when "GET"
|
||||
return get(path: path, token: token, params: params)
|
||||
when "POST"
|
||||
return post(path: path, token: token, params: params)
|
||||
else
|
||||
raise(BitPayError, "Invalid HTTP verb: #{verb.upcase}")
|
||||
end
|
||||
end
|
||||
|
||||
def get(path:, token: nil, public_request: false, params: {})
|
||||
urlpath = '/' + path + '?'
|
||||
urlpath = urlpath + 'token=' + token if token
|
||||
urlpath = urlpath + '&' + params.to_param if params.present?
|
||||
request = Net::HTTP::Get.new urlpath
|
||||
unless public_request
|
||||
request['X-Signature'] = KeyUtils.sign(@uri.to_s + urlpath, @priv_key)
|
||||
request['X-Identity'] = @pub_key
|
||||
end
|
||||
process_request(request)
|
||||
end
|
||||
|
||||
def post(path:, token: nil, params:)
|
||||
urlpath = '/' + path
|
||||
request = Net::HTTP::Post.new urlpath
|
||||
params[:token] = token if token
|
||||
params[:guid] = SecureRandom.uuid
|
||||
params[:id] = @client_id
|
||||
request.body = params.to_json
|
||||
if token
|
||||
request['X-Signature'] = KeyUtils.sign(@uri.to_s + urlpath + request.body, @priv_key)
|
||||
request['X-Identity'] = @pub_key
|
||||
end
|
||||
process_request(request)
|
||||
end
|
||||
|
||||
def delete(path:, token: nil)
|
||||
urlpath = '/' + path
|
||||
urlpath = urlpath + '?token=' + token if token
|
||||
request = Net::HTTP::Delete.new urlpath
|
||||
request['X-Signature'] = KeyUtils.sign(@uri.to_s + urlpath, @priv_key)
|
||||
request['X-Identity'] = @pub_key
|
||||
process_request(request)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
## Processes HTTP Request and returns parsed response
|
||||
# Otherwise throws error
|
||||
#
|
||||
def process_request(request)
|
||||
request['User-Agent'] = @user_agent
|
||||
request['Content-Type'] = 'application/json'
|
||||
request['X-BitPay-Plugin-Info'] = 'Rubylib' + VERSION
|
||||
|
||||
begin
|
||||
response = @https.request request
|
||||
rescue => error
|
||||
raise BitPay::ConnectionError, "#{error.message}"
|
||||
end
|
||||
|
||||
if response.kind_of? Net::HTTPSuccess
|
||||
return JSON.parse(response.body)
|
||||
elsif JSON.parse(response.body)["error"]
|
||||
raise(BitPayError, "#{response.code}: #{JSON.parse(response.body)['error']}")
|
||||
else
|
||||
raise BitPayError, "#{response.code}: #{JSON.parse(response.body)}"
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
## Fetches the tokens hash from the server and
|
||||
# updates @tokens
|
||||
#
|
||||
def refresh_tokens
|
||||
response = get(path: 'tokens')["data"]
|
||||
token_array = response || {}
|
||||
tokens = {}
|
||||
token_array.each do |t|
|
||||
tokens[t.keys.first] = t.values.first
|
||||
end
|
||||
@tokens = tokens
|
||||
return tokens
|
||||
end
|
||||
|
||||
## Makes a request to /tokens for pairing
|
||||
# Adds passed params as post parameters
|
||||
# If empty params, retrieves server-generated pairing code
|
||||
# If pairingCode key/value is passed, will pair client ID to this account
|
||||
# Returns response hash
|
||||
#
|
||||
|
||||
def get_token(facade)
|
||||
token = @tokens[facade] || refresh_tokens[facade] || raise(BitPayError, "Not authorized for facade: #{facade}")
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
@ -3,5 +3,5 @@
|
||||
# or https://github.com/bitpay/php-bitpay-client/blob/master/LICENSE
|
||||
|
||||
module BitPay
|
||||
VERSION = '2.3.1'
|
||||
VERSION = '2.4.6'
|
||||
end
|
||||
|
||||
@ -22,10 +22,7 @@ module BitPay
|
||||
# User agent reported to API
|
||||
USER_AGENT = 'ruby-bitpay-sdk '+VERSION
|
||||
|
||||
MISSING_PEM = 'No pem file specified. Pass pem string'
|
||||
|
||||
class BitPayError < StandardError; end
|
||||
class ArgumentError < ArgumentError; end
|
||||
class ConnectionError < Errno::ECONNREFUSED; end
|
||||
|
||||
end
|
||||
|
||||
@ -19,6 +19,18 @@ describe BitPay::SDK::Client do
|
||||
.to_return(:status => 200, :body => tokens.to_json, :headers => {})
|
||||
stub_request(:get, "#{BitPay::TEST_API_URI}/invoices/TEST_INVOICE_ID?token=MERCHANT_TOKEN").
|
||||
to_return(:body => get_fixture('invoices_{id}-GET.json'))
|
||||
stub_request(:get, "#{BitPay::TEST_API_URI}/invoices/TEST_INVOICE_ID/refunds?token=MERCHANT_INVOICE_TOKEN").
|
||||
to_return(:body => get_fixture('invoices_{id}_refunds-GET.json'))
|
||||
stub_request(:get, "#{BitPay::TEST_API_URI}/invoices/TEST_INVOICE_ID/refunds/TEST_REQUEST_ID?token=MERCHANT_INVOICE_TOKEN").
|
||||
to_return(:body => get_fixture('invoices_{id}_refunds-GET.json'))
|
||||
stub_request(:post, "#{BitPay::TEST_API_URI}/invoices/TEST_INVOICE_ID/refunds").
|
||||
to_return(:body => get_fixture('invoices_{id}_refunds-POST.json'))
|
||||
stub_request(:post, "#{BitPay::TEST_API_URI}/nuttin").
|
||||
to_return(:body => get_fixture('response-nodata.json'))
|
||||
stub_request(:get, "#{BitPay::TEST_API_URI}/nuttin").
|
||||
to_return(:body => get_fixture('response-nodata.json'))
|
||||
stub_request(:delete, "#{BitPay::TEST_API_URI}/nuttin").
|
||||
to_return(:body => get_fixture('response-nodata.json'))
|
||||
end
|
||||
|
||||
describe "#initialize" do
|
||||
@ -30,6 +42,14 @@ describe BitPay::SDK::Client do
|
||||
|
||||
end
|
||||
|
||||
describe "requests to endpoint without data field" do
|
||||
it "should return the json body" do
|
||||
expect(bitpay_client.post(path: "nuttin", params: {})["facile"]).to eq("is easy")
|
||||
expect(bitpay_client.get(path: "nuttin")["facile"]).to eq("is easy")
|
||||
expect(bitpay_client.delete(path: "nuttin")["facile"]).to eq( "is easy")
|
||||
end
|
||||
end
|
||||
|
||||
describe "#send_request" do
|
||||
before do
|
||||
stub_const('ENV', {'BITPAY_PEM' => PEM})
|
||||
@ -41,6 +61,13 @@ describe BitPay::SDK::Client do
|
||||
bitpay_client.send_request("GET", "whatever", facade: "merchant")
|
||||
expect(WebMock).to have_requested(:get, "#{BitPay::TEST_API_URI}/whatever?token=MERCHANT_TOKEN")
|
||||
end
|
||||
|
||||
it 'should handle query parameters gracefully' do
|
||||
stub_request(:get, /#{BitPay::TEST_API_URI}\/ledgers.*/).to_return(:body => '{"awesome": "json"}')
|
||||
bitpay_client.send_request("GET", "ledgers/BTC?startDate=2015-01-01&endDate=2015-02-01", facade: "merchant")
|
||||
expect(WebMock).to have_requested(:get, "#{BitPay::TEST_API_URI}/ledgers/BTC?startDate=2015-01-01&endDate=2015-02-01&token=MERCHANT_TOKEN")
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
context "POST" do
|
||||
@ -109,6 +136,51 @@ describe BitPay::SDK::Client do
|
||||
end
|
||||
end
|
||||
|
||||
describe '#refund_invoice' do
|
||||
subject { bitpay_client }
|
||||
before { stub_const('ENV', {'BITPAY_PEM' => PEM}) }
|
||||
it { is_expected.to respond_to(:refund_invoice) }
|
||||
|
||||
it 'should get the token for the invoice' do
|
||||
bitpay_client.refund_invoice(id: 'TEST_INVOICE_ID')
|
||||
expect(WebMock).to have_requested :get, "#{BitPay::TEST_API_URI}/invoices/TEST_INVOICE_ID?token=MERCHANT_TOKEN"
|
||||
end
|
||||
|
||||
it 'should generate a POST to the invoices/refund endpoint' do
|
||||
bitpay_client.refund_invoice(id: 'TEST_INVOICE_ID')
|
||||
expect(WebMock).to have_requested :post, "#{BitPay::TEST_API_URI}/invoices/TEST_INVOICE_ID/refunds"
|
||||
end
|
||||
end
|
||||
|
||||
describe '#get_all_refunds_for_invoice' do
|
||||
subject { bitpay_client }
|
||||
before {stub_const('ENV', {'BITPAY_PEM' => PEM})}
|
||||
it { is_expected.to respond_to(:get_all_refunds_for_invoice) }
|
||||
|
||||
it 'should get the token for the invoice' do
|
||||
bitpay_client.get_all_refunds_for_invoice(id: 'TEST_INVOICE_ID')
|
||||
expect(WebMock).to have_requested :get, "#{BitPay::TEST_API_URI}/invoices/TEST_INVOICE_ID?token=MERCHANT_TOKEN"
|
||||
end
|
||||
it 'should GET all refunds' do
|
||||
bitpay_client.get_all_refunds_for_invoice(id: 'TEST_INVOICE_ID')
|
||||
expect(WebMock).to have_requested :get, "#{BitPay::TEST_API_URI}/invoices/TEST_INVOICE_ID/refunds?token=MERCHANT_INVOICE_TOKEN"
|
||||
end
|
||||
end
|
||||
|
||||
describe '#get_refund' do
|
||||
subject { bitpay_client }
|
||||
before {stub_const('ENV', {'BITPAY_PEM' => PEM})}
|
||||
it { is_expected.to respond_to(:get_refund) }
|
||||
it 'should get the token for the invoice' do
|
||||
bitpay_client.get_refund(invoice_id: 'TEST_INVOICE_ID', request_id: 'TEST_REQUEST_ID')
|
||||
expect(WebMock).to have_requested :get, "#{BitPay::TEST_API_URI}/invoices/TEST_INVOICE_ID?token=MERCHANT_TOKEN"
|
||||
end
|
||||
it 'should GET a single refund' do
|
||||
bitpay_client.get_refund(invoice_id: 'TEST_INVOICE_ID', request_id: 'TEST_REQUEST_ID')
|
||||
expect(WebMock).to have_requested :get, "#{BitPay::TEST_API_URI}/invoices/TEST_INVOICE_ID/refunds/TEST_REQUEST_ID?token=MERCHANT_INVOICE_TOKEN"
|
||||
end
|
||||
end
|
||||
|
||||
describe "#verify_tokens" do
|
||||
subject { bitpay_client }
|
||||
before {stub_const('ENV', {'BITPAY_PEM' => PEM})}
|
||||
|
||||
@ -1,9 +1,11 @@
|
||||
{
|
||||
"facade": "merchant/supportRequest",
|
||||
"data": {
|
||||
"id": "TEST_REQUEST_ID",
|
||||
"requestDate": "2015-01-27T00:36:12.360Z",
|
||||
"status": "pending",
|
||||
"token": "REFUND_REQUEST_TOKEN"
|
||||
}
|
||||
"data": [
|
||||
{
|
||||
"id": "TEST_REQUEST_ID",
|
||||
"requestDate": "2015-01-27T00:36:12.360Z",
|
||||
"status": "pending",
|
||||
"token": "REFUND_REQUEST_TOKEN"
|
||||
}
|
||||
]
|
||||
}
|
||||
10
spec/fixtures/response-nodata.json
vendored
Normal file
10
spec/fixtures/response-nodata.json
vendored
Normal file
@ -0,0 +1,10 @@
|
||||
{
|
||||
"facile": "is easy",
|
||||
"diti": [
|
||||
{
|
||||
"requestDate": "2015-01-27T00:36:12.360Z",
|
||||
"status": "pending"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@ -1,41 +0,0 @@
|
||||
require 'spec_helper'
|
||||
|
||||
describe BitPay::KeyUtils do
|
||||
let(:key_utils) {BitPay::KeyUtils}
|
||||
|
||||
describe '.generate_pem' do
|
||||
it 'should generate a pem string' do
|
||||
regex = /BEGIN\ EC\ PRIVATE\ KEY/
|
||||
expect(regex.match(key_utils.generate_pem)).to be_truthy
|
||||
end
|
||||
end
|
||||
|
||||
describe '.get_public_key_from_pem' do
|
||||
it 'should generate the right public key' do
|
||||
expect(key_utils.get_public_key_from_pem(PEM)).to eq(PUB_KEY)
|
||||
end
|
||||
|
||||
it 'should get pem from the env if none is passed' do
|
||||
expect(key_utils.get_public_key_from_pem(PEM)).to eq(PUB_KEY)
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
describe '.generate_sin_from_pem' do
|
||||
let(:pem){PEM}
|
||||
let(:sin){CLIENT_ID}
|
||||
|
||||
it 'will return the right sin for the right pem' do
|
||||
expect(key_utils.generate_sin_from_pem(pem)).to eq sin
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
context "errors when priv_key is not provided" do
|
||||
it 'will not retrieve public key' do
|
||||
expect{key_utils.get_public_key_from_pem(nil)}.to raise_error(BitPay::BitPayError)
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
end
|
||||
@ -1,10 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
export RCROOTADDRESS=$1
|
||||
echo $RCROOTADDRESS
|
||||
export RCTESTUSER=$2
|
||||
echo $RCTESTUSER
|
||||
export RCTESTPASSWORD=$3
|
||||
echo $RCTESTPASSWORD
|
||||
export PRIV_KEY=$4
|
||||
echo $PRIV_KEY
|
||||
@ -1,11 +1,10 @@
|
||||
require 'webmock/rspec'
|
||||
require 'pry'
|
||||
require 'capybara/rspec'
|
||||
require 'capybara/poltergeist'
|
||||
require 'coveralls'
|
||||
Coveralls.wear!
|
||||
|
||||
require File.join File.dirname(__FILE__), '..', 'lib', 'bitpay_sdk.rb'
|
||||
require_relative '../config/constants.rb'
|
||||
require_relative '../config/capybara.rb'
|
||||
|
||||
#
|
||||
## Test Variables
|
||||
|
||||
Loading…
Reference in New Issue
Block a user