Facebook API:生成具有权限的用户access_token

时间:2018-03-14 09:03:49

标签: python facebook-graph-api

简而言之:如何通过许可获取Facebook API access_token

我想使用Python从Facebook API读取特定广告设置的覆盖面。为此,我需要一个具有扩展权限的facebook访问令牌。我使用以下函数来获取新的访问令牌,但我得到的令牌没有适当的权限级别。那么:如何获得具有自定义权限的access_token,就像您可以手动执行here

下面的Python示例(问题实际上与语言无关):

import requests
import json
from facebookads.adobjects.adaccount import AdAccount
from facebookads.api import FacebookAdsApi
from facebookads.adobjects.adset import AdSet

app_id = 'xxxx'
app_secret = 'xxxx'
account_id = 'xxxx'

def get_fb_token(app_id, app_secret):
    payload = {'grant_type': 'client_credentials', 
               'client_id': app_id, 
               'client_secret': app_secret,
               }
    file = requests.post('https://graph.facebook.com/oauth/access_token?', params = payload)

    string = file.content.decode('utf-8')
    json_obj = json.loads(string)  
    return json_obj['access_token']

access_token = get_fb_token(app_id, app_secret)
account = AdAccount(account_id)

# initiate API
FacebookAdsApi.init(app_id, app_secret, access_token)

# Request reach
targeting_spec = {
                'geo_locations': {
                    'countries': ['nl']
                },
            }
fb_params = {
            'currency': 'EUR',
            'optimize_for': AdSet.OptimizationGoal.offsite_conversions,
            'targeting_spec': targeting_spec,
        }
reach_estimate = account.get_reach_estimate(params=fb_params)

我收到错误消息:

(#278) Reading advertisements requires an access token with the extended permission ads_read

非常感谢帮助!

1 个答案:

答案 0 :(得分:0)

试试这个:

payload = {
    'grant_type': 'client_credentials', 
    'client_id': app_id, 
    'client_secret': app_secret,
    'scope': 'ads_read'
}
file = requests.post('https://graph.facebook.com/oauth/access_token?', params = payload)

此外,您需要重定向到正确的端点(https://www.facebook.com/v2.xy/dialog/oauth),而不是POST。没有用户交互,您无法获得用户令牌。