POST 至 Facebook Messenger Ruby Net::HTTP 错误 100

POST to Facebook Messenger with Ruby Net::HTTP error 100

我正在尝试从我的模型 (user.rb) 向 Facebook 发出直接 POST 请求,以便在 Messenger 中向该用户发送一条简单消息。但是我得到这个错误:

{"error":{"message":"(#100) param recipient must be non-empty.","type":"OAuthException","code":100,"fbtrace_id":"F07BNxzgciW"}} 

这是我的方法:

def send_message(msg)
    url = "https://graph.facebook.com/v2.6/me/messages?access_token="+ENV['PAGE_ACCESS_TOKEN']
    data = {
      'recipient': {
        'id': self.facebook_id
      },
      'message': {
        'text': msg
      }
    }
    #data = JSON.pretty_generate(data)
    puts data
    uri = URI(url)
    res = Net::HTTP.post_form(uri, data)
    puts res.body
end

似乎数据格式不正确,因此无法识别用户 ID。

取消注释 #data 行我得到这个错误,因为数据是一个字符串,而不是哈希:

NoMethodError: undefined method `map' for #<String:0x000000034bd248>

这是我试图重现的来自 Facebook 文档的请求示例:

curl -X POST -H "Content-Type: application/json" -d '{
  "recipient": {
    "id": "USER_ID"
  },
  "message": {
    "text": "hello, world!"
  }
}' "https://graph.facebook.com/v2.6/me/messages?access_token=PAGE_ACCESS_TOKEN"

试试这个:

Ruby/Rails:

uri = URI("https://graph.facebook.com/v2.6/me/messages?access_token="+ENV['PAGE_ACCESS_TOKEN'])
req = Net::HTTP::Post.new(uri)
req["Accept"] = "application/json"
req["Content-Type"] = "application/json"
req.body = {
  'recipient': {
    'id': self.facebook_id
   },
   'message': {
     'text': msg
   }
 }.to_json

 res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|
   http.request(req)
 end
 puts res.body

这可以重构为一个函数,然后在需要时调用。这个功能比上一个请求需要的功能高级一点

def http_post(url, payload='', headers={}, auth=false) #basic auth is passed as an array of ['user', 'password']
    uri = URI(url)
    req = Net::HTTP::Post.new(uri)
    headers.each do |k,v|
      req[k.to_s] = v
    end
    req.body = payload.is_a?(Hash) ? payload.to_json : payload.to_s
    req.basic_auth(*auth) if auth
    res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|
      log_this(req.inspect)
      http.request(req)
    end
    return res
  end

# you can now use like:
url = "https://graph.facebook.com/v2.6/me/messages?access_token="+ENV['PAGE_ACCESS_TOKEN']
headers = {
  "Accept": "application/json"
  "Content-Type": "application/json"
}
payload = {
  'recipient': {
    'id': self.facebook_id
  },
  'message': {
    'text': msg
  }
}
response = http_post(url, payload, options)

使用 curl,您可以执行相同的请求:

curl -X POST -H "Content-Type: application/json" -H "Accept: application/json" -d "{ \"recipient\": { \"id\": \"substitute_with_user_id\" }, \"message\": { \"text\": \"Your message goes here\" } }" https://graph.facebook.com/v2.6/me/messages?access_token=substitute_with_your_access_token

通常您不需要转义 ("\") 双引号,您可以只使用单引号 (') 作为 json 正文的分隔符,因为 curl lib 会为您完成在大多数使用它的 OS 中,但在 windows 上似乎你需要,并且有效地,它最终会在引擎盖下被转义,所以我猜这是正确的形式。