-
Notifications
You must be signed in to change notification settings - Fork 3
/
xero_app.rb
80 lines (67 loc) · 2.41 KB
/
xero_app.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# This is an example app that provides a dashboard to make some example
# calls to the Xero API actions after authorising the app via OAuth 2.0.
require 'sinatra'
require 'sinatra/reloader' if development?
require 'xero-ruby'
require 'securerandom'
require 'dotenv/load'
require 'jwt'
require 'pp'
enable :sessions
set :session_secret, "328479283uf923fu8932fu923uf9832f23f232"
use Rack::Session::Pool
set :haml, :format => :html5
# Setup the credentials we use to connect to the XeroAPI
CREDENTIALS = {
client_id: ENV['CLIENT_ID'],
client_secret: ENV['CLIENT_SECRET'],
grant_type: 'client_credentials'
}
# We initialise an instance of the Xero API Client here so we can make calls
# to the API later. Memoization `||=`` will return a previously initialized client.
helpers do
def xero_client
@xero_client ||= XeroRuby::ApiClient.new(credentials: CREDENTIALS)
end
def decode_token_set(token_set)
if token_set && token_set['access_token']
@access_token = JWT.decode token_set['access_token'], nil, false
end
end
end
# On the homepage, we need to define a few variables that are used by the
# 'home.haml' layout file in the 'views/' directory.
get '/' do
@token_set = xero_client.get_client_credentials_token
session[:token_set] = @token_set
puts "session[:token_set]: #{session[:token_set]}"
decode_token_set(@token_set)
haml :home
end
# This endpoint is here specifically to obtain a new, valid access token at will.
get '/refresh-token' do
@token_set = xero_client.get_client_credentials_token
session[:token_set] = @token_set
puts "session[:token_set]: #{session[:token_set]}"
# Set some variables for the 'refresh_token.haml' view
decode_token_set(@token_set)
haml :refresh_token
end
# This endpoint allows the user to explicitly disconnect the app from
# their Xero contacts.
# Note: At this point in time, it assumes that you have a single contacts
# connected.
# This endpoint shows invoice data via the 'invoices.haml' view.
get '/invoices' do
puts "session[:token_set]: #{session.inspect}"
xero_client.set_token_set(session[:token_set])
@invoices = xero_client.accounting_api.get_invoices('').invoices
haml :invoices
end
# This endpoint returns the object of the first contacts that appears
# in the xero_client.connections array.
get '/contacts' do
xero_client.set_token_set(session[:token_set])
@contacts = xero_client.accounting_api.get_contacts('').contacts
haml :contacts
end