forked from EasyPost/example-ui-for-buying-shipments
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.rb
75 lines (65 loc) · 1.92 KB
/
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
require 'sinatra/base'
require 'easypost'
require './lib/helpers'
class App < Sinatra::Base
require 'tilt/erb' if development?
require 'pry' if development?
set :show_exceptions, :after_handler
enable :sessions
helpers Helpers
configure do
EasyPost.api_key = ENV['EASYPOST_API_KEY']
set :addr_verification, {verify_strict: ['delivery','zip4']}
end
get '/' do
redirect '/shipment'
end
get '/shipment' do
erb :index
end
post '/shipment' do
begin
from_address = if params[:verify_from] == "true"
EasyPost::Address.create(params[:from_address].merge(settings.addr_verification))
else
params[:from_address]
end
to_address = if params[:verify_to] == "true"
EasyPost::Address.create(params[:to_address].merge(settings.addr_verification))
else
params[:to_address]
end
shipment = EasyPost::Shipment.create(
from_address: from_address,
to_address: to_address,
parcel: params[:parcel],
options: {
delivery_confirmation: params[:delivery_confirmation],
},
)
redirect "shipment/#{shipment.id}/rates"
rescue EasyPost::Error => e
erb :index, locals: {
exception: e
}
end
end
get '/shipment/:id/rates' do
shipment = retrieve_shipment
erb :rate, locals: {shipment: shipment}
end
post '/shipment/:id/buy' do
shipment = retrieve_shipment
begin
shipment.buy(rate: {id: params[:rate]})
raise "Failed to buy label" unless shipment.postage_label
redirect "shipment/#{shipment.id}"
rescue EasyPost::Error => e
halt 400, erb(:rate, locals: {exception: e})
end
end
get '/shipment/:id' do
erb :shipment, locals: {shipment: retrieve_shipment}
end
run! if app_file == $0
end