如何解决.NET5 向 Apple 设备发送推送通知
目前我正在 .NET5 中为 Apple Wallet 编写 REST 服务。现在一切正常,注册,注销,手动更新卡。问题是推送通知,我知道有很多代码内容,如何实现 .NET Apple 推送通知服务,但对我来说没有任何作用。我读到,我必须使用 Pass Type ID 证书和推送令牌,这是在 Apple 设备上注册新钱包卡时获得的。这是我的推送通知代码
[HttpGet]
[Route("passes/{passtypeIdentifier}/{serialNumber}/sendpushnotification")]
public async Task<IActionResult> SendPushNotificationToAppleAsync(string passtypeIdentifier,string serialNumber)
{
var devices = await _context.GetApplePassDevicesAsync(serialNumber,passtypeIdentifier).ConfigureAwait(false);
if (!devices.Any()) {
return NotFound();
}
try {
foreach (var device in devices) {
await SendEmptyApplePushNotificationAsync(device.PushToken).ConfigureAwait(false);
await _context.SaveApplePushNotificationAsync(device.DeviceLibraryIdentifier,device.PushToken).ConfigureAwait(false);
}
return Ok();
} catch (Exception ex) {
_logger.LogError($"SendPushNotification error: [{ex.Message}]");
return NotFound();
}
}
private async Task SendEmptyApplePushNotificationAsync(string pushToken)
{
_logger.LogDebug("Trying to send push notification.");
const string server = "api.sandBox.push.apple.com"; // Develop
using var tcpClient = new TcpClient(server,443);
await using var sslStream = new SslStream(
tcpClient.GetStream(),false,ValidateServerCertificate,null);
try {
var certs = new X509Certificate2Collection();
X509Certificate cert = await GetAppleServerCertificateAsync().ConfigureAwait(false);
certs.Add(cert);
await sslStream.AuthenticateAsClientAsync(server,certs,SslProtocols.Tls12,true).ConfigureAwait(false);
} catch (AuthenticationException exp) {
throw new AuthenticationException(exp.Message);
} catch (IOException exp) {
throw new IOException(exp.Message);
}
var memoryStream = new MemoryStream();
var writer = new BinaryWriter(memoryStream);
writer.Write((byte) 0);
writer.Write((byte) 0);
writer.Write((byte) 32);
writer.Write(HexStringToByteArray(pushToken.toupper()));
var payload = new JObject { new JProperty("aps") };
var json = JsonConvert.SerializeObject(payload);
writer.Write((byte) 0);
writer.Write((byte) json.Length);
var b1 = Encoding.UTF8.GetBytes(json);
writer.Write(b1);
writer.Flush();
var array = memoryStream.ToArray();
await sslStream.WriteAsync(array.AsMemory()).ConfigureAwait(false);
await sslStream.FlushAsync().ConfigureAwait(false);
}
private static byte[] HexStringToByteArray(string hex)
{
return Enumerable.Range(0,hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x,2),16))
.ToArray();
}
有没有人给我提示,怎么了?我也测试了2197端口,不行。
谢谢!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。