目前,我正在为 Apple Wallet 编写 .NET5 中的 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端口,不行。
谢谢!