在带有HTTParty的rails应用程序中使用Postmates API

Hay*_*r87 2 ruby httparty ruby-on-rails-3

我一直在努力将Postmates与我的电子商务rails应用程序集成,以便按需交付.我已经为测试目的构建了一个控制器和视图,并在我的路径文件中构建它(在我的开发环境中构建).作为参考,这里是Postmates的文档:docs,这是一个技术博客:博客

路线文件:

resources :postmates do
    member do 
        post 'get_delivery'
    end
  end
Run Code Online (Sandbox Code Playgroud)

控制器:

require 'httparty'
require 'json'

class PostmatesController < ApplicationController

  def get_delivery
    api_key = **hidden**
    @customer = 'cus_K8mRn4ovuNyNKV'
    @urlstring_to_post = 'https://api.postmates.com/v1/customers/' + @customer + '/delivery_quotes'

    @result = HTTParty.post(@urlstring_to_post.to_str,
      :body => { :dropoff_address => "205 E 95th Street, New York, NY 10128", 
                 :pickup_address => "619 W 54th St, New York, NY 10019" 
                }.to_json,
      :basic_auth => { :username => api_key },
      :headers => { 'Content-Type' => 'application/json' })
  end

end
Run Code Online (Sandbox Code Playgroud)

风景:

<div class="container">
  <%= form_tag url_for(:controller => 'postmates', :action => 'get_delivery'), :method => 'post' do %>
  <%= submit_tag "Get Delivery", :action => 'get_delivery', :controller => 'postmates'%>  
  <% end %>
</div>

<p>Result: <%= @result %></p>
Run Code Online (Sandbox Code Playgroud)

以下是来自api的回复:

{"kind"=>"error", "code"=>"invalid_params", "params"=>{"dropoff_address"=>"This field is required.", "pickup_address"=>"This field is required."}, "message"=>"The parameters of your request were invalid."}
Run Code Online (Sandbox Code Playgroud)

在我看来,在HTTP请求中没有提交下降和拾取地址.任何人都可以告诉我,如果我正在做一些小的语法错误或什么?我收到此回复的事实意味着我的身份验证很好,网址也是如此.有任何想法吗?

谢谢.

rhe*_*ttg 5

看起来你要将JSON数据发布到API,而文档(https://postmates.com/developer/docs#basics)说你应该将数据发布为application/x-www-form-urlencoded

我对HTTParty并不熟悉,但您可以删除.to_json并且不指定content-type标头.

  • 工作的真棒男人!非常感谢!这是我第一次尝试使用API​​,所以这是一个艰难的过程.希望这将有助于其他想要使用Postmates的经验不足的rails开发者. (2认同)