我正在努力了解安全获取应用程序访问令牌的正确方法,以及如何使用它向我的应用程序用户发送通知。
通过阅读Facebook的文档和其他问题,我认为应用令牌应该只在服务器端生成,所以我尝试在php脚本中包含Graph API调用来获取令牌,而不是在我的客户端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}
&client_secret={MYAPPSECRET}
</script>
"
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
我的应用程序ID和应用程序机密包含在这个php文件中,然后我试图调用Graph API以获取我的应用访问令牌,然后我尝试将响应(访问令牌)回显到我的Javascript文件/函数(它是客户端),以便它可以用于发送以下通知:
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);
}
}
);
}}
不幸的是,这不起作用,我甚至不确定这是否是一个安全的方法,因为我将访问令牌存储在客户端的一个变量中。
我真的很感谢任何人对正确方法的帮助或建议。我的代码完全不正确吗?还是只需要一些小的改变?
提前谢谢!
您不需要"获取应用访问令牌",应用令牌只是应用ID和应用秘密的组合:
$app_token = APPID . '|' . APPSECRET;
当然,只需使用服务器端即可。不要将应用令牌发送到客户端!您可以使用PHP SDK来使用通知端点,也可以自己使用cURL。