Posts tagged with facebook-javascript-sdk

I'm attempting to use Meta's OAuth login for a project, however, the dialog is always a complex multi-step process. Several other sites have a simple, 1-click dialog. I noticed that whether I use the SDK or url, it ends up being the same result. Additionally, the url for the 1-click dialog is much longer and always starts with "https://www.facebook.com/privacy/consent/gdp/?params%5Bapp_id%".

1-click Dialog Multi-step Dialog

Ss there any way to get the simpler login dialog on my end, or is it up to Meta?

I tried using both the SDK and a manual login with differing login settings. I also tried adding and removing scopes as well as all the possible auth_types to no avail. I also am testing in live mode/production.

I'm integrating Facebook Business Login using the Facebook JS SDK. Despite following many tutorials and the official guide, I've encountered a persistent issue over the past few days. I believe this might be an edge case specific to my setup.

The problem

Both FB.getLoginStatus() and FB.login() call functions return below response.

{authResponse: null, status: 'unknown'}  

I'm certain I've logged into Facebook and it should show "connected" instead. The issue is that callback functions are being triggered before Facebook returns the response. For example, when FB.login() opens the login dialog, the console shows the callback response before login completion. Additionally, after completing the login, the callback function is no longer called. Here is a screenshot:

Here is the source code

(I just copy-pasted from Facebook Offical Guide)

    <!DOCTYPE html> <html> <head> <title>Facebook Login JavaScript Example</title> <meta charset="UTF-8"> </head> <body> <script>   function statusChangeCallback(response) {  // Called with the results from FB.getLoginStatus().     console.log('statusChangeCallback');     console.log(response);                   // The current login status of the person.     if (response.status === 'connected') {   // Logged into your webpage and Facebook.       testAPI();       } else {                                 // Not logged into your webpage or we are unable to tell.       console.log( 'Please log ' +         'into this webpage.');         FB.login((response) => {           console.log(response)         },{             "config_id":{{FACEBOOK_CONFIG_ID}}         })     }   }   function checkLoginState() {               // Called when a person is finished with the Login Button.     FB.getLoginStatus(function(response) {   // See the onlogin handler       statusChangeCallback(response);     });   }   window.fbAsyncInit = function() {     FB.init({       appId      : '{{FACEBOOK_APP_ID}}',       cookie     : true,                     // Enable cookies to allow the server to access the session.       xfbml      : true,                     // Parse social plugins on this webpage.       version    : 'v20.0'           // Use this Graph API version for this call.     });     FB.getLoginStatus(function(response) {   // Called after the JS SDK has been initialized.       statusChangeCallback(response);        // Returns the login status.     });   };     function testAPI() {                      // Testing Graph API after login.  See statusChangeCallback() for when this call is made.     console.log('Welcome!  Fetching your information.... ');     FB.api('/me', function(response) {       console.log('Successful login for: ' + response.name);       document.getElementById('status').innerHTML =         'Thanks for logging in, ' + response.name + '!';     });   } </script> <!-- The JS SDK Login Button --> <fb:login-button config_id="{{FACEBOOK_CONFIG_ID}}" onlogin="checkLoginState();"> </fb:login-button> <div id="status"> </div> <!-- Load the JS SDK asynchronously --> <script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_US/sdk.js"></script> </body> </html> 

My Environment

I use Facebook Business Login so I can ask my clients permission to manage their pages. I've configured User Access Token configuration and included my Config ID in both login button and in FB.login() function. My Business is verified. I'm testing this in localhost. (I have local ssl and I use HTTPS. Also I've deployed this in my live web app where i have https as well and facing the same problem). My App is in Live mode.

Below are some screenshots from my app configs. I'm trying to give lot of details as I beleive this might be specific to my app configurations.

What I've Tried

  1. I've tried both FB.login() and Facebook login Button. (with facebook login button the onlogin callback function never getting called)

  2. I've deleted ALL my cookies and files

  3. I've deployed this in Live web app

UPDATE

There is a fblo_<app_id> cookie, which my research indicates is a Facebook logout cookie, defaulting to a value of "y". When I manually delete this cookie, the status changes to "connected" (sometimes this works and sometimes not.). However, it's not feasible to ask my clients to perform this action on their end. Additionally, the callback functions are still being triggered before the login (reconnect) process is complete. So maybe there might be an issue related to cookies or sessions.

When asking adding extra permissions to the scope argument of my FB login button, those permissions aren't added to the access token.

I'm building an app (with Next.js) that let's you schedule posts to a users profile page.

The user I'm testing with has the Role of Tester in my app, so app permissions shouldn't be a problem.

This is my code:

facebook async init code

useEffect(() => {         window.fbAsyncInit = function () {             // @ts-ignore             FB.init({                 appId: process.env.NEXT_PUBLIC_FACEBOOK_APP_ID,                 cookie: true,                 xfbml: true,                 version: process.env.NEXT_PUBLIC_FACEBOOK_API_VERSION, // v20.0             });             // @ts-ignore             FB.AppEvents.logPageView();             // @ts-ignore             FB.getLoginStatus(function (response) {                 console.log('login status:', response)             });         };         (function (d, s, id) {             var js, fjs = d.getElementsByTagName(s)[0];             if (d.getElementById(id)) { return; }             js = d.createElement(s); js.id = id;             // @ts-ignore             js.src = "https://connect.facebook.net/en_US/sdk.js";             // @ts-ignore             fjs.parentNode.insertBefore(js, fjs);         }(document, 'script', 'facebook-jssdk'));     }, []); 

the login button onClick handler:

const loginWithShowListPerm = () => {         // @ts-ignore         FB.login(function (response) {             (async () => {                 console.log('login response:', response)                 if (response.status === 'connected') {                     const params: GraphApiParams = {                         accessToken: response.authResponse.accessToken,                         platformUserId: response.authResponse.userID,                     }                     await saveAccessToken(params);                     const accessTokenData = await getAccessTokenData(params);                     console.log('accessTokenData:', accessTokenData);                     // User is logged in and authorized                     // Execute your function here                 }             })();         }, { scope: 'pages_show_list' }); 

the convertToLongLivedAccessToken backend method this method is called by the server action saveAccessToken

export async function convertToLongLivedAccessToken({     userAccessToken, }: {     userAccessToken: string, }) {     try {         const response = await fetch(`https://graph.facebook.com/${process.env.NEXT_PUBLIC_FACEBOOK_API_VERSION}/oauth/access_token`, {             method: 'POST',             headers: {                 'Content-Type': 'application/json',             },             body: JSON.stringify({                 grant_type: 'fb_exchange_token',                 client_id: process.env.NEXT_PUBLIC_FACEBOOK_APP_ID,                 client_secret: process.env.FACEBOOK_APP_SECRET,                 fb_exchange_token: userAccessToken,             }),         });         const data = await response.json();         console.log('data:', data);         return data.access_token;     } catch (error) {         console.error('Error converting to Long Lived Access Token:', error);         return null;     } } 

node.js script to check token permissions:

 async function main() { try { const response = await fetch(`https://graph.facebook.com/v20.0/me/permissions?access_token=${accessToken}`);         if (!response.ok) {             throw new Error(`HTTP error! status: ${response.status}`);         }              const data = await response.json();              console.log('Data:', data);          } catch (error) {         console.error('Error fetching user permissions:', error);     } } main(); 

Even when adding { scope: 'pages_show_list' } attribute to the login button code, both the short lived and the long lived tokens return this when testing with the check permissions script:

 Data: { data: \[ { permission: 'public_profile', status: 'granted' } \] } 

as you can see, only the default granted 'public_profile' permission is included, the 'pages_show_list' is missing. I would expect there to at least be a mention of the permission, either with status 'granted' or something else.

Help would be greatly apreciated.

I'm trying to upload a video to af Facebook Page following this Graph API documentation: https://developers.facebook.com/docs/video-api/guides/publishing

I have been able to upload the video and received a video handle in response (step 2).

However, no matter what I try, when doing the final "publish" step (step 3), I get this response:

{     "error": {         "message": "There was a problem uploading your video file. Please try again with another file.",         "type": "OAuthException",         "code": 6000,         "error_data": {             "error": null         },         "error_subcode": 1363019,         "is_transient": false,         "error_user_title": "Video wasn't uploaded",         "error_user_msg": "There was a problem with uploading your video. Please wait a few minutes and try again.",         "fbtrace_id": "AMa9zbs8h3b4omv5wRSfTsf"     } } 

Things I've tried:

  • Making POST request via Facebook Javascript SDK
  • Making POST request via axios
  • Making POST request via axios via CORS proxy
  • Making POST request via the Graph API Explorer
  • Making POST request from a vercel.app host rather than localhost
  • Using both graph.facebook.com and graph-video.facebook.com
  • Posting a variety of video file types and sizes ⠀ Every time, exactly the same response (fbtrace_id changes)

Needless to say, the error message isn't giving me enough information to find the cause of the problem (and waiting a few minutes and trying again later doesn't help).

The request that is being made (via Javascript SDK) is:

curl 'https://graph.facebook.com/v20.0/<PAGE_ID>/videos?access_token=<PAGE_ACCESS_TOKEN>' \   -H 'accept: */*' \   -H 'accept-language: en-GB,en-US;q=0.9,en;q=0.8' \   -H 'content-type: application/x-www-form-urlencoded' \   -H 'origin: https://localhost:3000' \   -H 'priority: u=1, i' \   -H 'referer: https://localhost:3000/' \   -H 'sec-ch-ua: "Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"' \   -H 'sec-ch-ua-mobile: ?0' \   -H 'sec-ch-ua-platform: "macOS"' \   -H 'sec-fetch-dest: empty' \   -H 'sec-fetch-mode: cors' \   -H 'sec-fetch-site: cross-site' \   -H 'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36' \   --data-raw $'description=Victoria\'s%20nurses%20and%20midwives%20have%20voted%20down%20a%20proposed%2023%25%20pay%20rise%20over%20four%20years%2C%20citing%20uncertainty%20and%20a%20desire%20for%20better%20conditions.&fbuploader_video_file_chunk=<VERY_LONG_VIDEO_HANDLE>&method=post&pretty=0&sdk=joey&suppress_http_code=1&title=Nurses%20Reject%20Offer' 

I suspect the problem has to do with permissions and the Facebook app configuration. I tried to post just a regular Page Post and that was successful. The successful Page Post request was:

curl 'https://graph.facebook.com/v20.0/<PAGE_ID>/feed?access_token=<PAGE_ACCESS_TOKEN>' \   -H 'accept: */*' \   -H 'accept-language: en-GB,en-US;q=0.9,en;q=0.8' \   -H 'content-type: application/x-www-form-urlencoded' \   -H 'origin: https://localhost:3000' \   -H 'priority: u=1, i' \   -H 'referer: https://localhost:3000/' \   -H 'sec-ch-ua: "Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"' \   -H 'sec-ch-ua-mobile: ?0' \   -H 'sec-ch-ua-platform: "macOS"' \   -H 'sec-fetch-dest: empty' \   -H 'sec-fetch-mode: cors' \   -H 'sec-fetch-site: cross-site' \   -H 'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36' \   --data-raw 'message=Nurses%20Reject%20Offer&method=post&pretty=0&sdk=joey&suppress_http_code=1' 

Other contextual information

  • The Facebook App has not undergone App Review yet, but the User is connected to the Facebook App, so that shouldn't be a problem
  • The User has admin access to the test Page
  • “Business Verification” is complete
  • developers.facebook.com is saying we can’t apply for Access Verification because we don’t need Access Verification.
  • App Type is ‘business’ and App Mode is ‘development’
  • Based on the user access token and the page access token, the permissions are: (same for both)
    • email
    • publish_video
    • pages_show_list
    • pages_read_engagement
    • pages_read_user_content
    • pages_manage_posts
    • pages_manage_engagement
  • Screenshot of Facebook App login configuration:
    • login variation: general
    • access token: User access token
    • permissions: pages_show_list, publish_video, pages_manage_posts, email, pages_read_management, pages_manage_engagement
  • Another possible clue: After uploading the video (step 2) and receiving a video handle in response, I can't see the uploaded video anywhere. I can't see it on any Facebook page (not listed on user's personal page, the business page, as 'cross postable' content in the Creator Studio etc) and when I make a Graph API request for the user's videos, I get an empty array in response. Maybe uploaded videos remain invisible until they are published at least once? Or maybe there's a problem with the upload, despite the successful response from the HTTP request?
  • Facebook does not provide a way to communicate with them about this apart from posting to community forums (no dev support, can’t even raise bug tickets). This problem is also posted at [ Video API ] error_subcode: [...] when publishing video - Developer Community Forum - Meta for Developers, but raising here on S.O. because no response on the other one.