如何使用 PHP 和 Javascript 安全地获取和使用 Facebook 应用访问令牌来发送通知

How to securely get & use Facebook App Access Token to send Notifications using PHP & Javascript

我正在努力了解安全获取应用访问令牌的正确方法以及如何使用它向我的应用用户发送通知。

通过阅读 Facebook 的文档和此处的其他问题,我认为应用程序令牌应该只在服务器端生成,所以我试图在内部包含 Graph API 调用以获取令牌php 脚本,而不是在我的客户端 Javascript 代码中。这是我为实现此目的而编写的 php 脚本:

getapptoken.php:

<?php
$servername = "MYSERVERNAME";
$username = "MYUSERNAME";
$password = "MYPASSWORD";
$dbname = "MYDBNAME";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

echo "
<script type=\"text/javascript\">
    GET /oauth/access_token?
        client_id={MYAPPID}
        &amp;client_secret={MYAPPSECRET}
</script>
"
    }

catch(PDOException $e)
{
    echo "Error: " . $e->getMessage();
}
$conn = null;
?>  

我的 App ID 和 App Secret 包含在这个 php 文件中,然后我尝试调用 Graph API 来获取我的 App 访问令牌,然后我我正在尝试将响应(访问令牌)回显到我的 Javascript file/function(客户端),以便它可用于发送以下通知:

 function deliverNotifications(){

    // Using AJAX to get the apptoken as the response from getapptoken.php
    // This response is then stored in the variable named "apptoken"
    $.ajax({
            url: 'scripts/getapptoken.php',
            type: "POST",
            success: function(response){
                if (response.error) {
                    console.log('Error: ' + response.error.message);
                }
                else {

                var apptoken = response;

    //Defining the Array of IDs to send notifications to
    var myArray = [45563562722445, 83724562462, 245622722725, 367345634562];

    //Iterating through each ID and sending a notification to each one
    for (var i = 0; i < myArray.length; i++) { 

        FB.api( 
       "/"+myArray[i]+"/notifications",
        "POST",
       {
            "template": "This is a test notification!",
// Trying to use the variable named "apptoken" here to include the required app token
            "access_token": ""+apptoken+""
        },
        function (response) {
          if (response && !response.error) {
              console.log("notification should be sent.");
          } else {
          console.log(response);
             }
          }
         );             
        }}

不幸的是,这不起作用,我什至不确定这是否是一种安全的使用方法,因为我将访问令牌存储在客户端的一个变量中。

我非常感谢任何人提供有关正确执行此操作的帮助或建议。我的代码完全不正确吗?还是只需要一些小改动?

提前致谢!

您不需要"get an App Access Token",App Token 只是 App ID 和 App Secret 的组合:

$app_token = APPID . '|' . APPSECRET;

当然,只使用那个服务器端。不要将 App Token 发送给客户端!您可以使用 PHP SDK 来使用通知端点,也可以自己使用 cURL。