I\'m trying to send a push notification to APNs using Erlang. This is the code I came up with so far:
-module(apnstest2).
-export([connect/0]).
connect() ->
To start with, there is no need for creating a list of a single binary and then calling list_to_binary/1
on it. You can just send the binary itself.
Also, make sure the field lengths and values are appropriate according to the protocol:
TokenLength = 32 = length(Token),
Packet = <<0:8, TokenLength:16/big, Token, PayloadLength:16/big, Payload>>,
ssl:send(Socket, Packet),
Now that we have gotten this far, we will see that length(Token) is in fact 64, not 32: You forgot to convert the hex string for Token to a binary, so you are sending a 64 byte hex character string instead of 32 binary bytes.
So... making Payload a binary from the start, and making Token a numeric constant, you can do something like the following:
Payload = <<"{\"aps\":{\"alert\":\"Just testing.\",\"sound\":\"chime\", \"badge\":10}}">>,
PayloadLength = size(Payload),
Packet = <<0:8, 32:16/big,
16#195ec05a962b24954693c0b638b6216579a0d1d74b3e1c6f534c6f8fd0d50d03:256/big,
PayloadLength:16/big, Payload/binary>>,
ssl:send(Socket, Packet),
Thanks to Christian for pointing out a number of mistakes in the former revisions of this answer.
I see two mistakes:
For parsing hex to an integer and then down to binary use something like this:
Token = "dead",
TokenNum = erlang:list_to_integer(Token, 16),
TokenBin = <<TokenNum:32/integer-unit:8>>,
Build the protocol packet with something like this:
TokenBin = ...,
Payload = <<"Payload">>,
PayloadSize = byte_size(Payload),
Packet = <<0:8, 32:16, TokenBin/binary, PayloadSize:16, Payload/binary>>,
Try use a simple library epns(Erlang Push Notifications)
This library can send push notification as APNS and FCM by Erlang side. How use epns(Erlang Push Notifications) library - you can read in README.md. This liblary can used as 3-rd party in project, or you can run it locally for see how this library works:
$ git clone https://github.com/vkatsuba/epns.git
$ cd epns
$ make
Retested on Erlang 20~21