How to send a push notification using Erlang?

I see two mistakes:

  • Token should be passed in binary and not in hex ascii.
  • You can't use the binary syntax to turn lists into binaries.

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>>,

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.


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