A very long time I didn’t post a code here. I recently implemented “Web Push Notification” on a few websites using the very popular OneSignal cross platform service. To reuse the method on multiple sites, I simplified the code that handles message sending in a function. In this post I just wanted to share that for my readers.
function osAddPush($oneSignalConfig) { if (sizeof($oneSignalConfig)) { $notifTitle = html_entity_decode($oneSignalConfig['title'], ENT_QUOTES, 'UTF-8'); $notifContent = html_entity_decode($oneSignalConfig['brief'], ENT_QUOTES, 'UTF-8'); $includedSegments = array('All'); $fields = array( 'app_id' => $oneSignalConfig['app_id'], 'headings' => array("en" => $notifTitle), 'included_segments' => $includedSegments, 'isAnyWeb' => true, 'url' => $oneSignalConfig['url'], 'contents' => array("en" => $notifContent) ); $thumbnailUrl = $oneSignalConfig['image_url']; if (!empty($thumbnailUrl)) { $fields['chrome_web_image'] = $thumbnailUrl; } $logoUrl = $oneSignalConfig['logo_url']; if (!empty($logoUrl)) { $fields['chrome_web_icon'] = $logoUrl; } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications"); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Basic ' . $oneSignalConfig['app_rest_api_key'])); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_HEADER, FALSE); curl_setopt($ch, CURLOPT_POST, TRUE); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields)); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); $response = curl_exec($ch); curl_close($ch); return $response; } return null; } // EO_Fn
Its the function that made my reuse easier.
Now, to make it even easier, let me add an example call on that function:
$oneSignalConfig = array( 'app_id' => 'YOUR_ONE_SIGNAL_APP_ID', // replace with your app_id 'app_rest_api_key' => 'YOUR_ONE_SIGNAL_REST_API_KEY', // replace with your app_rest_api_key 'title' => 'Testing the OneSignal Push', 'brief' => 'Write your brief or summary content here. This will be shown below the title.', 'url' => 'CONTENT_URL', // URL of the page/post that you're pushing for 'image_url' => 'CONTENT_IMAGE_URL', 'logo_url' => 'LOGO_URL', // logo of the company/website ); // now do the call osAddPush($oneSignalConfig);
Replace with your own values and make sure you tested it more than once before announcing it for public.
My next post will be a step by step guideline to integrate OneSignal notifications on any website.
Thanks for reading!