如何使用Ruby on Rails从Facebook营销API获得潜在覆盖面5
问题描述:
我想从使用Ruby on Rails 5的Facebook营销API中获取potential reach。我找到了Ruby SDK here,但我看不到示例代码和我需要获取我想要的数据的功能。我也发现了这个post这是基于Python的,并试图将语言转化为红宝石这使我这个代码:如何使用Ruby on Rails从Facebook营销API获得潜在覆盖面5
require "facebook_ads"
class FacebookApi
attr_reader :ad_instance
def initialize(opts={})
@ad_instance = FacebookAds::AdAccount.get("act_#{opts[:account_id]}")
raise 'Account ID Key must be provided' unless opts[:account_id]
end
def get_target()
targeting_spec = {
'geo_locations': {
'countries': ['US'],
},
'age_min': 20,
'age_max': 40,
}
params = {
'targeting_spec': targeting_spec,
}
@ad_instance.get_reach_estimate(params: params)
end
end
然而,功能get_reach_estimate没有找到。
我也试着模仿样本卷曲的命令,而不是与下面的测试脚本上来:
require 'net/http'
require 'uri'
require "erb"
include ERB::Util
class FacebookApi
def get_target()
account_id = <ACCOUNT_ID>
access_token = <USER_ACCESS_TOKEN_WITH_ADS_MANAGEMENT_PRIVILEGE>
uri = URI.parse("https://graph.facebook.com/v2.10/act_#{account_id}/reachestimate")
request = Net::HTTP::Post.new(uri)
request.set_form_data(
"access_token" => access_token,
"targeting_spec" => url_encode("{\"geo_locations\": {\"countries\":[\"US\"]}, \"age_min\": 20, \"age_max\": 40}")
)
req_options = {
use_ssl: uri.scheme == "https",
}
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
puts response.code
puts response.body
end
end
请留意,我用我的代码中的实际帐户ID和访问令牌。只是把它藏在这里。所以,现在上面的代码返回以下错误:
{
"error": {
"message": "Unsupported post request. Object with ID <ACCOUNT_ID> does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api",
"type": "GraphMethodException",
"code": 100,
"fbtrace_id": "ESJks9/KxJC"
}
}
我敢肯定,我加入了ad_management访问我的访问令牌。我也尝试删除URI中的前缀act_,但结果相同。我现在正处于死路一条,所以我想问一些关于如何做到这一点的建议。非常感谢你。
答
原来,这是因为发布的请求。我应该使用GET请求。以下是我的工作代码,其中兴趣点参数适用于定位规范。
def get_target(interest_id, interest_name)
account_id = @account_id
access_token = @access_token
url = "https://graph.facebook.com/v2.10/act_#{account_id}/reachestimate"
params = {
"access_token" => access_token,
"targeting_spec" => "{" +
"\"geo_locations\": {\"country_groups\":[\"Worldwide\"]}," +
" \"age_min\": 20, \"age_max\": 40," +
" \"interests\": [" +
"{\"id\":#{interest_id}, \"name\":\"#{interest_name}\"}" +
"]" +
"}"
}
response = get_response(url, params)
response
end
def get_response(url, params)
uri = URI.parse(url)
uri.query = URI.encode_www_form(params)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Get.new(uri)
response = http.request(request)
response.body
end