ninja_van_api 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/.env.example +3 -0
- data/.rspec +1 -0
- data/CHANGELOG.md +5 -0
- data/CODE_OF_CONDUCT.md +132 -0
- data/LICENSE.txt +21 -0
- data/README.md +168 -0
- data/Rakefile +4 -0
- data/app/controllers/ninja_van_api/webhook_controller.rb +40 -0
- data/config/routes.rb +3 -0
- data/lib/ninja_van_api/client.rb +146 -0
- data/lib/ninja_van_api/configuration.rb +49 -0
- data/lib/ninja_van_api/engine.rb +14 -0
- data/lib/ninja_van_api/error.rb +6 -0
- data/lib/ninja_van_api/objects/base.rb +23 -0
- data/lib/ninja_van_api/objects/order.rb +6 -0
- data/lib/ninja_van_api/resources/base_resource.rb +92 -0
- data/lib/ninja_van_api/resources/order_resource.rb +15 -0
- data/lib/ninja_van_api/version.rb +5 -0
- data/lib/ninja_van_api.rb +19 -0
- data/sig/ninja_van_api.rbs +4 -0
- metadata +163 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: 498b64c23b4c90326050957887a23552deda6444bdf1ee6b779015d007a7da3a
|
4
|
+
data.tar.gz: 831f91cba7c2368c42ac03325df4d2eadf602c3b23286a62180a3d89e34286bc
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: a8017469ab59a08951a908bf9f7a89b7da7d558351d785e4cc3714aa5b82f7f05402355a56f3666066659c69494f2f2f2a643f22218879206cdf5608e971fa2e
|
7
|
+
data.tar.gz: 4388e9cfba5ec46a464e283a61fb007aa4560613a40f6fda3bc65980038004238c33e234975b4097d4ab1db3e6fa036d515d9e1a939868a0b0d18a4d220bf6aa
|
data/.env.example
ADDED
data/.rspec
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
--require spec_helper
|
data/CHANGELOG.md
ADDED
data/CODE_OF_CONDUCT.md
ADDED
@@ -0,0 +1,132 @@
|
|
1
|
+
# Contributor Covenant Code of Conduct
|
2
|
+
|
3
|
+
## Our Pledge
|
4
|
+
|
5
|
+
We as members, contributors, and leaders pledge to make participation in our
|
6
|
+
community a harassment-free experience for everyone, regardless of age, body
|
7
|
+
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
8
|
+
identity and expression, level of experience, education, socio-economic status,
|
9
|
+
nationality, personal appearance, race, caste, color, religion, or sexual
|
10
|
+
identity and orientation.
|
11
|
+
|
12
|
+
We pledge to act and interact in ways that contribute to an open, welcoming,
|
13
|
+
diverse, inclusive, and healthy community.
|
14
|
+
|
15
|
+
## Our Standards
|
16
|
+
|
17
|
+
Examples of behavior that contributes to a positive environment for our
|
18
|
+
community include:
|
19
|
+
|
20
|
+
* Demonstrating empathy and kindness toward other people
|
21
|
+
* Being respectful of differing opinions, viewpoints, and experiences
|
22
|
+
* Giving and gracefully accepting constructive feedback
|
23
|
+
* Accepting responsibility and apologizing to those affected by our mistakes,
|
24
|
+
and learning from the experience
|
25
|
+
* Focusing on what is best not just for us as individuals, but for the overall
|
26
|
+
community
|
27
|
+
|
28
|
+
Examples of unacceptable behavior include:
|
29
|
+
|
30
|
+
* The use of sexualized language or imagery, and sexual attention or advances of
|
31
|
+
any kind
|
32
|
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
33
|
+
* Public or private harassment
|
34
|
+
* Publishing others' private information, such as a physical or email address,
|
35
|
+
without their explicit permission
|
36
|
+
* Other conduct which could reasonably be considered inappropriate in a
|
37
|
+
professional setting
|
38
|
+
|
39
|
+
## Enforcement Responsibilities
|
40
|
+
|
41
|
+
Community leaders are responsible for clarifying and enforcing our standards of
|
42
|
+
acceptable behavior and will take appropriate and fair corrective action in
|
43
|
+
response to any behavior that they deem inappropriate, threatening, offensive,
|
44
|
+
or harmful.
|
45
|
+
|
46
|
+
Community leaders have the right and responsibility to remove, edit, or reject
|
47
|
+
comments, commits, code, wiki edits, issues, and other contributions that are
|
48
|
+
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
49
|
+
decisions when appropriate.
|
50
|
+
|
51
|
+
## Scope
|
52
|
+
|
53
|
+
This Code of Conduct applies within all community spaces, and also applies when
|
54
|
+
an individual is officially representing the community in public spaces.
|
55
|
+
Examples of representing our community include using an official email address,
|
56
|
+
posting via an official social media account, or acting as an appointed
|
57
|
+
representative at an online or offline event.
|
58
|
+
|
59
|
+
## Enforcement
|
60
|
+
|
61
|
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
62
|
+
reported to the community leaders responsible for enforcement at
|
63
|
+
[INSERT CONTACT METHOD].
|
64
|
+
All complaints will be reviewed and investigated promptly and fairly.
|
65
|
+
|
66
|
+
All community leaders are obligated to respect the privacy and security of the
|
67
|
+
reporter of any incident.
|
68
|
+
|
69
|
+
## Enforcement Guidelines
|
70
|
+
|
71
|
+
Community leaders will follow these Community Impact Guidelines in determining
|
72
|
+
the consequences for any action they deem in violation of this Code of Conduct:
|
73
|
+
|
74
|
+
### 1. Correction
|
75
|
+
|
76
|
+
**Community Impact**: Use of inappropriate language or other behavior deemed
|
77
|
+
unprofessional or unwelcome in the community.
|
78
|
+
|
79
|
+
**Consequence**: A private, written warning from community leaders, providing
|
80
|
+
clarity around the nature of the violation and an explanation of why the
|
81
|
+
behavior was inappropriate. A public apology may be requested.
|
82
|
+
|
83
|
+
### 2. Warning
|
84
|
+
|
85
|
+
**Community Impact**: A violation through a single incident or series of
|
86
|
+
actions.
|
87
|
+
|
88
|
+
**Consequence**: A warning with consequences for continued behavior. No
|
89
|
+
interaction with the people involved, including unsolicited interaction with
|
90
|
+
those enforcing the Code of Conduct, for a specified period of time. This
|
91
|
+
includes avoiding interactions in community spaces as well as external channels
|
92
|
+
like social media. Violating these terms may lead to a temporary or permanent
|
93
|
+
ban.
|
94
|
+
|
95
|
+
### 3. Temporary Ban
|
96
|
+
|
97
|
+
**Community Impact**: A serious violation of community standards, including
|
98
|
+
sustained inappropriate behavior.
|
99
|
+
|
100
|
+
**Consequence**: A temporary ban from any sort of interaction or public
|
101
|
+
communication with the community for a specified period of time. No public or
|
102
|
+
private interaction with the people involved, including unsolicited interaction
|
103
|
+
with those enforcing the Code of Conduct, is allowed during this period.
|
104
|
+
Violating these terms may lead to a permanent ban.
|
105
|
+
|
106
|
+
### 4. Permanent Ban
|
107
|
+
|
108
|
+
**Community Impact**: Demonstrating a pattern of violation of community
|
109
|
+
standards, including sustained inappropriate behavior, harassment of an
|
110
|
+
individual, or aggression toward or disparagement of classes of individuals.
|
111
|
+
|
112
|
+
**Consequence**: A permanent ban from any sort of public interaction within the
|
113
|
+
community.
|
114
|
+
|
115
|
+
## Attribution
|
116
|
+
|
117
|
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
118
|
+
version 2.1, available at
|
119
|
+
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
|
120
|
+
|
121
|
+
Community Impact Guidelines were inspired by
|
122
|
+
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
|
123
|
+
|
124
|
+
For answers to common questions about this code of conduct, see the FAQ at
|
125
|
+
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
|
126
|
+
[https://www.contributor-covenant.org/translations][translations].
|
127
|
+
|
128
|
+
[homepage]: https://www.contributor-covenant.org
|
129
|
+
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
|
130
|
+
[Mozilla CoC]: https://github.com/mozilla/diversity
|
131
|
+
[FAQ]: https://www.contributor-covenant.org/faq
|
132
|
+
[translations]: https://www.contributor-covenant.org/translations
|
data/LICENSE.txt
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
The MIT License (MIT)
|
2
|
+
|
3
|
+
Copyright (c) 2025 JM
|
4
|
+
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
7
|
+
in the Software without restriction, including without limitation the rights
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
10
|
+
furnished to do so, subject to the following conditions:
|
11
|
+
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
13
|
+
all copies or substantial portions of the Software.
|
14
|
+
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
21
|
+
THE SOFTWARE.
|
data/README.md
ADDED
@@ -0,0 +1,168 @@
|
|
1
|
+
# NinjaVanAPI
|
2
|
+
|
3
|
+
A Ruby gem for integrating with NinjaVan's API and handling webhooks in Rails applications.
|
4
|
+
|
5
|
+
## Installation
|
6
|
+
|
7
|
+
Add this line to your application's Gemfile:
|
8
|
+
|
9
|
+
```ruby
|
10
|
+
gem 'ninja_van_api'
|
11
|
+
```
|
12
|
+
|
13
|
+
And then execute:
|
14
|
+
|
15
|
+
$ bundle install
|
16
|
+
|
17
|
+
## Usage
|
18
|
+
|
19
|
+
### Mounting the Engine
|
20
|
+
|
21
|
+
In your Rails application's `config/routes.rb`, mount the webhook engine. You can mount it multiple times with different country paths. For example:
|
22
|
+
|
23
|
+
```ruby
|
24
|
+
Rails.application.routes.draw do
|
25
|
+
# Mount multiple endpoints for different countries
|
26
|
+
mount NinjaVanAPI::Engine => '/ninja_van/my'
|
27
|
+
mount NinjaVanAPI::Engine => '/ninja_van/sg'
|
28
|
+
mount NinjaVanAPI::Engine => '/ninja_van/id'
|
29
|
+
end
|
30
|
+
```
|
31
|
+
|
32
|
+
### Configuring Webhooks
|
33
|
+
|
34
|
+
Create an initializer in `config/initializers/ninja_van_api.rb`. When configuring webhook secrets, you'll need to provide a hash where each key is a country code that corresponds to your mounting paths:
|
35
|
+
|
36
|
+
```ruby
|
37
|
+
NinjaVanAPI.configure do |config|
|
38
|
+
# Set your webhook job class to process incoming webhooks
|
39
|
+
config.webhook_job_class = "NinjaVanWebhookJob"
|
40
|
+
|
41
|
+
# Set your webhook secrets (obtained from NinjaVan)
|
42
|
+
# The country code in the mounting path (e.g., 'my', 'sg', 'id')
|
43
|
+
# determines which secret is used for verification
|
44
|
+
config.webhook_secrets = {
|
45
|
+
my: 'your-malaysia-webhook-secret',
|
46
|
+
sg: 'your-singapore-webhook-secret',
|
47
|
+
id: 'your-indonesia-webhook-secret'
|
48
|
+
}
|
49
|
+
end
|
50
|
+
```
|
51
|
+
|
52
|
+
Note: The country code from your mounting path (e.g., '/ninja_van/my' uses 'MY') determines which webhook secret is used to verify incoming webhooks. The country codes are case-insensitive.
|
53
|
+
|
54
|
+
### Creating Orders
|
55
|
+
|
56
|
+
First, initialize the NinjaVan API client:
|
57
|
+
|
58
|
+
```ruby
|
59
|
+
client = NinjaVanAPI::Client.new(
|
60
|
+
client_id: 'your-client-id',
|
61
|
+
client_secret: 'your-client-secret',
|
62
|
+
test_mode: false # Set to true for sandbox environment
|
63
|
+
)
|
64
|
+
```
|
65
|
+
|
66
|
+
Then, create an order with the following example:
|
67
|
+
|
68
|
+
```ruby
|
69
|
+
payload = {
|
70
|
+
service_type: "Return",
|
71
|
+
service_level: "Standard",
|
72
|
+
from: {
|
73
|
+
name: "John Doe",
|
74
|
+
phone_number: "+6591234567",
|
75
|
+
email: "john.doe@gmail.com",
|
76
|
+
address: {
|
77
|
+
address1: "Block 123 Tampines Street 11",
|
78
|
+
address2: "#12-345",
|
79
|
+
area: "Tampines",
|
80
|
+
city: "Singapore",
|
81
|
+
state: "Singapore",
|
82
|
+
address_type: "office",
|
83
|
+
country: "SG",
|
84
|
+
postcode: "521123"
|
85
|
+
}
|
86
|
+
},
|
87
|
+
to: {
|
88
|
+
name: "Jane Doe",
|
89
|
+
phone_number: "+6598765432",
|
90
|
+
email: "jane.doe@gmail.com",
|
91
|
+
address: {
|
92
|
+
address1: "Block 456 Jurong West Street 42",
|
93
|
+
address2: "#08-910",
|
94
|
+
area: "Jurong West",
|
95
|
+
city: "Singapore",
|
96
|
+
state: "Singapore",
|
97
|
+
address_type: "home",
|
98
|
+
country: "SG",
|
99
|
+
postcode: "640456"
|
100
|
+
}
|
101
|
+
},
|
102
|
+
parcel_job: {
|
103
|
+
is_pickup_required: true,
|
104
|
+
pickup_service_type: "Scheduled",
|
105
|
+
pickup_service_level: "Standard",
|
106
|
+
pickup_date: "2025-02-26",
|
107
|
+
pickup_timeslot: {
|
108
|
+
start_time: "09:00",
|
109
|
+
end_time: "18:00",
|
110
|
+
timezone: "Asia/Kuala_Lumpur"
|
111
|
+
},
|
112
|
+
delivery_start_date: "2025-02-26",
|
113
|
+
delivery_timeslot: {
|
114
|
+
start_time: "09:00",
|
115
|
+
end_time: "18:00",
|
116
|
+
timezone: "Asia/Kuala_Lumpur"
|
117
|
+
},
|
118
|
+
dimensions: {
|
119
|
+
weight: 1.5
|
120
|
+
},
|
121
|
+
items: [
|
122
|
+
{
|
123
|
+
item_description: "Sample description",
|
124
|
+
quantity: 1,
|
125
|
+
is_dangerous_good: false
|
126
|
+
}
|
127
|
+
]
|
128
|
+
}
|
129
|
+
}
|
130
|
+
|
131
|
+
response = client.orders.create(payload)
|
132
|
+
```
|
133
|
+
|
134
|
+
### Processing Webhooks
|
135
|
+
|
136
|
+
Create a job to process the webhooks:
|
137
|
+
|
138
|
+
```ruby
|
139
|
+
class NinjaVanWebhookJob < ApplicationJob
|
140
|
+
def perform(payload)
|
141
|
+
# Process the webhook payload
|
142
|
+
# payload contains the webhook data from NinjaVan
|
143
|
+
end
|
144
|
+
end
|
145
|
+
```
|
146
|
+
|
147
|
+
The webhook endpoints will be available at your specified paths (e.g., `/ninja_van/sg`, `/ninja_van/my`, etc.) and will:
|
148
|
+
|
149
|
+
1. Verify the webhook signature using your secret
|
150
|
+
2. Enqueue the webhook job with the payload
|
151
|
+
|
152
|
+
## Development
|
153
|
+
|
154
|
+
After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
|
155
|
+
|
156
|
+
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 the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
|
157
|
+
|
158
|
+
## Contributing
|
159
|
+
|
160
|
+
Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/ninja_van_api. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/ninja_van_api/blob/main/CODE_OF_CONDUCT.md).
|
161
|
+
|
162
|
+
## License
|
163
|
+
|
164
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
165
|
+
|
166
|
+
## Code of Conduct
|
167
|
+
|
168
|
+
Everyone interacting in the NinjaVanApi project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/ninja_van_api/blob/main/CODE_OF_CONDUCT.md).
|
data/Rakefile
ADDED
@@ -0,0 +1,40 @@
|
|
1
|
+
module NinjaVanAPI
|
2
|
+
class WebhookController < ActionController::Base
|
3
|
+
protect_from_forgery with: :null_session
|
4
|
+
before_action :verify_webhook_signature
|
5
|
+
|
6
|
+
def create
|
7
|
+
if NinjaVanAPI.configuration.webhook_job_class
|
8
|
+
NinjaVanAPI.configuration.webhook_job_class.perform_later(webhook_params.to_h)
|
9
|
+
head :ok
|
10
|
+
else
|
11
|
+
head :unprocessable_entity
|
12
|
+
end
|
13
|
+
end
|
14
|
+
|
15
|
+
private
|
16
|
+
|
17
|
+
def webhook_params
|
18
|
+
params.permit!.except(:controller, :action)
|
19
|
+
end
|
20
|
+
|
21
|
+
def verify_webhook_signature
|
22
|
+
# Extract country code from the request path
|
23
|
+
# Example: /ninjavan/sg/webhooks -> 'sg'
|
24
|
+
country_code = request.path.split('/')[2]&.downcase
|
25
|
+
return head :unauthorized unless country_code.present?
|
26
|
+
|
27
|
+
webhook_secret = NinjaVanAPI.configuration.get_webhook_secret(country_code)
|
28
|
+
return head :unauthorized unless webhook_secret
|
29
|
+
|
30
|
+
signature = request.headers['X-Ninjavan-Hmac-Sha256']
|
31
|
+
return head :unauthorized unless signature.present?
|
32
|
+
|
33
|
+
payload = request.raw_post
|
34
|
+
hash = OpenSSL::HMAC.digest('sha256', webhook_secret, payload)
|
35
|
+
expected_signature = Base64.encode64(hash).strip
|
36
|
+
|
37
|
+
return head :unauthorized unless Rack::Utils.secure_compare(signature, expected_signature)
|
38
|
+
end
|
39
|
+
end
|
40
|
+
end
|
data/config/routes.rb
ADDED
@@ -0,0 +1,146 @@
|
|
1
|
+
require "faraday"
|
2
|
+
require "faraday/net_http"
|
3
|
+
|
4
|
+
module NinjaVanAPI
|
5
|
+
class Client
|
6
|
+
BASE_URL = "https://api.ninjavan.co".freeze
|
7
|
+
SANDBOX_BASE_URL = "https://api-sandbox.ninjavan.co".freeze
|
8
|
+
SUPPORTED_COUNTRY_CODES = %w[SG MY TH ID VN PH MM]
|
9
|
+
|
10
|
+
attr_reader :country_code, :test_mode
|
11
|
+
|
12
|
+
def initialize(client_id:, client_secret:, country_code: "SG", test_mode: false, conn_opts: {})
|
13
|
+
@client_id = client_id
|
14
|
+
@client_secret = client_secret
|
15
|
+
@country_code = country_code
|
16
|
+
@test_mode = test_mode
|
17
|
+
@conn_opts = conn_opts
|
18
|
+
if defined?(Rails) && Rails.env.development?
|
19
|
+
@token_info = { "access_token" => ENV["NINJAVAN_API_ACCESS_TOKEN"], "expires" => Time.now.utc.to_i + 3600 }
|
20
|
+
end
|
21
|
+
|
22
|
+
validate_country_code
|
23
|
+
end
|
24
|
+
|
25
|
+
def connection
|
26
|
+
@connection ||=
|
27
|
+
Faraday.new do |conn|
|
28
|
+
conn.url_prefix = url_prefix
|
29
|
+
conn.options.merge!(@conn_opts)
|
30
|
+
# access_token will be evaluated on each request using proc
|
31
|
+
conn.request :authorization, :Bearer, -> { access_token }
|
32
|
+
conn.request :json
|
33
|
+
conn.response :json
|
34
|
+
conn.response :raise_error # Raises error on 4xx and 5xx responses
|
35
|
+
end
|
36
|
+
end
|
37
|
+
|
38
|
+
def orders
|
39
|
+
@orders ||= OrderResource.new(self)
|
40
|
+
end
|
41
|
+
|
42
|
+
private
|
43
|
+
|
44
|
+
def validate_country_code
|
45
|
+
if test_mode
|
46
|
+
if country_code != "SG"
|
47
|
+
raise NinjaVanAPI::UnsupportedCountryCodeError, "#{country_code} is not supported on test mode"
|
48
|
+
end
|
49
|
+
else
|
50
|
+
unless SUPPORTED_COUNTRY_CODES.include? country_code
|
51
|
+
raise NinjaVanAPI::UnsupportedCountryCodeError, "#{country_code} is not supported"
|
52
|
+
end
|
53
|
+
end
|
54
|
+
end
|
55
|
+
|
56
|
+
def access_token
|
57
|
+
fetch_access_token if token_expired?
|
58
|
+
|
59
|
+
if defined?(Rails) && Rails.respond_to?(:cache)
|
60
|
+
Rails.cache.read(cache_key)["access_token"]
|
61
|
+
else
|
62
|
+
@token_info["access_token"]
|
63
|
+
end
|
64
|
+
end
|
65
|
+
|
66
|
+
def refresh_access_token
|
67
|
+
@token_info = nil
|
68
|
+
Rails.cache.delete(cache_key) if defined?(Rails) && Rails.respond_to?(:cache)
|
69
|
+
fetch_access_token
|
70
|
+
end
|
71
|
+
|
72
|
+
def fetch_access_token
|
73
|
+
endpoint = "#{url_prefix}/2.0/oauth/access_token"
|
74
|
+
response =
|
75
|
+
Faraday
|
76
|
+
.new
|
77
|
+
.post(endpoint) do |req|
|
78
|
+
req.headers["Content-Type"] = "application/json"
|
79
|
+
req.body = {
|
80
|
+
client_id: @client_id,
|
81
|
+
client_secret: @client_secret,
|
82
|
+
grant_type: "client_credentials",
|
83
|
+
}.to_json
|
84
|
+
end
|
85
|
+
|
86
|
+
raise NinjaVanAPI::AuthenticationError, response.body unless response.success?
|
87
|
+
|
88
|
+
JSON.parse(response.body)["access_token"]
|
89
|
+
|
90
|
+
response =
|
91
|
+
Faraday.post(endpoint) do |req|
|
92
|
+
req.headers["Content-Type"] = "application/json"
|
93
|
+
req.headers["Accept"] = "application/json"
|
94
|
+
req.body = { client_id: @client_id, client_secret: @client_secret, grant_type: "client_credentials" }.to_json
|
95
|
+
end
|
96
|
+
|
97
|
+
handle_access_token_response(response)
|
98
|
+
end
|
99
|
+
|
100
|
+
def access_token
|
101
|
+
fetch_access_token if token_expired?
|
102
|
+
|
103
|
+
if defined?(Rails) && Rails.respond_to?(:cache)
|
104
|
+
Rails.cache.read(cache_key)["access_token"]
|
105
|
+
else
|
106
|
+
@token_info["access_token"]
|
107
|
+
end
|
108
|
+
end
|
109
|
+
|
110
|
+
def token_expired?
|
111
|
+
token_info =
|
112
|
+
if defined?(Rails) && Rails.respond_to?(:cache)
|
113
|
+
Rails.cache.read(cache_key)
|
114
|
+
else
|
115
|
+
@token_info
|
116
|
+
end
|
117
|
+
|
118
|
+
return true if token_info.nil?
|
119
|
+
|
120
|
+
# Add a buffer of 6 minutes
|
121
|
+
Time.now.utc.to_i >= (token_info["expires"] - 360)
|
122
|
+
end
|
123
|
+
|
124
|
+
def handle_access_token_response(response)
|
125
|
+
raise NinjaVanAPI::AuthenticationError unless response.success?
|
126
|
+
|
127
|
+
token_info = JSON.parse(response.body)
|
128
|
+
|
129
|
+
if defined?(Rails) && Rails.respond_to?(:cache)
|
130
|
+
Rails.cache.write(cache_key, token_info)
|
131
|
+
else
|
132
|
+
@token_info = token_info
|
133
|
+
end
|
134
|
+
end
|
135
|
+
|
136
|
+
def cache_key
|
137
|
+
"ninja_van_api_token_#{@client_id}_#{country_code}"
|
138
|
+
end
|
139
|
+
|
140
|
+
def url_prefix
|
141
|
+
endpoint = test_mode ? SANDBOX_BASE_URL : BASE_URL
|
142
|
+
|
143
|
+
"#{endpoint}/#{country_code.downcase}"
|
144
|
+
end
|
145
|
+
end
|
146
|
+
end
|
@@ -0,0 +1,49 @@
|
|
1
|
+
#
|
2
|
+
# NinjaVanAPI.configure do |config|
|
3
|
+
# config.webhook_job_class = MyWebhookJob
|
4
|
+
# config.webhook_secret = 'your-webhook-secret'
|
5
|
+
# end
|
6
|
+
#
|
7
|
+
module NinjaVanAPI
|
8
|
+
class Configuration
|
9
|
+
attr_accessor :webhook_job_class
|
10
|
+
attr_reader :webhook_secrets
|
11
|
+
|
12
|
+
def initialize
|
13
|
+
@webhook_job_class = nil
|
14
|
+
@webhook_secrets = {}
|
15
|
+
end
|
16
|
+
|
17
|
+
def webhook_secrets=(secrets)
|
18
|
+
@webhook_secrets = secrets.transform_keys(&:downcase)
|
19
|
+
end
|
20
|
+
|
21
|
+
def get_webhook_secret(country_code)
|
22
|
+
@webhook_secrets[country_code.to_s.downcase]
|
23
|
+
end
|
24
|
+
|
25
|
+
def webhook_job_class=(job_class)
|
26
|
+
return @webhook_job_class = nil if job_class.nil?
|
27
|
+
|
28
|
+
klass = job_class.is_a?(String) ? job_class.constantize : job_class
|
29
|
+
unless klass.is_a?(Class) && klass.respond_to?(:perform_later)
|
30
|
+
raise ArgumentError, 'webhook_job_class must be an ActiveJob class name or class that responds to perform_later'
|
31
|
+
end
|
32
|
+
@webhook_job_class = klass
|
33
|
+
end
|
34
|
+
end
|
35
|
+
|
36
|
+
class << self
|
37
|
+
def configuration
|
38
|
+
@configuration ||= Configuration.new
|
39
|
+
end
|
40
|
+
|
41
|
+
def configure
|
42
|
+
yield(configuration)
|
43
|
+
end
|
44
|
+
|
45
|
+
def reset_configuration!
|
46
|
+
@configuration = Configuration.new
|
47
|
+
end
|
48
|
+
end
|
49
|
+
end
|
@@ -0,0 +1,23 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require "active_support"
|
4
|
+
require "active_support/core_ext/string"
|
5
|
+
require "ostruct"
|
6
|
+
|
7
|
+
module NinjaVanAPI
|
8
|
+
class Base < OpenStruct
|
9
|
+
def initialize(attributes)
|
10
|
+
super to_ostruct(attributes)
|
11
|
+
end
|
12
|
+
|
13
|
+
def to_ostruct(obj)
|
14
|
+
if obj.is_a?(Hash)
|
15
|
+
OpenStruct.new(obj.map { |key, val| [key.to_s.underscore, to_ostruct(val)] }.to_h)
|
16
|
+
elsif obj.is_a?(Array)
|
17
|
+
obj.map { |o| to_ostruct(o) }
|
18
|
+
else # Assumed to be a primitive value
|
19
|
+
obj
|
20
|
+
end
|
21
|
+
end
|
22
|
+
end
|
23
|
+
end
|
@@ -0,0 +1,92 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require 'active_support'
|
4
|
+
require 'active_support/core_ext/string'
|
5
|
+
|
6
|
+
module NinjaVanAPI
|
7
|
+
class BaseResource
|
8
|
+
attr_reader :client
|
9
|
+
|
10
|
+
def initialize(client)
|
11
|
+
@client = client
|
12
|
+
end
|
13
|
+
|
14
|
+
def get_request(url, params: {}, headers: {})
|
15
|
+
handle_response client.connection.get(url, params, headers)
|
16
|
+
end
|
17
|
+
|
18
|
+
def post_request(url, body:, headers: {})
|
19
|
+
handle_response client.connection.post(url, parse_body(body), headers)
|
20
|
+
end
|
21
|
+
|
22
|
+
def put_request(url, body:, headers: {})
|
23
|
+
handle_response client.connection.put(url, parse_body(body), headers)
|
24
|
+
end
|
25
|
+
|
26
|
+
def delete_request(url, body: {}, headers: {})
|
27
|
+
response = client.connection.delete(url) do |request|
|
28
|
+
request.body = parse_body(body)
|
29
|
+
request.headers = request.headers.merge(headers)
|
30
|
+
end
|
31
|
+
|
32
|
+
handle_response response
|
33
|
+
end
|
34
|
+
|
35
|
+
private
|
36
|
+
|
37
|
+
def handle_response(response, retry_count = 0)
|
38
|
+
error_message = response.body
|
39
|
+
|
40
|
+
case response.status
|
41
|
+
when 400
|
42
|
+
raise Error, "A bad request or a validation exception has occurred. #{error_message}"
|
43
|
+
when 401
|
44
|
+
if retry_count.zero?
|
45
|
+
# Force token refresh and retry the request once
|
46
|
+
client.refresh_access_token
|
47
|
+
return retry_request(response.env, retry_count + 1)
|
48
|
+
else
|
49
|
+
raise Error, "Invalid authorization credentials. #{error_message}"
|
50
|
+
end
|
51
|
+
when 403
|
52
|
+
raise Error, "Connection doesn't have permission to access the resource. #{error_message}"
|
53
|
+
when 404
|
54
|
+
raise Error, "The resource you have specified cannot be found. #{error_message}"
|
55
|
+
when 429
|
56
|
+
raise Error, "The API rate limit for your application has been exceeded. #{error_message}"
|
57
|
+
when 500
|
58
|
+
raise Error,
|
59
|
+
"An unhandled error with the server. Contact the NinjaVan team if problems persist. #{error_message}"
|
60
|
+
when 503
|
61
|
+
raise Error,
|
62
|
+
"API is currently unavailable – typically due to a scheduled outage – try again soon. #{error_message}"
|
63
|
+
end
|
64
|
+
|
65
|
+
response
|
66
|
+
end
|
67
|
+
|
68
|
+
def retry_request(env, retry_count)
|
69
|
+
request = client.connection.build_request(env.method.downcase) do |req|
|
70
|
+
req.url env.url.to_s
|
71
|
+
req.body = env.request_body
|
72
|
+
req.headers = env.request_headers
|
73
|
+
end
|
74
|
+
|
75
|
+
handle_response(request.run, retry_count)
|
76
|
+
end
|
77
|
+
|
78
|
+
def parse_body(params)
|
79
|
+
if params.is_a?(Array)
|
80
|
+
params.map { |value| parse_body(value) }
|
81
|
+
elsif params.is_a?(Hash)
|
82
|
+
params.deep_transform_keys { |key| key.to_s.underscore }
|
83
|
+
else
|
84
|
+
params
|
85
|
+
end
|
86
|
+
end
|
87
|
+
|
88
|
+
def parse_response(response)
|
89
|
+
response.body.deep_transform_keys { |key| key.to_s.underscore }
|
90
|
+
end
|
91
|
+
end
|
92
|
+
end
|
@@ -0,0 +1,15 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module NinjaVanAPI
|
4
|
+
class OrderResource < BaseResource
|
5
|
+
def create(params = {})
|
6
|
+
response = post_request('/4.2/orders', body: params)
|
7
|
+
Order.new(parse_response(response))
|
8
|
+
end
|
9
|
+
|
10
|
+
def cancel(tracking_number)
|
11
|
+
response = delete_request("/2.2/orders/#{tracking_number}")
|
12
|
+
Order.new(parse_response(response))
|
13
|
+
end
|
14
|
+
end
|
15
|
+
end
|
@@ -0,0 +1,19 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative 'ninja_van_api/version'
|
4
|
+
|
5
|
+
module NinjaVanAPI
|
6
|
+
# Objects
|
7
|
+
autoload :Base, 'ninja_van_api/objects/base'
|
8
|
+
autoload :Order, 'ninja_van_api/objects/order'
|
9
|
+
|
10
|
+
# Resources
|
11
|
+
autoload :BaseResource, 'ninja_van_api/resources/base_resource'
|
12
|
+
autoload :OrderResource, 'ninja_van_api/resources/order_resource'
|
13
|
+
|
14
|
+
# Core components
|
15
|
+
autoload :Client, 'ninja_van_api/client'
|
16
|
+
autoload :Error, 'ninja_van_api/error'
|
17
|
+
autoload :UnsupportedCountryCodeError, 'ninja_van_api/error'
|
18
|
+
autoload :AuthenticationError, 'ninja_van_api/error'
|
19
|
+
end
|
metadata
ADDED
@@ -0,0 +1,163 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: ninja_van_api
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
version: 0.1.0
|
5
|
+
platform: ruby
|
6
|
+
authors:
|
7
|
+
- Jane Trang Mai Nguyen
|
8
|
+
autorequire:
|
9
|
+
bindir: exe
|
10
|
+
cert_chain: []
|
11
|
+
date: 2025-02-26 00:00:00.000000000 Z
|
12
|
+
dependencies:
|
13
|
+
- !ruby/object:Gem::Dependency
|
14
|
+
name: activesupport
|
15
|
+
requirement: !ruby/object:Gem::Requirement
|
16
|
+
requirements:
|
17
|
+
- - ">="
|
18
|
+
- !ruby/object:Gem::Version
|
19
|
+
version: '0'
|
20
|
+
type: :runtime
|
21
|
+
prerelease: false
|
22
|
+
version_requirements: !ruby/object:Gem::Requirement
|
23
|
+
requirements:
|
24
|
+
- - ">="
|
25
|
+
- !ruby/object:Gem::Version
|
26
|
+
version: '0'
|
27
|
+
- !ruby/object:Gem::Dependency
|
28
|
+
name: faraday
|
29
|
+
requirement: !ruby/object:Gem::Requirement
|
30
|
+
requirements:
|
31
|
+
- - "~>"
|
32
|
+
- !ruby/object:Gem::Version
|
33
|
+
version: '2.12'
|
34
|
+
type: :runtime
|
35
|
+
prerelease: false
|
36
|
+
version_requirements: !ruby/object:Gem::Requirement
|
37
|
+
requirements:
|
38
|
+
- - "~>"
|
39
|
+
- !ruby/object:Gem::Version
|
40
|
+
version: '2.12'
|
41
|
+
- !ruby/object:Gem::Dependency
|
42
|
+
name: faraday-encoding
|
43
|
+
requirement: !ruby/object:Gem::Requirement
|
44
|
+
requirements:
|
45
|
+
- - ">="
|
46
|
+
- !ruby/object:Gem::Version
|
47
|
+
version: '0'
|
48
|
+
type: :runtime
|
49
|
+
prerelease: false
|
50
|
+
version_requirements: !ruby/object:Gem::Requirement
|
51
|
+
requirements:
|
52
|
+
- - ">="
|
53
|
+
- !ruby/object:Gem::Version
|
54
|
+
version: '0'
|
55
|
+
- !ruby/object:Gem::Dependency
|
56
|
+
name: faraday-net_http
|
57
|
+
requirement: !ruby/object:Gem::Requirement
|
58
|
+
requirements:
|
59
|
+
- - ">="
|
60
|
+
- !ruby/object:Gem::Version
|
61
|
+
version: '0'
|
62
|
+
type: :runtime
|
63
|
+
prerelease: false
|
64
|
+
version_requirements: !ruby/object:Gem::Requirement
|
65
|
+
requirements:
|
66
|
+
- - ">="
|
67
|
+
- !ruby/object:Gem::Version
|
68
|
+
version: '0'
|
69
|
+
- !ruby/object:Gem::Dependency
|
70
|
+
name: dotenv
|
71
|
+
requirement: !ruby/object:Gem::Requirement
|
72
|
+
requirements:
|
73
|
+
- - ">="
|
74
|
+
- !ruby/object:Gem::Version
|
75
|
+
version: '0'
|
76
|
+
type: :development
|
77
|
+
prerelease: false
|
78
|
+
version_requirements: !ruby/object:Gem::Requirement
|
79
|
+
requirements:
|
80
|
+
- - ">="
|
81
|
+
- !ruby/object:Gem::Version
|
82
|
+
version: '0'
|
83
|
+
- !ruby/object:Gem::Dependency
|
84
|
+
name: pry
|
85
|
+
requirement: !ruby/object:Gem::Requirement
|
86
|
+
requirements:
|
87
|
+
- - ">="
|
88
|
+
- !ruby/object:Gem::Version
|
89
|
+
version: '0'
|
90
|
+
type: :development
|
91
|
+
prerelease: false
|
92
|
+
version_requirements: !ruby/object:Gem::Requirement
|
93
|
+
requirements:
|
94
|
+
- - ">="
|
95
|
+
- !ruby/object:Gem::Version
|
96
|
+
version: '0'
|
97
|
+
- !ruby/object:Gem::Dependency
|
98
|
+
name: rspec
|
99
|
+
requirement: !ruby/object:Gem::Requirement
|
100
|
+
requirements:
|
101
|
+
- - ">="
|
102
|
+
- !ruby/object:Gem::Version
|
103
|
+
version: '0'
|
104
|
+
type: :development
|
105
|
+
prerelease: false
|
106
|
+
version_requirements: !ruby/object:Gem::Requirement
|
107
|
+
requirements:
|
108
|
+
- - ">="
|
109
|
+
- !ruby/object:Gem::Version
|
110
|
+
version: '0'
|
111
|
+
description:
|
112
|
+
email:
|
113
|
+
- jane.trangm@gmail.com
|
114
|
+
executables: []
|
115
|
+
extensions: []
|
116
|
+
extra_rdoc_files: []
|
117
|
+
files:
|
118
|
+
- ".env.example"
|
119
|
+
- ".rspec"
|
120
|
+
- CHANGELOG.md
|
121
|
+
- CODE_OF_CONDUCT.md
|
122
|
+
- LICENSE.txt
|
123
|
+
- README.md
|
124
|
+
- Rakefile
|
125
|
+
- app/controllers/ninja_van_api/webhook_controller.rb
|
126
|
+
- config/routes.rb
|
127
|
+
- lib/ninja_van_api.rb
|
128
|
+
- lib/ninja_van_api/client.rb
|
129
|
+
- lib/ninja_van_api/configuration.rb
|
130
|
+
- lib/ninja_van_api/engine.rb
|
131
|
+
- lib/ninja_van_api/error.rb
|
132
|
+
- lib/ninja_van_api/objects/base.rb
|
133
|
+
- lib/ninja_van_api/objects/order.rb
|
134
|
+
- lib/ninja_van_api/resources/base_resource.rb
|
135
|
+
- lib/ninja_van_api/resources/order_resource.rb
|
136
|
+
- lib/ninja_van_api/version.rb
|
137
|
+
- sig/ninja_van_api.rbs
|
138
|
+
homepage: https://github.com/Postco/ninja_van_api
|
139
|
+
licenses:
|
140
|
+
- MIT
|
141
|
+
metadata:
|
142
|
+
homepage_uri: https://github.com/Postco/ninja_van_api
|
143
|
+
source_code_uri: https://github.com/Postco/ninja_van_api
|
144
|
+
post_install_message:
|
145
|
+
rdoc_options: []
|
146
|
+
require_paths:
|
147
|
+
- lib
|
148
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
149
|
+
requirements:
|
150
|
+
- - ">="
|
151
|
+
- !ruby/object:Gem::Version
|
152
|
+
version: 3.0.0
|
153
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
154
|
+
requirements:
|
155
|
+
- - ">="
|
156
|
+
- !ruby/object:Gem::Version
|
157
|
+
version: '0'
|
158
|
+
requirements: []
|
159
|
+
rubygems_version: 3.5.23
|
160
|
+
signing_key:
|
161
|
+
specification_version: 4
|
162
|
+
summary: Ninja Van API Wrapper
|
163
|
+
test_files: []
|