Tiliman’s Weblog

January 2, 2013

Google Cloud Messaging with Erlang

I have been working on Facebook matchmaking code for Android/Unity to mimic iOS Game Center like flow of match making where other player receives notification on phone. Server side is coded with Mochiweb in Erlang. Here is simple code to send GCM Notification.

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
send_gcm_msg(ApiKey, Pnstoken, Message, Game) ->
        Baseurl = "http://android.googleapis.com/gcm/send",
        ApiKey1 = string:concat("key=",ApiKey),
        %% Create Json struct
        Body = lists:flatten(mochijson:encode({struct, [{registration_ids,{array, [Pnstoken]}},
                        {data,{struct, [{message,Message},{game,Game}]}},
                        {time_to_live,3600},
                        {collapse_key,game_invite}]})),
        try httpc:request(post, {Baseurl,[{"Authorization",ApiKey1}],"application/json",Body},[],[]) of
                {ok, {{_,200,_},_,RespBody}} ->
                        {ok, mochijson:decode(RespBody)};
                {error, Reason } ->
                        {error, Reason};
                {ok, {{StatusLine,_,_},_,RespBody}} ->
                        {error, {StatusLine, RespBody}};
                BigError -> {error, BigError}
        catch
                Throw -> {error, caught, Throw}
        end.
Advertisements

1 Comment »

  1. Hw do we send “notifications” like “data” as a key, value pair. It is throwing an internal server error

    Comment by shlokspeare — April 26, 2016 @ 9:28 pm


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: