-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathxero_app.rb
95 lines (80 loc) · 2.57 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# 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'
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'],
redirect_uri: ENV['REDIRECT_URI'],
scopes: ENV['SCOPES']
}
# 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
end
get '/' do
@form_data = {
given_name: '',
family_name: '',
email: '',
org_name: '',
contacts_count: 0
}
@auth_url = xero_client.authorization_url
haml :home
end
get '/callback' do
token_set = xero_client.get_token_set_from_callback(params)
@id_token_details = JWT.decode(token_set['id_token'], nil, false)[0]
tenant_id = xero_client.connections.sort { |a,b|
DateTime.parse(a['updatedDateUtc']) <=> DateTime.parse(b['updatedDateUtc'])
}.last['tenantId']
@organisation = xero_client.accounting_api.get_organisations(tenant_id).organisations[0]
@contacts = []
page = 1
continue = true
while continue
opts = { page: page }
contacts = xero_client.accounting_api.get_contacts(tenant_id, opts).contacts
if contacts.count > 0
@contacts << contacts
page += 1
else
continue = false
end
end
adr = @organisation.addresses[0]
phone = @organisation.phones[0]
@form_data = {
given_name: @id_token_details['given_name'],
family_name: @id_token_details['family_name'],
email: @id_token_details['email'],
org_name: @organisation.name,
contacts_count: @contacts.flatten.count,
currency: @organisation.base_currency,
timezone: @organisation.timezone,
street: adr ? adr.address_line1 : '',
city: adr ? adr.address_line2 : '',
postal_code: adr ? adr.postal_code : '',
phone: phone ? "#{phone.phone_type}: #{phone.phone_area_code} #{phone.phone_number}" : '',
password: 'Set a password to create your account!'
}
@auth_url = xero_client.authorization_url
haml :home
end
post '/xero-signup' do
@params = params.reject { |k, v| ["password", "password_confirmation"].include? k }
haml :dashboard
end