drc15469 2018-03-03 12:54
浏览 22
已采纳

我想用facebook php sdk发布通知,我该怎么做?

I have a facebook app and I want to send a notification.

I have the id of the user but can't seem to get a valid access token...

I couldn't find examples that worked online and the facebook api documentation doesn't give examples.

My question boils down to this:

How do I get an access token to do this and which (working) code can I use to perform this action?

S.

  • 写回答

1条回答 默认 最新

  • douxidao3524 2018-03-03 12:54
    关注

    You need an app access token, luckily there is a page where you can get it.

    -> keep it secret i.e. don't check in in source control, it is directly linked with your app secret...

    This is code that works at the time of writing:

    replace {test-user-id} in the sample with the user id (for instance of a test user)

    <?php
    
    session_start();
    
    require_once __DIR__ . '/../vendor/autoload.php'; // change path as needed
    
    $fb = new Facebook\Facebook([
      'app_id' => '',
      'app_secret' => '',
      'default_graph_version' => 'v2.9',
      ]);
    
    $token = ''; //see rest of answer
    
    $message = 'You have people waiting to play with you, play now!';
    
    $request = $fb->request('post', '/{test-user-id}/notifications?access_token='.$token.'&template='.$message.'&href=test.html');
    
    // Send the request to Graph
    try {
      $response = $fb->getClient()->sendRequest($request);
    } catch(Facebook\Exceptions\FacebookResponseException $e) {
      // When Graph returns an error
      echo 'Graph returned an error: ' . $e->getMessage();
      exit;
    } catch(Facebook\Exceptions\FacebookSDKException $e) {
      // When validation fails or other local issues
      echo 'Facebook SDK returned an error neverthelss: ' . $e->getMessage();
      exit;
    }
    
    $graphNode = $response->getGraphNode();
    
    echo 'success: ' . $graphNode['success'] . ' error: ' . $graphNode['error'];
    
    ?>
    

    The $token is obtained from this tool (credits to this question and answer).

    The page outputs succes: 1 error: (and sends the message as a notification to the test user account).

    If you click the notification you get directed to test.html relative to your app root on your server.

    I hope it is useful to others.

    Cheers,

    S.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么