欢迎来到cool的博客
7

Music box

Click to Start

点击头像播放音乐
新博客链接

rails中集成阿里云物流查询api(aliyun 快递查询接口 - API)

阿里云开发文档:https://market.aliyun.com/products/57126001/cmapi011120.html?spm=5176.2020520132.101.13.d9dH00#sku=yuncode512000008

案例实例:

 

1.首先在阿里云 开通产品,云服务中的 快递查询。开通之后获得三个key  (AppKey ,AppSecret, AppCode)  AppCode是需要用到的。把它放在settings.yml中

2.Gemfile中添加:

gem 'httparty', '0.13.7'

3.增加一个表,保存所有的物流公司 express_types

4.初始化所有的物流公司,脚本方法如下:(app/models/member_user.rb)

  def self.init_express_type
    url = "http://jisukdcx.market.alicloudapi.com/express/type"
    appcode = Settings.AppCode
    response = HTTParty.get(url, headers: {"Authorization" => "APPCODE #{appcode}"})
    express_types = JSON.parse(response.body)["result"]
    logger.info "快递公司类型:=======#{express_types}======="
    logger.info "=======开始初始化所有的快递公司 保存到数据库======="
    express_types.each do |express_type|
      ExpressType.create(
        :name => express_type["name"],
        :express_type => express_type["type"],
        :letter => express_type["letter"],
        :tel => express_type["tel"],
        :number => express_type["number"]
      )
    end
    logger.info "=======结束初始化所有的快递公司======="
  end

5.增加了 物流查询的方法:根据参数, 快递公司和 订单号返回 一大段 json.

  def self.search_express_status(type, number)
    logger.info "==== 开始查询"
    appcode = Settings.AppCode
    headers = {
      "Authorization" => "APPCODE #{appcode}"
    }
    url = "http://jisukdcx.market.alicloudapi.com/express/query?number=#{number}&type=#{type}"
    result = HTTParty.get(url, headers: headers)
    logger.info "=======#{result.inspect}======="
    return result
  end

6.controller中的方法:

  def do_search
    if params[:express_type].present? and params[:express_number].present?
      result = MemberUser.search_express_status(params[:express_type], params[:express_number])
      msg = result['msg']
      if msg == "ok"
        express_type = result['result']['type']
        express_lists = result['result']['list']
        logger.info "======= msg: #{msg}"
        logger.info "======= express_lists: #{express_lists}"
        express_time_and_status = []
        express_lists.each do |l|
          status = l["time"] + " " + l["status"]
          express_time_and_status.push(status)
        end
        express_time_and_status = express_time_and_status.reverse
        logger.info "======= express_time_and_status: #{express_time_and_status}"
        render :json => {
          msg: msg,
          express_type: express_type,
          express_lists: express_time_and_status
        }
      else
        render :json => {
          msg: msg
        }
      end
    end
  end

7.view使用 ajax 发起请求:

<div class="m_right">
  <div class="search_field">
    <%= select_tag :express_type, options_from_collection_for_select(ExpressType.all, :express_type, :name), :prompt => "请选择快递类型"
    <span class="label_text"><%= label_tag "快递单号:" %></span>
    <%= text_field_tag :express_number, "", placeholder: "例如:201708058888",  style: "width: 200px;" %>
    <%= button_tag "确定", class: "submit_button", id: "submit_button" %>
  </div>
  <hr/>
  <div id="express_status">
  </div>
</div>

 
<script>
$("#submit_button").click(function() {
  var express_type = $("#select_express_type").select2().val()
  var express_number = $("#express_number").val()
  if (express_type != "" && express_number != "") {
    console.info(express_type)
      console.info(express_number)
      $.post(
          "/member_users/do_search",
          {
            express_type: express_type,
            express_number: express_number
          },
          function(data) {
            if(data.msg == "ok"){
              console.info(data)
              var express_lists = data.express_lists
              console.info(express_lists)
              $.each(express_lists, function(index, value) {
                index += 1
                  $("#express_status").append("<p class='express_list'>" + index + ". " + value + "</p>")
              })
            } else {
              alert("此单号不存在")
            }
          }
      )
  } else {
    alert("请正确填写快递单号信息")
  }
})

返回列表