Search code examples
iosparse-platformonesignalparse-cloud-code

Send Push Notification using OneSignal in parse cloud code


I pretty much copy and pasted OneSignal's doc example of what a parse cloud function looks like to just try and get a simple test push out. Here's my cloud code:

Parse.Cloud.define('followPush', function(request, response) {
send = function(request) {

var promise = new Parse.Promise();

var jsonBody = {
app_id: "XXX",
included_segments: ["All"],
contents: {en: "English Message"},
data: {foo: "bar"}
};

Parse.Cloud.httpRequest({
                        method: "POST",
                        url: "https://onesignal.com/api/v1/notifications",
                        headers: {
                        "Content-Type": "application/json;charset=utf-8",
                        "Authorization": "Basic XXX"
                        },
                        body: JSON.stringify(jsonBody)
                        }).then(function (httpResponse) {
                                promise.resolve(httpResponse)
                                },
                                function (httpResponse) {
                                promise.reject(httpResponse);
                                });

return promise;
};

exports.send = send;

});

I get a "request timeout" on my server logs and a "JSON text did not start with..." on client side. If i send a push notification from the OneSignal website, it reaches the user. I had it working with Parse but do not understand with oneSignal.


Solution

  • It looks like you were able to get in touch with the OneSignal dev team to resolve this. (I help work on OneSignal)

    For the benefit of other StackOverflow users, the solution was to change your httpRequest code to be as follows:

    Parse.Cloud.httpRequest({ 
      url: "https://onesignal.com/api/v1/notifications", 
      method: "POST", 
      headers: { 
        "Content-Type": "application/json;charset=utf-8", 
        "Authorization": "Basic XXX" 
      }, 
      body: JSON.stringify(jsonBody), 
      success: function(httpResponse) { 
        response.success("sent"); 
      }, 
      error: function(httpResponse) { 
        response.error('Failed with: ' + httpResponse.status); 
      } 
    });