Giter VIP home page Giter VIP logo

bunq-client's Introduction

Bunq::Client

rspec Actions Status

The Bunq::Client is a ruby wrapper of the bunq Public API extracted from Jortt Online boekhouden.

The Bunq::Client is the main interface which can be used to navigate to other resources. The response objects are just hashes similar to the documentation of the bunq API. Only the content of Response is returned.

The bunq Pagination is implemented using a ruby Enumerator. All index methods are Paginated. This means you can loop through large resultsets without loading everything into memory.

Installation

Add this line to your application's Gemfile:

gem 'bunq-client'

And then execute:

$ bundle

Or install it yourself as:

$ gem install bunq-client

One time setup

  1. Create installation
# Generate keys on the fly. Make sure you save these keys in a secure location.
# Alternatively use keys already generated.
openssl_key = OpenSSL::PKey::RSA.new(2048)
public_key = openssl_key.public_key.to_pem
private_key = openssl_key.to_pem

Bunq.configure do |config|
  config.api_key = 'YOUR API KEY'
  config.private_key = private_key
  config.server_public_key = nil # you don't have this yet
  config.installation_token = nil # this MUST be nil for creating installations
end

# Create the installation
installation = Bunq.client.installations.create(public_key)

# Print the installation token to put in your Bunq::Configuration
installation_token = installation[1]['Token']['token']
puts "config.installation_token = #{installation_token}"

# Keep the public key to put in your Bunq::Configuration
server_public_key_location = "./server_public_key.pub"
File.open(server_public_key_location, 'w') { |file| file.write(installation[2]['ServerPublicKey']['server_public_key']) }
puts "config.server_public_key written to file #{server_public_key_location}"
  1. Register your device as device server This is typically your application server (or your laptop when playing around).
Bunq.configure do |config|
  config.api_key = 'YOUR API KEY'
  # Used for request signing
  config.private_key = 'SAME PRIVATE KEY AS IN STEP 1'
  # Used for response verification
  config.server_public_key = 'THE CONTENTS OF THE PUBLIC KEY FILE RETURNED IN STEP 1'
  config.installation_token = 'THE INSTALLATION TOKEN RETURNED IN STEP 1'
end

response = Bunq.client.device_servers.create('My Laptop')
puts "Device server created: #{response[0]['Id']['id']}"
  1. Optional: Pin certificate (if you want to receive callbacks)
Bunq.configure do |config|
  config.api_key = 'YOUR API KEY'
  # Used for request signing
  config.private_key = 'SAME PRIVATE KEY AS IN STEP 1'
  # Used for response verification
  config.server_public_key = 'THE CONTENTS OF THE PUBLIC KEY FILE RETURNED IN STEP 1'
  config.installation_token = 'THE INSTALLATION TOKEN RETURNED IN STEP 1'
end

certificate_of_you_callback_url = IO.read('path_to_pem_file')
Bunq.client.me_as_user.certificate_pinned.create(certificate_of_you_callback_url)
  1. Optional: Register callback url (for realtime updates of e.g. payments)
Bunq.configure do |config|
  config.api_key = 'YOUR API KEY'
  # Used for request signing
  config.private_key = 'SAME PRIVATE KEY AS IN STEP 1'
  # Used for response verification
  config.server_public_key = 'THE CONTENTS OF THE PUBLIC KEY FILE RETURNED IN STEP 1'
  config.installation_token = 'THE INSTALLATION TOKEN RETURNED IN STEP 1'
end

Bunq.client.me_as_user.notification_filter_url.create(
  [{
    "notification_target": 'https://YOUR_CALLBACK_URL',
    "category": "PAYMENT"
  }]
)

Usage

Bunq.configure do |config|
  
  # Mandatory configuration after inital setup phase
  config.api_key = 'YOUR API KEY' 
  # Private key used for request signing
  config.private_key = 'YOUR PRIVATE KEY'
  # Public key from bunq retrieved via Bunq.client.installations.create
  config.server_public_key = 'SERVER PUBLIC KEY'
  # Installation token retrieved via Bunq.client.installations.create
  config.installation_token = 'YOUR INSTALLATION TOKEN'

  
  # Optional configuration for access to the sandbox
  # config.sandbox = true 
  # if config.sandbox
  #  config.sandbox_user = 'USER'
  #  config.sandbox_password = 'PASSWORD'
  # end
end

# List id's of all your monetary_accounts
Bunq.client.me_as_user.monetary_accounts.index.each do |monetary_account|
  puts monetary_account['MonetaryAccountBank']['id']
end

Session caching

By default, each Bunq.client creates a new session. If you want to share a session between multiple Bunq.clients, use the following configuration:

Bunq.configure do |config|
  config.session_cache = Bunq::ThreadSafeSessionCache.new
end

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/jorttbv/bunq-client. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

License

The gem is available as open source under the terms of the MIT License.

bunq-client's People

Contributors

bforma avatar calvinwalzel avatar douwem avatar erikdebruijn avatar lvonk avatar mvandiepen avatar romikoops avatar wvteijlingen avatar

Stargazers

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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

bunq-client's Issues

Usage without global configuration

Can I use this library without configuring the global Bunq module? So, will initializing a client as follows work?

configuration = Bunq::Configuration.new
configuration.base_url = Bunq::Configuration::SANDBOX_BASE_URL
configuration.sandbox = true
# etc

client = Bunq::Client.new(configuration)

I looked through the code and it seems supported. However, I'm a bit worried about this method, because it uses the global configuration instance. However, I cannot find this method being called anywhere.

Integrate Rubocop

Now the code style is too different from contributors. It would be really helpful to integrate Rubocop gem.

I am able to send a PR.

Endless loop when paginating

When requesting an index using a given newer_id, the bunq api returns a pagination object containing an older_url. This older_url contains an older_id.

The Paginated class merges this older_id into the new pagination params, which results in params that contain both a newer_id and an older_id.

I don't think this is supported, since setup_params can throw with "Cant pass both older_id and newer_id". Also, it seems that when this occurs, the Bunq api keeps returning the same pagination object, causing the enumerator to get stuck in an infinite loop.

Group of headers are optional now in Bunq

Based on last changes announced in Bunq blog following headers are optional:

X-Bunq-Geolocation
X-Bunq-Language
X-Bunq-Region
X-Bunq-Request-Id

Currently there is no way do not send them.

Suggestion "registration script"

To make it easier for people to register I created this registration script:

require "openssl"

def register!

	puts "Input the API key from Bunq and press Enter: "
	api_key = gets.chomp

	puts "OK. Generating an SSL certificate..."
	openssl_key = OpenSSL::PKey::RSA.new(2048)
	public_key = openssl_key.public_key.to_pem
	private_key = openssl_key.to_pem

	Bunq.configure do |config|
		config.api_key = api_key
		config.private_key = private_key
		config.server_public_key = public_key
		config.installation_token = nil
	end

	puts "OK. \nSetting up the installation..."
	installation = Bunq.client.installations.create(public_key)


	# Print the installation token to put in your Bunq::Configuration
	installation_token = installation[1]['Token']['token']
	puts "config.installation_token = #{installation_token}"
	puts "OK. \nSetting up the device..."

	Bunq.configure do |config|
		config.api_key = api_key
		config.private_key = private_key
		config.server_public_key = public_key
		config.installation_token = installation_token
	end

	puts "Input a name or identifer for your device and press Enter: "
	device_name = gets.chomp

	begin
	  response = Bunq.client.device_servers.create(device_name)
	rescue StandardError => e
	  puts "Rescued: #{e.inspect}"
	end
	# raise "Exiting since we couldn't register the device (response code needs to be 200)." unless response.code == 200
	puts "OK."
	pp response
	# puts "Device server created: #{response[0]['Id']['id']}"

	puts "Find your configuration below:"

	puts <<-CONFIG
Bunq.configure do |config|
	config.api_key = "#{api_key}"
	config.private_key = "#{openssl_key.public_key.to_pem}"
	config.server_public_key = "#{openssl_key.public_key.to_pem}"
	config.installation_token = "#{installation_token}"
end
CONFIG
end

register!

Obviously it could use some refinement. Also, I never got a good response from Bunq.client.device_servers.create, but this should probably not be worked around with a rescue block.

The error I'm now catching is the following:

Rescued: #<Bunq::InvalidResponseSignature: Response error (code: 200, body: {"Response":[{"Id":{"id":123123}}]})>

Since I am abandoning this attempt to automate payments for now, maybe someone likes to take it from here?

ArgumentError (Private key is needed.)

I tried to setup using the readme but I wanted it to be more repeatable (since I ran into an error). The installer I created could be useful and is shared in another issue that I'll post separately.

The error I got is:

irb(main):032:0> Bunq.client.me_as_user
Traceback (most recent call last):
        2: from (irb):32
        1: from (irb):32:in `rescue in irb_binding'
ArgumentError (Private key is needed.)

User credentials are incorrect. Incorrect API key or IP address.

Hi,

Did something change in the Bunq API? Since a few weeks I'm getting "User credentials are incorrect. Incorrect API key or IP address.", but nothing has changed. Creating new API keys doesn't help either, where in the past it would work without any problems.

Better exceptions

Some exceptions are instantiated with a hash, for example in the Resource class:

fail UnexpectedResponse.new(code: response.code, headers: response.raw_headers, body: response.body)

These hashes are converted to strings and end up in a serialised form in the exception message. This makes it very hard to extract the actual cause from an exception. I think it would be better if these exceptions are custom subclasses with additional accessors

class UnexpectedResponse < StandardError
  attr_reader :status_code
  attr_reader :headers
  attr_reader :body

  def initialize(msg = "Unexpected response", status_code: nil, headers: nil, body: nil)
    @status_code = status_code
    @headers = headers
    @body = body
    super(msg)
  end
end

exception = UnexpectedResponse.new("Descriptive message", status_code: 404, headers: {foo: 'bar'}, body: 'Body')
exception.message # Descriptive message
exception.code # 404
exception.headers # {foo: 'bar'}
exception.body # Body

Since the Bunq API has a standard JSON layout for 4xx errors, the exception message could be derived from the JSON.

config.api_key should not be mandatory for installation

The API documentation from Bunq doesn't mention anything about the API key being required when creating an installation. However, the Configuration class raises an error when config.api_key is nil. This means it is impossible to create an installation without having an API key.

I've looked through the codebase and I think we can solve this as follows:

  1. I see there is already a nil check when creating a SessionServer here.
  2. Add the same check when creating a DeviceServer here.
  3. Remove the check in the Configuration class.

No instruction how to upgrade the gem

Hello. It is nice to see the gem moves forward and is alive. It was went up to version 0.7.2 from 0.2.0 during short period of time. At the same time there is no information what was changed exactly and which brake changes were introduced.

It would be really nice to support CHANGELOG file with last changes. Now it looks abandoned.

In additional, it would be really appreciated to add Upgrade instructions in README file.

Anyway, thank you for such amazing gem. I am ready to contribute to it.

Support Bunqme-tab API endpoints

Currently we do not have a support bunq-tab api endpoints in this gem

https://doc.bunq.com/#/bunqme-tab

PUT /user/{userID}/monetary-account/{monetary-accountID}/bunqme-tab/{itemId}
GET /user/{userID}/monetary-account/{monetary-accountID}/bunqme-tab/{itemId}
POST /user/{userID}/monetary-account/{monetary-accountID}/bunqme-tab
GET /user/{userID}/monetary-account/{monetary-accountID}/bunqme-tab

I am ready to send a PR

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.