使用 PHP 向 Windows Phone 8.1 应用发送推送通知





5.00/5 (2投票s)
在本文中,我们将学习如何使用 PHP 向 Windows Phone 8.1 应用发送推送通知。
引言
在这里,我们将了解如何在 Windows 8.1 设备上接收通知。为了接收推送通知,我们需要一个客户端和一个服务器。客户端是接收通知的设备,服务器是向客户端发送通知的设备。 我们将在 Windows Phone 8.1 上创建客户端,在 PHP 中创建服务器。
客户端 (WP 8.1 应用)
创建一个新项目,例如空白 WP 8.1 应用,并赋予它你想要的名称。
首先需要将你的应用与 Windows 应用商店关联。因此,请在你的开发者帐户中注册你的应用 这里。 在应用商店注册后,在解决方案资源管理器中右键单击你的项目,然后单击“商店”->“将应用与商店关联...”。
你将看到下面的屏幕
登录后,你将看到手机号码验证屏幕。 手机号码验证后,你将获得一个已在你的开发者帐户中注册的所有应用的列表。 选择应用名称并单击“下一步”按钮。
创建通道并生成 URI。 此 URI 对于任何设备都是唯一的。 WNS 将向此 URI 发送通知。 我们可以将其称为设备令牌或设备 ID。
string notificationUrl;
var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
notificationUrl= channel.Uri.ToString();
它将由客户端应用本身生成,我们需要将此 URI 提供给服务器,因为服务器将使用此 URI 发送通知。
服务器 (PHP)
为了向 Windows Phone 8.1 设备发送推送通知,我们需要以下三样东西
- 包 SID
- 客户端密钥
- URI
你将从你的 Windows 开发者帐户中获得包 SID 和客户端密钥。 在你的开发者帐户中,转到左侧导航栏中的“服务”->“推送通知”。 然后,单击 Live Services 站点。
你将在这里获得包 SID 和客户端密钥。
URI 将由客户端应用生成,我们已经了解了这一点。
创建一个 PHP 页面,并将以下代码写入其中。
<html>
<head>
<title>Send Push Notification</title>
</head>
<body>
<?php
/* Defining a PHP Function */
function sendPushNotification() {
$token="";
$message="Test message";
$XmlToastTemplate = '<?xml version="1.0"
encoding="UTF-8"?><toast launch="">
<visual lang="en-US">
<binding template="ToastText01">
<text id="1">'.$message.'</text>
</binding>
</visual>
</toast>';
if ($token == null || $token=="")
{
$token=createToken();
}
//echo $XmlToastTemplate;
//It is the device token, it will be unique for each user
$sUrlWithToken="Uri with token";
// ************* Call API:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sUrlWithToken);
curl_setopt($ch, CURLOPT_POST, 1);// set post data to true
curl_setopt($ch, CURLOPT_POSTFIELDS,$XmlToastTemplate); // post data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'X-WNS-Type: wns/toast',
'X-WNS-RequestForStatus: true',
'Content-Type: text/xml',
'Authorization: Bearer '.$token
));
$json = curl_exec($ch);
curl_close ($ch);
echo "Notification Sent";
}
function createToken()
{
//Change Package Id and ClientSecret to the given one.
$encSid = urlencode('Package Id');
$encSecret = urlencode('Client Secret');
$sUrl ="https://login.live.com/accesstoken.srf";
$body =
"grant_type=client_credentials&client_id=".$encSid.
"&client_secret=".$encSecret."&scope=notify.windows.com";
// ************* Call API:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sUrl);
curl_setopt($ch, CURLOPT_POST, 1);// set post data to true
curl_setopt($ch, CURLOPT_POSTFIELDS,$body); // post data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($ch);
curl_close ($ch);
$obj = json_decode($json);
return $obj->{'access_token'};
}
/* Calling a PHP Function */
sendPushNotification();
?>
</body>
</html>
当你运行此页面时,页面加载时,你将在你的应用中收到通知。