我正在努力寻找正确的方法来安全地获取应用访问令牌,以及如何使用它向我的应用的用户发送通知。
通过阅读Facebook的文档以及此处的其他问题,我认为应用程序令牌应仅在服务器端生成,因此我试图将Graph API调用包含在php脚本中以获取令牌,而不是将其包含在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}
&client_secret={MYAPPSECRET}
</script>
"
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
我在此php文件中包含我的App ID和App Secret,然后尝试调用Graph API以获取我的App访问令牌,然后尝试回显响应(访问令牌)到我的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。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句