how to read facebook signed_request to get user_id

后端 未结 3 1062
陌清茗
陌清茗 2021-01-19 02:25

According to Facebook - Authentication within a Canvas Page Document, they say that we will be getting a signed_request which consists a JSON object. Now they s

相关标签:
3条回答
  • 2021-01-19 03:07

    I think it failed at json_decode($json) because $json is not a valid json string, as you've mentioned in comment about print_r($_POST['signed_request']);.

    According to Facebook - Authentication within a Canvas Page Document, the signed_request parameter is encoded and, parsing the signed_request string will yield a JSON object.

    if you're using the PHP SDK, just as Abhishek said in the comment, $facebook->getSignedRequest(); will give you the decoded json.

    look here for more details on the Signed Request

    0 讨论(0)
  • 2021-01-19 03:21

    Old post I know but wanted to add a reply to Art Geigel's answer (I can't comment directly on it).

    Your code snippet is missing the line,

       $secret = "appsecret"; // Use your app secret here
    

    and the complete snippet,

    function parse_signed_request($signed_request) {
       list($encoded_sig, $payload) = explode('.', $signed_request, 2); 
    
       $secret = "appsecret"; // Use your app secret here
    
       // decode the data
       $sig = base64_url_decode($encoded_sig);
       $data = json_decode(base64_url_decode($payload), true);
    
       // confirm the signature
       $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
       if ($sig !== $expected_sig) {
          error_log('Bad Signed JSON signature!');
          return null;
       }
    
       return $data;
    }
    
    function base64_url_decode($input) {
       return base64_decode(strtr($input, '-_', '+/'));
    }
    

    To answer the original question

    To get data from the signed_request, include the functions above and...

    $data = parse_signed_request($_POST['signed_request']);
    
    echo '<pre>';
    print_r($data);
    
    0 讨论(0)
  • 2021-01-19 03:29

    If you don't want to work with the FB SDK you can use this snippet of code to get the user_id and other variables (snippet from https://developers.facebook.com/docs/facebook-login/using-login-with-games/)

    function parse_signed_request($signed_request) {
      list($encoded_sig, $payload) = explode('.', $signed_request, 2); 
    
      // decode the data
      $sig = base64_url_decode($encoded_sig);
      $data = json_decode(base64_url_decode($payload), true);
    
      // confirm the signature
      $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
      if ($sig !== $expected_sig) {
        error_log('Bad Signed JSON signature!');
        return null;
      }
    
      return $data;
    }
    
    function base64_url_decode($input) {
      return base64_decode(strtr($input, '-_', '+/'));
    }
    
    0 讨论(0)
提交回复
热议问题