Posts tagged with facebook-graph-api

If I make this call to get campaign data from the Graph API:

const url = `https://graph.facebook.com/v19.0/${account}/insights?time_increment=30&time_range={since:'2024-01-01',until:'2024-01-30'}&level=campaign&fields=campaign_id,campaign_name,frequency,spend,reach,impressions,objective,optimization_goal,clicks,actions&action_breakdowns=action_type&access_token=${token}`;  

I get 219,189 as the total reach. However, if I make the same call, changing only time_increment=7

const url = `https://graph.facebook.com/v19.0/${account}/insights?time_increment=7&time_range={since:'2024-01-01',until:'2024-01-30'}&level=campaign&fields=campaign_id,campaign_name,frequency,spend,reach,impressions,objective,optimization_goal,clicks,actions&action_breakdowns=action_type&access_token=${token}`; 

I get 287,141 as the total reach. If, finally, I change time_increment=1

const url = `https://graph.facebook.com/v19.0/${account}/insights?time_increment=1&time_range={since:'2024-01-01',until:'2024-01-30'}&level=campaign&fields=campaign_id,campaign_name,frequency,spend,reach,impressions,objective,optimization_goal,clicks,actions&action_breakdowns=action_type&access_token=${token}`;      

I get 391,900 as total reach. As we can see, these are very inconsistent figures. What could be the cause of this Thanks in advance!

Technical detail: I'm calling the data via the GET REST API method >> const data = await fetch(url). I'm not using an SDK.

I expect to recieve the same reach figure, independently of the time_increment parameter.

I want to create a catalog programmatically, without using commerce manager. I am using this end point but I keep getting this error message": "Unsupported post request. Object with ID does not exist, cannot be loaded due to missing permissionss.. These are my permissions: catalog_management, ads_management, business_management, whatsapp_business_management, commerce_account_read_settings, commerce_account_manage_orders, commerce_account_read_orders, whatsapp_business_messaging and I can see my owned catalogs by using this same business id but cannot create one. Am I missing something here?

I am integrating the WhatsApp Business API into my website, and everything works fine during the creation of a template. However, I am encountering an issue when updating a carousel template that contains media (image) in the header.

**Here’s the data I provide during template creation, and it works perfectly: **

{     "category": "MARKETING",     "components": [         {             "type": "BODY",             "text": "Enter the text for your message in the language that you've selected."         },         {             "type": "HEADER",             "format": "IMAGE",             "example": {                 "header_handle": [                     "https://scontent.whatsapp.net/v/t61.29466-34/455307745_840177258275973_4917068164528515056_n.jpg?ccb=1-7&_nc_sid=8b1bef&_nc_ohc=JhgXpTB6hb8Q7kNvgGo4C8z&_nc_ht=scontent.whatsapp.net&edm=AH51TzQEAAAA&_nc_gid=AYrC8T5SS1pa7iuvimhJfWi&oh=01_Q5AaIDQYeMKQIW57cK89ejtgUrwADCGDyq30TZQusIPOCDmo&oe=672C6BF5"                 ]             }         }     ] } 

However, when I try to update a carousel template with similar image data, I receive the following error:

This carousel template contains a card (index=0) with an invalid media sample.

Here’s the data I send during the update, which throws the error:

{     "category": "MARKETING",     "components": [         {             "type": "BODY",             "text": "12324"         },         {             "type": "CAROUSEL",             "cards": [                 {                     "components": [                         {                             "type": "HEADER",                             "format": "IMAGE",                             "example": {                                 "header_handle": [                                     "https://scontent.whatsapp.net/v/t61.29466-34/421261359_838328285127784_2325180770850864310_n.jpg?ccb=1-7&_nc_sid=a80384&_nc_ohc=CvDs5MWLqggQ7kNvgEuowZS&_nc_ht=scontent.whatsapp.net&edm=AH51TzQEAAAA&_nc_gid=AThnla93YjSTDzg4e3-2eDa&oh=01_Q5AaID-Ozb7JEZ-dNOAYQlxmks79b0nfTElne8ZqRD14ZtFV&oe=672C57BB"                                 ]                             }                         },                         {                             "type": "BODY",                             "text": "234525"                         },                         {                             "type": "BUTTONS",                             "buttons": [                                 {                                     "type": "QUICK_REPLY",                                     "text": "2452"                                 }                             ]                         }                     ]                 }             ]         }     ] } 

What I've Tried:

  • The image URL is valid and works fine for non-carousel templates.
  • The URL is provided by Meta after uploading the media.
  • I suspect the issue might be related to how the API validates media for carousel components.

Question:

Why does the same image URL work for a regular template but result in an "invalid media sample" error for a carousel template? Does the WhatsApp API require a media ID for carousel updates, even if the URL is valid? How should I handle image media in carousel templates to avoid this error?

Any insights or suggestions are appreciated. Thanks in advance!

I'm creating an automation flow with puppeteer to log in to Facebook and get the User Access Token. The code is a NodeJS code and pretty simple for now:

require("dotenv").config(); const { tagmanager } = require("googleapis/build/src/apis/tagmanager"); const puppeteer = require("puppeteer"); (async () => {   // Lança o navegador com a UI visível para que possamos acompanhar o processo   const browser = await puppeteer.launch({ headless: false });   const page = await browser.newPage();   // Define a URL para o fluxo de login do Facebook   const facebookLoginURL = `https://www.facebook.com/v16.0/dialog/oauth?client_id=${process.env.FB_APP_ID}&redirect_uri=${process.env.FB_REDIRECT_URI}&scope=email,public_profile&response_type=code`;   // Vai para a página de login do Facebook   await page.goto(facebookLoginURL);   // Espera o span com o texto específico "Permitir todos os cookies"   await page.waitForFunction(() => {     const elements = Array.from(document.querySelectorAll("span"));     // Verifica se algum elemento contém o texto "Permitir todos os cookies"     const targetElement = elements.find(       (element) => element.textContent.trim() === "Permitir todos os cookies"     );     // Se o elemento for encontrado, retorna true para sair do loop     if (targetElement) {       return true;     }     // Continua o loop se não encontrar o elemento     return false;   });   // Encontra e clica diretamente com page.click()   await page.evaluate(() => {     const elements = Array.from(document.querySelectorAll("span"));     // Verifica se algum elemento contém o texto "Permitir todos os cookies"     const targetElement = elements.find(       (element) => element.textContent.trim() === "Permitir todos os cookies"     );     if (targetElement) {       targetElement.setAttribute("id", "cookie-button"); // Atribui um ID temporário para garantir o seletor     }   });   await page.click("#cookie-button"); // Usa o seletor id para clicar diretamente   // Espera que o campo de email esteja disponível e preenche com o seu usuário de teste   await page.waitForSelector("#email");   await page.type("#email", process.env.FB_TEST_USER_EMAIL);   // Preenche a senha com a senha do usuário de teste   await page.type("#pass", process.env.FB_TEST_USER_PASSWORD);   // Clica no botão de login   await page.click('button[name="login"]');   // Espera o redirecionamento para a URL de callback   await page.waitForNavigation();   // Obtém a URL atual (que deve conter o código de autenticação)   const redirectedUrl = page.url();   console.log("Redirected URL:", redirectedUrl);   //here we need to handle 2FA   //...   // Extraia o código da URL de redirecionamento   const urlParams = new URLSearchParams(redirectedUrl.split("?")[1]);   const authCode = urlParams.get("code");   console.log(`Auth Code: ${authCode}`);   await browser.close(); })(); 

The puppeter code above comprises the following steps:

  1. Open Facebook login page (OK)

  2. Log in with user and password (OK)

  3. Enter 2FA code (not OK)

  4. Get User Access Token (not OK because of 3)

I'm having trouble with step 3, because I don't know how to get the code automatically, i.e. without having to enter it manually. Any solutions?

2FA is enabled in Meta Business Manager and I normally receive this code by SMS or via the Microsoft Authenticator app. I could perhaps disable 2FA for the user in question in the Meta Business Manager, but that's something I wouldn't want to do, as it reduces credibility on the Meta side, which could block the user.

So I'd like to "hear" from you about possible ways of dealing with this. Thanks in advance!

I want to handle with 2FA by using puppeteer to login on Facebook with a normal user account.

This is my first time trying to do react-native bridge. Problem is it always says it couldnt find the dependency, irrespective of my integration, I should be able to download the dependency right? I am trying to bridge: https://developer.imepay.com.np/#/andriod-sdk

I am not being able to implement the dependecy:

implementation 'com.swifttechnology.imepaysdk:payment-service:4.0.1

In my main/java/imepayintegration: ImepayModule.java:

package com.reactnativeimepay; import androidx.annotation.NonNull; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import java.util.Map; import java.util.HashMap; import com.swifttechnology.imepaysdk.IMEPayment; import com.swifttechnology.imepaysdk.IMEPaymentCallback; import com.swifttechnology.imepaysdk.ENVIRONMENT; public class ImepayModule extends ReactContextBaseJavaModule {     private final ReactApplicationContext reactContext;     public ImepayModule(ReactApplicationContext reactContext) {         super(reactContext);         this.reactContext = reactContext;     }     @Override     public String getName() {         return "ImepayModule";     }     @ReactMethod     public void performPayment(String merchantCode, String merchantName, String module,                                String username, String password, String referenceValue,                                String amount, String merchantTransactionRecordingUrl,                                Promise promise) {         IMEPayment imePayment = new IMEPayment(reactContext, ENVIRONMENT.TEST);         imePayment.performPayment(merchantCode,                 merchantName,                 merchantTransactionRecordingUrl,                 amount,                 referenceValue,                 module,                 username,                 password,                 new IMEPaymentCallback() {                     @Override                     public void onSuccess(int responseCode, String responseDescription,                                           String transactionId, String msisdn,                                           String amount, String refId) {                         promise.resolve("Payment successful");                     }                     @Override                     public void onError(int responseCode, String responseDescription) {                         promise.reject("ERROR", responseDescription);                     }                 });     } } 

ImepayPackage.java:

package com.reactnativeimepay; import java.util.Arrays; import java.util.Collections; import java.util.List; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; public class ImepayPackage implements ReactPackage {     @Override     public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {         return Arrays.<NativeModule>asList(new ImepayModule(reactContext));     }     @Override     public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {         return Collections.emptyList();     } }