Как отправить сертификат pu sh в APNS при вызове их API? - PullRequest
0 голосов
/ 10 марта 2020

застрял при отправке уведомления pu sh с использованием сертификата apns pu sh из моего серверного приложения (Spring Boot Application). Apple обсудила здесь о том, как мы можем отправить pu sh с сертификатом, но нет технических подробностей о связи TLS (особенно о том, как я могу отправить свой сертификат pu sh в APNS и продолжить Вызовы API).

У кого-нибудь есть ссылки или статьи?

1 Ответ

1 голос
/ 20 марта 2020

Поскольку вы упомянули о своей работе над приложением Spring Boot, я предполагаю, что вы используете Java и Maven.

Наши серверные части также написаны на Java, и я недавно обновил наш код уведомления pu sh, внедрив Pushy . намного проще использовать библиотеку, которая проверена в бою и регулярно обновляется, чем писать свою собственную. Я использую pushy для отправки около 100k pu sh уведомлений в день на довольно слабый сервер, и у меня никогда не было с этим проблем.

Это было довольно просто реализовать. Их README очень полезен, но в вашем файле pom.xml добавлена ​​краткая зависимость:

<dependency>
    <groupId>com.eatthepath</groupId>
    <artifactId>pushy</artifactId>
    <version>0.13.11</version>
</dependency>  

Вот простой пример для вашего случая использования украденного кода из README , я добавил комментарий, хотя:

// Add these lines as class properties  

// This creates the object that handles the sending of the push notifications.
// Use ApnsClientBuilder.PRODUCTION_APNS_HOST to send pushes to App Store apps
final ApnsClient apnsClient = new ApnsClientBuilder()
        .setApnsServer(ApnsClientBuilder.DEVELOPMENT_APNS_HOST)
        .setClientCredentials(new File("/path/to/certificate.p12"), "p12-file-password")
        .build();  

// The push notification
final SimpleApnsPushNotification pushNotification;  

// In some method:  

// Creating the object that builds the APNs payload
final ApnsPayloadBuilder payloadBuilder = new ApnsPayloadBuilder();  

// setting the text of the push
payloadBuilder.setAlertBody("Example!");  

// Builds the anps payload for the push notification
final String payload = payloadBuilder.build();  

// The push token of the device you're sending the push to
final String token = TokenUtil.sanitizeTokenString("<efc7492 bdbd8209>");  

// Creating the push notification object using the push token, your app's bundle ID, and the APNs payload
pushNotification = new SimpleApnsPushNotification(token, "com.example.myApp", payload);  

try {
    // Asking the APNs client to send the notification 
    // and creating the future that will return the status 
    // of the push after it's sent.  
    // (It's a long line, sorry)
    final PushNotificationFuture<SimpleApnsPushNotification, PushNotificationResponse<SimpleApnsPushNotification>> sendNotificationFuture = apnsClient.sendNotification(pushNotification);  

    // getting the response from APNs 
    final PushNotificationResponse<SimpleApnsPushNotification> pushNotificationResponse = sendNotificationFuture.get();
    if (pushNotificationResponse.isAccepted()) {
        System.out.println("Push notification accepted by APNs gateway.");
    } else {
        System.out.println("Notification rejected by the APNs gateway: " +
                pushNotificationResponse.getRejectionReason());

        if (pushNotificationResponse.getTokenInvalidationTimestamp() != null) {
            System.out.println("\t…and the token is invalid as of " +
                pushNotificationResponse.getTokenInvalidationTimestamp());
        }
    }
} catch (final ExecutionException e) {
    System.err.println("Failed to send push notification.");
    e.printStackTrace();
}
...