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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀