Skip to content

Commit

Permalink
feat: support multiple customer
Browse files Browse the repository at this point in the history
  • Loading branch information
xifengzhu committed Dec 3, 2020
1 parent 846bfe3 commit 8ddee0d
Show file tree
Hide file tree
Showing 6 changed files with 96 additions and 49 deletions.
36 changes: 19 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ A simple gem provides Kuaidi100 enterprise-edition APIs, includes query the expr
Add this line to your Gemfile:

```ruby
gem 'kuaidi100', :github => 'xifengzhu/kuaidi100'
gem 'kuaidi100', github: 'xifengzhu/kuaidi100', branch: 'feature/support-multi-client'
```

And then execute:
Expand All @@ -20,18 +20,6 @@ $ bundle

## Usage

### Config

Create `config/initializers/kuaidi100.rb` and put following configurations into it.

```ruby
# required
Kuaidi100.key = 'key'
Kuaidi100.customer = 'customer_id'
Kuaidi100.salt = "salt"
Kuaidi100.callbackurl = "http://${domain}.com"
```

### APIs

Kuaidi100 gem supports express track query and subscribe push from kuaidi100.
Expand All @@ -49,10 +37,21 @@ Common Kuaidi100 Express Code:
"yunda"=>"韵达"
```

#### Init Client

```ruby
client = Kuaidi100::Client.new({
key: 'xxx',
customer: 'xxx',
salt: 'xxx',
callbackurl: 'http://${domain}/apps/${app_id}/express/notify'
})
```

#### Express Track Query

```ruby
result = Kuaidi100::Service.logistic_traces("765698489802", "shunfeng", {mobiletelephone: '132xxxxxxxx'})
result = client.query('765720722994', "shunfeng", { mobiletelephone: '132xxxxxxx' })
# => {
# "message"=>"ok",
# "nu"=>"765720722994",
Expand Down Expand Up @@ -80,7 +79,7 @@ result = Kuaidi100::Service.logistic_traces("765698489802", "shunfeng", {mobilet
#### Subscribe Push from Kuaidi100

```ruby
result = Kuaidi100::Service.subscribe("765698489802", "shunfeng", {mobiletelephone: '132xxxxxxxx'})
result = client.subscribe('765720722994', "shunfeng", { mobiletelephone: '132xxxxxxxx' })
# => {
# "result":true,
# "returnCode":"200",
Expand All @@ -95,12 +94,15 @@ A simple example of processing notify.

```ruby
# config/routes.rb
post "notify" => "express#notify"
post "apps/:id/express/notify" => "express#notify"

# app/controllers/express_controller.rb

def notify
if Kuaidi100::Sign.callback_verify?(params)
# find the business model with id and get the salt
app = Bean::Application.find(params[:id])

if Kuaidi100::Sign.callback_verify?(params, app.salt)

# find your logistic and update it

Expand Down
7 changes: 1 addition & 6 deletions lib/kuaidi100.rb
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
require 'kuaidi100/sign'
require 'kuaidi100/service'
require "kuaidi100/version"

module Kuaidi100
class << self
attr_accessor :key, :customer, :callbackurl, :salt
end
end
require "kuaidi100/client"
57 changes: 57 additions & 0 deletions lib/kuaidi100/client.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
module Kuaidi100
class Client

include ::HTTParty
include Kuaidi100::Service

base_uri 'https://poll.kuaidi100.com'.freeze

attr_accessor :key, :customer, :callbackurl, :salt

@@logger = ::Logger.new("./log/kuaidi100.log")

HTTP_ERRORS = [
EOFError,
Errno::ECONNRESET,
Errno::EINVAL,
Net::HTTPBadResponse,
Net::HTTPHeaderSyntaxError,
Net::ProtocolError,
Timeout::Error
]
TIMEOUT = 5

def initialize(key:, customer:, salt:, callbackurl:)
@key = key
@customer = customer
@salt = salt
@callbackurl = callbackurl
end

def http_get(path, options)
options = options.dup.merge!({
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Accept-Encoding" => "*"
},
timeout: TIMEOUT
})

uuid = SecureRandom.uuid

@@logger.debug("request[#{uuid}] url: #{path}, options: #{options}")

response = begin
resp = self.class.get(path, options).body
rescue JSON::ParserError
resp
rescue *HTTP_ERRORS
{ "errmsg" => "连接超时" }
end
@@logger.debug("response[#{uuid}]: #{response}")

JSON.parse(response)

end
end
end
34 changes: 13 additions & 21 deletions lib/kuaidi100/service.rb
Original file line number Diff line number Diff line change
@@ -1,47 +1,43 @@
require 'httparty'

module Kuaidi100
class Service
include ::HTTParty
module Service

base_uri 'https://poll.kuaidi100.com'.freeze

def self.logistic_traces(express_no, express_code, options = {})
def query(express_no, express_code, options = {})

params = {
com: express_code, # 快递公司编码
num: express_no, # 快递单号
phone: options.delete(:mobiletelephone) || "", # 寄件人或收件人手机号(顺丰单号必填)
from: options.delete(:from) || "", # 出发地城市(可空)
to: options.delete(:to) || "", # 目的地城市(可空)
resultv2: options.delete(:resultv2) || 0 # 添加此字段表示开通行政区域解析功能
resultv2: options.delete(:resultv2) || 0, # 添加此字段表示开通行政区域解析功能
# 用来generate签名的额外参数
key: @key,
customer: @customer
}

payload = {
customer: Kuaidi100.customer,
customer: @customer || Kuaidi100.customer,
sign: Kuaidi100::Sign.generate(params),
param: params.to_json
}

response = self.get('/poll/query.do',
query: payload,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
)
JSON.parse(response.body)
http_get('/poll/query.do', { query: payload })
end

def self.subscribe(express_no, express_code, options = {})
def subscribe(express_no, express_code, options = {})

# TODO: 支持 parameters 参数
params = {
company: express_code,
number: express_no,
from: options.delete(:from) || "",
to: options.delete(:to) || "",
key: Kuaidi100.key,
key: @key || Kuaidi100.key,
parameters: {
"callbackurl": Kuaidi100.callbackurl,
"salt": Kuaidi100.salt,
"callbackurl": @callbackurl || Kuaidi100.callbackurl,
"salt": @salt || Kuaidi100.salt,
"mobiletelephone": options.delete(:mobiletelephone) || "", # 寄件人或收件人手机号(顺丰单号必填)
"resultv2": "0",
"autoCom": "0",
Expand All @@ -58,11 +54,7 @@ def self.subscribe(express_no, express_code, options = {})
param: params.to_json
}

response = self.get('/poll',
query: payload,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
)
JSON.parse(response.body)
http_get('/poll', { query: payload })
end
end
end
9 changes: 5 additions & 4 deletions lib/kuaidi100/sign.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,17 @@ module Kuaidi100
module Sign

def self.generate(params)
param = params.dup
string_sign_temp = (param.to_json + Kuaidi100.key + Kuaidi100.customer).to_s
key = params.delete(:key) || Kuaidi100.key
customer = params.delete(:customer) || Kuaidi100.customer
string_sign_temp = (params.to_json + key + customer).to_s
Digest::MD5.hexdigest(string_sign_temp).upcase
end

# MD5(param + salt) == sign
def self.callback_verify?(params)
def self.callback_verify?(params, salt)
params = params.dup
sign = params.delete('sign')
sign_string = params.delete('param') + Kuaidi100.salt
sign_string = params.delete('param') + (salt || Kuaidi100.salt)
sign == Digest::MD5.hexdigest(sign_string).upcase
end
end
Expand Down
2 changes: 1 addition & 1 deletion lib/kuaidi100/version.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module Kuaidi100
VERSION = "0.1.2"
VERSION = "0.1.3"
end

0 comments on commit 8ddee0d

Please sign in to comment.