如何通过Graph API或OAuth登录流获取Facebook Pixel ID?
Let's break down how to solve your problem, since the error you're hitting comes from a misunderstanding of how app permissions vs. user authorization work for Ads API resources.
Why You Got the (#274) Error
The error you saw happens because you were trying to access your own ad account through your app, but hadn't added that account to your app's allowed advertising accounts list. However, this step is only required when you're accessing your own business assets programmatically. For your use case—accessing your users' Pixel IDs—you don't need to add their ad accounts to your app settings at all. Instead, you need to get the user's explicit authorization to access their ad account data.
Step-by-Step Solution
1. Request the Correct OAuth Permissions
First, you need to ask users for permissions that let your app access their ad accounts and associated Pixels. The key permissions you'll need are:
ads_read: This lets your app read the user's ad account data (including Pixels) without modifying anything.- Optional
ads_management: Use this only if you need to create or modify Pixels for the user (you probably don't need this for just fetching IDs).
When initiating the OAuth login flow, include these permissions in your scope parameter. For example, your authorization URL should include a scope value like:scope=ads_read
2. Fetch the User's Ad Accounts
Once you have a valid user access token with the correct permissions, call the Graph API to get their ad accounts:
GET /me/adaccounts?fields=id,name
This will return a list of ad accounts the user has access to.
3. Fetch Pixels for Each Ad Account
For each ad account ID returned in the previous step, call the adspixels endpoint to get the associated Pixels:
GET /act_{AD_ACCOUNT_ID}/adspixels?fields=id,name,code
This will give you the Pixel ID, name, and even the base Pixel code if you need it for your tracking setup.
Important Notes
- App Review: If you plan to use this with non-test users, your app will need to go through Facebook's App Review process for the
ads_readpermission. You'll need to explain exactly how you're using the Pixel data (e.g., "To set up website tracking for the user's site hosted on our platform, so they can view analytics in their own Facebook Ads account"). - Page-Associated Pixels: In some cases, users might have Pixels linked directly to a Facebook Page instead of an ad account. If you need to cover this scenario, request the
pages_read_engagementandpages_show_listpermissions, then call:GET /{PAGE_ID}/pixels?fields=id,name
Fixing Your Original Test Flow
If you want to test this with your own account, instead of adding your ad account to the app settings, just go through the OAuth flow as a user (using your own Facebook account) and grant the ads_read permission. Your app will then be able to access your ad account's Pixels without needing to pre-add the account to the app settings.
内容的提问来源于stack exchange,提问作者ayush gupta

