我在 Windows Phone 8.1/Windows 应用程序(通用应用程序)中使用推送通知取得了成功。我已经实现了从我们自己的 Web 服务向设备发送推送通知。
第 1 步:从 dev.windows.com >> Services >> Live Services获取Client Secret和Package SID 。稍后在 Web 服务中将需要这些。
第 2 步:在您的 Windows 应用程序中,您必须将您的应用程序与应用商店关联。为此,右键单击项目>>商店>>将应用程序与商店关联。使用您的开发帐户登录并关联您的应用程序。
第 3 步
您需要一个 Channel Uri。在 MainPage.xaml 中,添加一个 Button 和一个 Textblock 以获取您的 Channel Uri。XAML 代码如下所示:
<Page
x:Class="FinalPushNotificationTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:FinalPushNotificationTest"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Text="Push Notification" Margin="20,48,10,0" Style="{StaticResource HeaderTextBlockStyle}" TextWrapping="Wrap" />
<ScrollViewer Grid.Row="1" Margin="20,10,10,0">
<StackPanel x:Name="resultsPanel">
<Button x:Name="PushChannelBtn" Content="Get Channel Uri" Click="PushChannelBtn_Click" />
<ProgressBar x:Name="ChannelProgress" IsIndeterminate="False" Visibility="Collapsed" />
<TextBlock x:Name="ChannelText" FontSize="22" />
</StackPanel>
</ScrollViewer>
</Grid>
第 4 步:在 MainPage.xaml.cs 页面中,添加以下代码片段,即按钮单击事件。当您运行您的应用程序时,您将在控制台窗口中获得Channel Uri 。记下这个 Channel Uri,你需要在 Web Service 中使用它。
private async void PushChannelBtn_Click(object sender, RoutedEventArgs e)
{
var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
ChannelText.Text = channel.Uri.ToString();
Debug.WriteLine(channel.Uri);
}
第 5 步:
现在您需要一个 Web 服务来向您的设备发送推送通知。为此,在解决方案资源管理器中右键单击您的项目。添加 >> 新项目 >> Visual C# >> Web >> ASP.NET Web 应用程序。单击确定,在模板上选择空。之后在您的 Web 应用程序中添加一个新的Web 表单。将其命名为SendToast。
第 6 步:
现在在SendToast.aspx.cs中,您需要实现方法和函数,以使用 Package SID、Client Secret 和 Channel Uri获取Access Token 。在相应位置添加您的 Package SID、Cleint Secret 和 Channel Uriin。完整的代码类似于以下代码片段:
using Microsoft.ServiceBus.Notifications;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace SendToast
{
public partial class SendToast : System.Web.UI.Page
{
private string sid = "Your Package SID";
private string secret = "Your Client Secret";
private string accessToken = "";
[DataContract]
public class OAuthToken
{
[DataMember(Name = "access_token")]
public string AccessToken { get; set; }
[DataMember(Name = "token_type")]
public string TokenType { get; set; }
}
OAuthToken GetOAuthTokenFromJson(string jsonString)
{
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
{
var ser = new DataContractJsonSerializer(typeof(OAuthToken));
var oAuthToken = (OAuthToken)ser.ReadObject(ms);
return oAuthToken;
}
}
public void getAccessToken()
{
var urlEncodedSid = HttpUtility.UrlEncode(String.Format("{0}", this.sid));
var urlEncodedSecret = HttpUtility.UrlEncode(this.secret);
var body =
String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=notify.windows.com", urlEncodedSid, urlEncodedSecret);
var client = new WebClient();
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
string response = client.UploadString("https://login.live.com/accesstoken.srf", body);
var oAuthToken = GetOAuthTokenFromJson(response);
this.accessToken = oAuthToken.AccessToken;
}
protected string PostToCloud(string uri, string xml, string type = "wns/toast")
{
try
{
if (accessToken == "")
{
getAccessToken();
}
byte[] contentInBytes = Encoding.UTF8.GetBytes(xml);
WebRequest webRequest = HttpWebRequest.Create(uri);
HttpWebRequest request = webRequest as HttpWebRequest;
webRequest.Method = "POST";
webRequest.Headers.Add("X-WNS-Type", type);
webRequest.Headers.Add("Authorization", String.Format("Bearer {0}", accessToken));
Stream requestStream = webRequest.GetRequestStream();
requestStream.Write(contentInBytes, 0, contentInBytes.Length);
requestStream.Close();
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
return webResponse.StatusCode.ToString();
}
catch (WebException webException)
{
string exceptionDetails = webException.Response.Headers["WWW-Authenticate"];
if ((exceptionDetails != null) && exceptionDetails.Contains("Token expired"))
{
getAccessToken();
return PostToCloud(uri, xml, type);
}
else
{
return "EXCEPTION: " + webException.Message;
}
}
catch (Exception ex)
{
return "EXCEPTION: " + ex.Message;
}
}
protected void Page_Load(object sender, EventArgs e)
{
string channelUri = "Your Channel Uri";
if (Application["channelUri"] != null)
{
Application["channelUri"] = channelUri;
}
else
{
Application.Add("channelUri", channelUri);
}
if (Application["channelUri"] != null)
{
string aStrReq = Application["channelUri"] as string;
string toast1 = "<?xml version=\"1.0\" encoding=\"utf-8\"?> ";
string toast2 = @"<toast>
<visual>
<binding template=""ToastText01"">
<text id=""1"">Hello Push Notification!!</text>
</binding>
</visual>
</toast>";
string xml = toast1 + toast2;
Response.Write("Result: " + PostToCloud(aStrReq, xml));
}
else
{
Response.Write("Application 'channelUri=' has not been set yet");
}
Response.End();
}
}
}
运行您的 Web 应用程序,如果它成功发送推送通知,您将收到Result OK响应。
如果您需要工作示例项目,请告诉我。希望这可以帮助。谢谢!