{"metadata":{"image":[],"title":"","description":""},"api":{"url":"","auth":"required","params":[],"results":{"codes":[]},"settings":""},"next":{"description":"","pages":[]},"title":"Implementação","type":"basic","slug":"codigo-fonte-phonegap-cordova","excerpt":"","body":"<p style=\"margin-top:-20px;margin-bottom:-18px;\">O código de manipulação dos eventos de **PushNotification** deverá ser incluído dentro da função **onDeviceReady**. De forma geral, dois eventos serão tratados:\n<ul style=\"margin-bottom:-38px;\"> \n<li style=\"margin-bottom:-18px;\"><code>registration</code> &ndash; registro do dispositivo no provedor GCM (Google) ou APNS (Apple).</li>\n<li style=\"margin-bottom:-18px;\"><code>notification</code> &ndash; apresentação da notificação quando esta for recebida pelo dispositivo.</li>\n</ul>\n</p>\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var app = {\\n  onDeviceReady: function () {\\n\\t... // sua implementação\\n  },\\n};\\napp.initialize();\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n<p style=\"margin-top:-12px;margin-bottom:-12px;\">**1.** Inicialização das propriedades de sua aplicação, onde:\n<ul style=\"margin-bottom:-75px;\"> \n<li style=\"margin-bottom:-18px;\"><code>app_token</code> &ndash; é o código do seu app obtido na plataforma da Inngage.</li>\n<li style=\"margin-bottom:-18px;\"><code>senderID</code> &ndash; é o identificador do seu projeto no Google Developers Console.</li>\n<li style=\"margin-bottom:20px;\"><code>icon</code> &ndash; é o nome do ícone disponibilizado no diretório drawables do Android.</li>\n</ul>\n</p>\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var app_token = \\\"50a8affe879ee54b1fe67d2638672a4f\\\";\\nvar server = \\\"https://api.inngage.com.br/v1\\\";\\nvar jsonData = \\\"\\\";\\n\\nvar push = PushNotification.init({\\n\\\"android\\\": {\\n  \\\"senderID\\\": \\\"123456789\\\",\\n  \\\"icon\\\": \\\"icon\\\",\\n  \\\"iconColor\\\": \\\"white\\\"\\n},\\n\\\"ios\\\": { \\n  \\\"alert\\\": \\\"true\\\", \\n  \\\"badge\\\": \\\"true\\\", \\n  \\\"sound\\\": \\\"true\\\"\\n }, \\n \\\"windows\\\": {}\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n<p style=\"margin-top:-12px;margin-bottom:-12px;\">**2.** Registro do dispositivo nos provedores (GCM ou APNS) para o recebimento de push notification.\n</p>\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"push.on('registration', function(data) {\\n\\n\\tnavigator.geolocation.getCurrentPosition(function success(position) {\\n\\n  \\tvar latitude = position.coords.latitude;\\n    var longitude = position.coords.longitude;\\n    jsonData = JSON.stringify({\\n    \\t\\\"registerGeolocationRequest\\\": {\\n      \\t\\\"app_token\\\": app_token,\\n        \\\"uuid\\\": device.uuid,\\n        \\\"lat\\\": latitude,\\n        \\\"lon\\\": longitude\\n    \\t}\\n    });\\n    console.log(\\\"Sending location data to server: \\\" + jsonData);\\n    $.post(server + \\\"/geolocation/\\\", jsonData)\\n    \\t.done(function(response) {\\n      \\tconsole.log(\\\"Server response: \\\" + JSON.stringify(response));\\n    \\t})\\n      .fail(function() {\\n       console.log(\\\"A communication error occurred while sending data to the server (1401).\\\");\\n      });\\n    }, function error(error) {\\n        console.log(\\\"An error occurred while obtaining the user location (1402).\\\");\\n    });\\n  \\tcordova.getAppVersion(function(version) {\\n\\n    \\tjsonData = JSON.stringify({\\n            \\\"registerSubscriberRequest\\\": {\\n                \\\"identifier\\\": device.uuid,\\n                \\\"registration\\\": data.registrationId,\\n                \\\"platform\\\": device.platform.toLowerCase(),\\n                \\\"sdk\\\": 3,\\n                \\\"app_token\\\": app_token,\\n                \\\"device_model\\\": device.model,\\n                \\\"device_manufacturer\\\": device.manufacturer,\\n                \\\"os_language\\\": navigator.language,\\n                \\\"os_version\\\": device.cordova,\\n                \\\"app_version\\\": version,\\n                \\\"uuid\\\": device.uuid\\n            }\\n\\t\\t\\t});\\n      console.log(\\\"Sending data to server: \\\" + jsonData);\\n      $.post(server + \\\"/subscription/\\\", jsonData)\\n \\t     .done(function(response) {\\n  \\t    \\tconsole.log(\\\"Server response: \\\" + JSON.stringify(response));\\n      \\t})\\n       .fail(function() {\\n       \\t\\tconsole.log(\\\"A communication error occurred while sending data to the server (1403).\\\");\\n        });\\n    });\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n<p style=\"margin-top:-12px;margin-bottom:-12px;\">**3.** Manipulação do evento de recebimento de Pushes. Toda vez que uma nova notificação for recebida, este evento será disparado.\n</p>\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"push.on('notification', function (data) {\\n\\tconsole.log(\\\"Notification received :\\\" + JSON.stringify(data));\\n  jsonData = JSON.stringify({\\n\\t  \\\"notificationRequest\\\": {\\n    \\\"id\\\": data.additionalData.id,\\n    \\\"app_token\\\": app_token\\n    }\\n  });\\n  console.log(\\\"Sending callback to server: \\\" + jsonData);\\n  $.post(server + \\\"/notification/\\\", jsonData)\\n\\t .done(function (response) {\\n    \\tconsole.log(\\\"Server response: \\\" + JSON.stringify(response));\\n   })\\n   .fail(function () {\\n   \\t\\tconsole.log(\\\"A communication error occurred while sending data to the server (1404).\\\");\\n   });\\n\\tnavigator.notification.alert(\\n    data.body,\\n  \\tfunction () {},\\n    data.title,\\n    \\\"Ok\\\"\\n    );\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"info\",\n  \"title\": \"Recebendo Dados Adicionais\",\n  \"body\": \"Para receber dados adicionais enviados através da API de envio de mensagens, você deverá utilizar o objeto **inngage_data[0].nome_variavel**. Veremos abaixo um exemplo de utilização dos dados adicionais recebidos na mensagem.\"\n}\n[/block]\nDados adicionais (**additional_data**) enviados na mensagem:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{\\n\\t\\\"sendPushRequest\\\": {\\n\\t\\t\\\"title\\\": \\\"Meu App\\\",\\n\\t\\t\\\"message\\\": \\\"Mensagem Urgente\\\",\\n\\t\\t\\\"app_token\\\": \\\"e605c02ac034dc676465d13e5663d1c41\\\",\\n\\t\\t\\\"identifier\\\": \\\"49556274634\\\",\\n\\t\\t\\\"additional_data\\\": {\\n\\t\\t\\t\\\"acao\\\": \\\"adesao_fatura_email\\\"\\n\\t\\t}\\n\\t}\\n}\",\n      \"language\": \"json\"\n    }\n  ]\n}\n[/block]\nA seguinte mensagem será recebida pelo dispositivo:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{\\n\\t\\\"title\\\": \\\"Meu App\\\",\\n\\t\\\"message\\\": \\\"Mensagem Urgente\\\",\\n\\t\\\"additionalData\\\": {\\n\\t\\t\\\"id\\\": \\\"133945\\\",\\n\\t\\t\\\"inngage_data\\\": [{\\n\\t\\t\\t\\\"acao\\\": \\\"adesao_fatura_email\\\"\\n\\t\\t}],\\n\\t\\t\\\"google.message_id\\\": \\\"0:1487196990535718%7a9e9be3f9fd7ecd\\\",\\n\\t\\t\\\"coldstart\\\": false,\\n\\t\\t\\\"collapse_key\\\": \\\"do_not_collapse\\\",\\n\\t\\t\\\"foreground\\\": true\\n\\t}\\n}\",\n      \"language\": \"json\"\n    }\n  ]\n}\n[/block]\nPara recuperar o objeto **acao** neste exemplo:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"data.additionalData.inngage_data[0].acao\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]","updates":["5c33a37219dd9600d529cbdb"],"order":2,"isReference":false,"hidden":false,"sync_unique":"","link_url":"","link_external":false,"_id":"572598f892467217005e3807","project":"57240e292887bb0e00bb9d93","user":"57240d9f110e570e00486ca0","githubsync":"","__v":67,"createdAt":"2016-05-01T05:49:44.798Z","version":{"version":"1.0","version_clean":"1.0.0","codename":"","is_stable":true,"is_beta":false,"is_hidden":false,"is_deprecated":false,"categories":["57240e292887bb0e00bb9d97","57241b7deae5090e00ee6249","57241c06eae5090e00ee624a","57242abb2ad0bc170012279b","5734d18c7b9859320047f4b1","57688cc71f818b0e00695efb","577ead2ca74eb40e00d97bca","57b66af649a12a0e007b461b","597e5f8f13505b0014251a79","59964eb2f824b4000f961fbe","5a15ab12f2643f001ee8737c","5ab1151799750500797334e0","5c597e8b0abe110014bf1a11","5e395a05470bc3002d78d886","5e42a9647515f300509a594d","5f5e716dcc85f9004a4fa193","5f6dd615c624d800180bd237","5f984feb8aed05003a0032dc","60ac0e9c4c04970016613c6c"],"_id":"57240e292887bb0e00bb9d96","createdAt":"2016-04-30T01:45:13.341Z","project":"57240e292887bb0e00bb9d93","releaseDate":"2016-04-30T01:45:13.341Z","__v":19},"category":{"sync":{"isSync":false,"url":""},"pages":[],"title":"Phonegap / Cordova","slug":"phonegapcordova","order":4,"from_sync":false,"reference":false,"_id":"57242abb2ad0bc170012279b","project":"57240e292887bb0e00bb9d93","version":"57240e292887bb0e00bb9d96","__v":0,"createdAt":"2016-04-30T03:47:07.962Z"},"parentDoc":null}
<p style="margin-top:-20px;margin-bottom:-18px;">O código de manipulação dos eventos de **PushNotification** deverá ser incluído dentro da função **onDeviceReady**. De forma geral, dois eventos serão tratados: <ul style="margin-bottom:-38px;"> <li style="margin-bottom:-18px;"><code>registration</code> &ndash; registro do dispositivo no provedor GCM (Google) ou APNS (Apple).</li> <li style="margin-bottom:-18px;"><code>notification</code> &ndash; apresentação da notificação quando esta for recebida pelo dispositivo.</li> </ul> </p> [block:code] { "codes": [ { "code": "var app = {\n onDeviceReady: function () {\n\t... // sua implementação\n },\n};\napp.initialize();", "language": "javascript" } ] } [/block] <p style="margin-top:-12px;margin-bottom:-12px;">**1.** Inicialização das propriedades de sua aplicação, onde: <ul style="margin-bottom:-75px;"> <li style="margin-bottom:-18px;"><code>app_token</code> &ndash; é o código do seu app obtido na plataforma da Inngage.</li> <li style="margin-bottom:-18px;"><code>senderID</code> &ndash; é o identificador do seu projeto no Google Developers Console.</li> <li style="margin-bottom:20px;"><code>icon</code> &ndash; é o nome do ícone disponibilizado no diretório drawables do Android.</li> </ul> </p> [block:code] { "codes": [ { "code": "var app_token = \"50a8affe879ee54b1fe67d2638672a4f\";\nvar server = \"https://api.inngage.com.br/v1\";\nvar jsonData = \"\";\n\nvar push = PushNotification.init({\n\"android\": {\n \"senderID\": \"123456789\",\n \"icon\": \"icon\",\n \"iconColor\": \"white\"\n},\n\"ios\": { \n \"alert\": \"true\", \n \"badge\": \"true\", \n \"sound\": \"true\"\n }, \n \"windows\": {}\n});", "language": "javascript" } ] } [/block] <p style="margin-top:-12px;margin-bottom:-12px;">**2.** Registro do dispositivo nos provedores (GCM ou APNS) para o recebimento de push notification. </p> [block:code] { "codes": [ { "code": "push.on('registration', function(data) {\n\n\tnavigator.geolocation.getCurrentPosition(function success(position) {\n\n \tvar latitude = position.coords.latitude;\n var longitude = position.coords.longitude;\n jsonData = JSON.stringify({\n \t\"registerGeolocationRequest\": {\n \t\"app_token\": app_token,\n \"uuid\": device.uuid,\n \"lat\": latitude,\n \"lon\": longitude\n \t}\n });\n console.log(\"Sending location data to server: \" + jsonData);\n $.post(server + \"/geolocation/\", jsonData)\n \t.done(function(response) {\n \tconsole.log(\"Server response: \" + JSON.stringify(response));\n \t})\n .fail(function() {\n console.log(\"A communication error occurred while sending data to the server (1401).\");\n });\n }, function error(error) {\n console.log(\"An error occurred while obtaining the user location (1402).\");\n });\n \tcordova.getAppVersion(function(version) {\n\n \tjsonData = JSON.stringify({\n \"registerSubscriberRequest\": {\n \"identifier\": device.uuid,\n \"registration\": data.registrationId,\n \"platform\": device.platform.toLowerCase(),\n \"sdk\": 3,\n \"app_token\": app_token,\n \"device_model\": device.model,\n \"device_manufacturer\": device.manufacturer,\n \"os_language\": navigator.language,\n \"os_version\": device.cordova,\n \"app_version\": version,\n \"uuid\": device.uuid\n }\n\t\t\t});\n console.log(\"Sending data to server: \" + jsonData);\n $.post(server + \"/subscription/\", jsonData)\n \t .done(function(response) {\n \t \tconsole.log(\"Server response: \" + JSON.stringify(response));\n \t})\n .fail(function() {\n \t\tconsole.log(\"A communication error occurred while sending data to the server (1403).\");\n });\n });\n});", "language": "javascript" } ] } [/block] <p style="margin-top:-12px;margin-bottom:-12px;">**3.** Manipulação do evento de recebimento de Pushes. Toda vez que uma nova notificação for recebida, este evento será disparado. </p> [block:code] { "codes": [ { "code": "push.on('notification', function (data) {\n\tconsole.log(\"Notification received :\" + JSON.stringify(data));\n jsonData = JSON.stringify({\n\t \"notificationRequest\": {\n \"id\": data.additionalData.id,\n \"app_token\": app_token\n }\n });\n console.log(\"Sending callback to server: \" + jsonData);\n $.post(server + \"/notification/\", jsonData)\n\t .done(function (response) {\n \tconsole.log(\"Server response: \" + JSON.stringify(response));\n })\n .fail(function () {\n \t\tconsole.log(\"A communication error occurred while sending data to the server (1404).\");\n });\n\tnavigator.notification.alert(\n data.body,\n \tfunction () {},\n data.title,\n \"Ok\"\n );\n});", "language": "javascript" } ] } [/block] [block:callout] { "type": "info", "title": "Recebendo Dados Adicionais", "body": "Para receber dados adicionais enviados através da API de envio de mensagens, você deverá utilizar o objeto **inngage_data[0].nome_variavel**. Veremos abaixo um exemplo de utilização dos dados adicionais recebidos na mensagem." } [/block] Dados adicionais (**additional_data**) enviados na mensagem: [block:code] { "codes": [ { "code": "{\n\t\"sendPushRequest\": {\n\t\t\"title\": \"Meu App\",\n\t\t\"message\": \"Mensagem Urgente\",\n\t\t\"app_token\": \"e605c02ac034dc676465d13e5663d1c41\",\n\t\t\"identifier\": \"49556274634\",\n\t\t\"additional_data\": {\n\t\t\t\"acao\": \"adesao_fatura_email\"\n\t\t}\n\t}\n}", "language": "json" } ] } [/block] A seguinte mensagem será recebida pelo dispositivo: [block:code] { "codes": [ { "code": "{\n\t\"title\": \"Meu App\",\n\t\"message\": \"Mensagem Urgente\",\n\t\"additionalData\": {\n\t\t\"id\": \"133945\",\n\t\t\"inngage_data\": [{\n\t\t\t\"acao\": \"adesao_fatura_email\"\n\t\t}],\n\t\t\"google.message_id\": \"0:1487196990535718%7a9e9be3f9fd7ecd\",\n\t\t\"coldstart\": false,\n\t\t\"collapse_key\": \"do_not_collapse\",\n\t\t\"foreground\": true\n\t}\n}", "language": "json" } ] } [/block] Para recuperar o objeto **acao** neste exemplo: [block:code] { "codes": [ { "code": "data.additionalData.inngage_data[0].acao", "language": "javascript" } ] } [/block]