Click here to Skip to main content
15,889,176 members
Articles / Programming Languages / PHP

Send Push Notifications to Windows Phone 8.1 App Using PHP

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
3 Apr 2016CPOL2 min read 16.6K   364   2
In this article, we will learn how to send Push notifications to Windows phone 8.1 app using php

Introduction

Here, we will see how to receive notifications in Windows 8.1 devices. For receiving Push notifications, we need a client and a server. Client is one which will receive notification and the server is one which will send notification to the client. We will create client in Windows phone 8.1 and server in PHP.

Client (WP 8.1 App)

Take a new project, i.e., Blank WP 8.1 App and give it whatever name you want.

You need to associate your app with Windows store first. So register your app in your developer account here. After registering your app at store, right click on your project in solution explorer and click on Store-->Associate App with Store...

You will get the below screen:

Image 1

Image 2

After login, you will get mobile number verification screen. After mobile number verification, you will get a list of all the apps that you have registered in your developer account. Select the app name and click Next button.

Image 3

Create channel and generate uri. This uri is unique for any device. WNS will send notification to this uri. We can call it Device Token or Device Id.

C#
string notificationUrl;
var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
notificationUrl= channel.Uri.ToString();

It will be generated by client app itself and we need to give this uri to the server because the server will send notification using this uri.

Server (PHP)

For sending push notification to Windows phone 8.1 devices, we need the following three things:

  1. Package SID
  2. Client secret
  3. Uri

You will get Package SID and Client secret from your Windows developer account. In your developer account, go to Services-->Push notifications in left navigation bar. Then, click on Live Services site.

Image 4

You will get Package SID and Client secret here.

Image 5

Uri will be generated by client app and we have already seen this.

Create a php page and write the below code in it.

PHP
 <html>
   
   <head>
      <title>Send Push Notification</title>
   </head>
   
   <body>
      
      <?php
      
         /* Defining a PHP Function */
         function sendPushNotification() {

        $token="";
        $message="Test message";
                $XmlToastTemplate = '<?xml version="1.0" 
                encoding="UTF-8"?><toast launch="">
            <visual lang="en-US">
            <binding template="ToastText01">
            <text id="1">'.$message.'</text>
            </binding>
            </visual>
            </toast>';           
            
            if ($token == null || $token=="")
            {              
              $token=createToken();
               }
               
               //echo $XmlToastTemplate;
               
               //It is the device token, it will be unique for each user
               $sUrlWithToken="Uri with token";
             
             // ************* Call API:
        $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $sUrlWithToken);
        curl_setopt($ch, CURLOPT_POST, 1);// set post data to true
        curl_setopt($ch, CURLOPT_POSTFIELDS,$XmlToastTemplate);   // post data
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'X-WNS-Type: wns/toast',
                'X-WNS-RequestForStatus: true',
                'Content-Type: text/xml',
                'Authorization: Bearer '.$token
                ));
        $json = curl_exec($ch);
        
        curl_close ($ch);
        
         echo "Notification Sent";
         }
         
         function createToken()
         {
            //Change Package Id and ClientSecret to the given one.
            $encSid = urlencode('Package Id');
            $encSecret = urlencode('Client Secret');
            
            
            $sUrl ="https://login.live.com/accesstoken.srf";
            $body =
                "grant_type=client_credentials&client_id=".$encSid.
                 "&client_secret=".$encSecret."&scope=notify.windows.com";

        // ************* Call API:
        $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $sUrl);
        curl_setopt($ch, CURLOPT_POST, 1);// set post data to true
        curl_setopt($ch, CURLOPT_POSTFIELDS,$body);   // post data
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $json = curl_exec($ch);
        curl_close ($ch);
        $obj = json_decode($json);
        
        return $obj->{'access_token'};

         }
         
         /* Calling a PHP Function */
         sendPushNotification();
      ?>
      
   </body>
</html>

When you will run this page, on page load, you will receive notification in your app.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
QuestionPush Not Received Pin
Abhijeet Chowdhury12-Jan-17 20:54
Abhijeet Chowdhury12-Jan-17 20:54 
Hi,
I am developing a winrt Windows 8.1 app with PHP services.
Using the code given in the link ( https://www.codeproject.com/Articles/1089935/Send-Push-Notifications-to-Windows-Phone-App-Using ) we have developed the push notification service both in client and server end.
But we are not getting any notification on device.
The steps we have followed till now are as below :
1. Enabled Toast Capable option on app manifest file
2. Added a Background Task(Push Notification)
3. Registered a channel uri and send it to the server for sending push.

C#
private void CreateUri()
        {
            string notificationUrl;
            var channel = Task.Run(async () => await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync()).Result;
            channel.PushNotificationReceived += channel_PushNotificationReceived;
            //localSettings.Values["ChannelUri"] = channel.ToString();
            notificationUrl = channel.Uri.ToString();
            var result = Task.Run(async () => await this.regPush.GetPushNotifRegID(this.customerId, notificationUrl)).Result;
            RegisterBackgroundTask();
        }


We got a channel uri like this :

https://hk2.notify.windows.com/?token=AwYAAAC8OZsKv0lulse+lxPQF7NGostwaolxwNWgXqfw1Ed8Pm1hySMyCQuMARKiNhFQ0bCm5D1esKgnIcl8qw/ahP+b4Q6nU0HSouzHKvg38x30p+ytlLCETXvV3wvnhXySWRM=

4. Using this channel uri we send the push after registering the App with WNS and getting the accessToken

{
    "token_type": "bearer",
    "access_token": "EgCbAQMAAAAEgAAADAABBEZezsYWE3v6nE/0SKOxQv66Dlcs0WZP2zCZJl0xIV246+nqQpkQHBcmMz0tAaqCe/OtcO/WF1OTuuubyWVcyNnANtFSL0XS2oPSRWA55ZwkK+D4tHrR/i2RHvCqL+QaDLG7wUT5Lw+4DFnVYXbcrJyZoYaTDYHvNk4/dYERpTjTpEYRJw+t+7L77HJHCf4oLg9VKWoUTqLzv/ycQfkX09/FHyTHaDRxKRvy3qCwAGL1o3VeNJ1P076Q883nZbIpWsWXCOyuUjIHo86DNju/a/c44fo3BS+W9IzcwBRKIvFnKfPxlg2s+/02L1972x46rwhK6XYDYR2vM+uX4R0wtooAWgCKAAAAAAADDhpEv4J4WL+CeFjrSAQADQA1Mi42Ni45MC4xNDAAAAAAAF0AbXMtYXBwOi8vcy0xLTE1LTItMzMxNzk5MzY4OC0zNzExMDMyODMyLTM4NzIzMzA1NS03NjgwMTk5NTQtNDE3Mzg4NjI1MC0xMDI4MTQwMjk0LTIwMDQwODgwNTUA",
    "expires_in": 86400
}



These all we have done but we are not receiving any push from the server.
Any help on this will be appreciated. Thanks in advance.
Questionmultiple send Pin
Burhan Aksendir13-Apr-16 16:09
Burhan Aksendir13-Apr-16 16:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.