从Facebook注册JSON对象获取值

时间:2013-03-26 14:56:10

标签: php json facebook facebook-graph-api foreach

我正在使用Facebook注册来处理我正在构建的竞赛表单时遇到问题,表单提交并在使用print_r时提供以下JSON数组:

Array (
    [algorithm] => HMAC-SHA256
    [expires] => 1364313600
    [issued_at] => 1364306406
    [oauth_token] => AAAB8bFGZCv4MBAIpl7rSmqzMnJ6V6Om78oZAEvWtxlGZCMoMgiNNIWjLHv2nf7ZAQulTr8fqrwFKFnKROX4rpwbaiZACTMIsrwMZBtDI47jgZDZD
    [registration] => Array (
        [name] => Ben Franklin
        [email] => email@email.com
        [address] => 455 Hickory Rd.
        [city] => Array
            (
                [name] => Baltimore, Maryland
                [id] => 1.04052369632E+14
            )

        [gender] => male
        [birthday] => 07/12/1978
        [phone] => 5550005555
    )

    [registration_metadata] => Array (
        [fields] => [{'name':'name'},
             {'name':'email'},
             {'name':'address', 'description':'Address', 'type':'text'},
             {'name':'city', 'description':'City', 'type':'typeahead', 'categories':['city','country','state_province']},
             {'name':'gender'},
             {'name':'birthday'},
             {'name':'phone', 'description':'Phone Number', 'type':'text'}]
    )

    [user] => Array (
        [country] => us
        [locale] => en_US
    )

    [user_id] => 574207194
)

我现在的问题是我已经按照Facebook PHP的例子来阅读signed_request,因为他们应该这样做,最后是使用print_r获取上面的输出。现在我需要获得一些可以存储在数据库中的实际变量。我一直在尝试使用foreach循环来获取我在Registration数组中需要的字段,然后是其中的City数组,但为了简化我只是想获取[address]值并存储它,以下是我建议的PHP代码,在print_r命令下我添加了我在foreach循环中的尝试来获取我的值,我一直得到错误,如“致命错误:不能使用字符串偏移作为数组.... ”。任何人都有任何见解,下面是我处理提交表单的PHP文件:

<?php
define('FACEBOOK_APP_ID', 'MY_APP_ID');
define('FACEBOOK_SECRET', 'MY_SECRET_ID');

function parse_signed_request($signed_request, $secret) {
  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);

  if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
    error_log('Unknown algorithm. Expected HMAC-SHA256');
    return null;
  }

  // check sig
  $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, '-_', '+/'));
}

if ($_REQUEST) {
   $response = parse_signed_request($_REQUEST['signed_request'], 
                               FACEBOOK_SECRET);
   echo '<pre>';
   print_r ($response);
   echo '</pre>';

  foreach ($response as $r) {
    echo $r["registration"]["address"];
  }

} else {
   echo '$_REQUEST is empty';
}
?>

0 个答案:

没有答案