6

I have single app for iPhone and android.I want to implement custom push notification in my app using asp.net webservice.

How can i do it?

Is there any sample code which manage the data with webservice?please suggest me how can i manage webservice for this.

Thanks.

2 Answers 2

3

Please use following code from github available for .Net push notification. You need to provide .p12 file in it and you have to set developer/production mode according to your requirement.

Sign up to request clarification or add additional context in comments.

5 Comments

Is it so ? I don't find such rule anywhere mentioned on our community.
You may be interested to check this meta.stackexchange.com/questions/25209/…
Refer to Jeff Atwood's (who is a Moderator) Comment below Lance Robert's answer and Jeff's answer itself explains it.
Answer may be useful to other who is looking for PHP solutions which I believe so not deleted. If you Still prefer to be deleted please flag it to Moderator attention and let him decide what to do with it.
No problem. Leave it. My interest is not to get your answer deleted. But It would have been great if you could merge the answers. Nothing Personal
2

Below code is for PHP.

There is no such Code readily available. You can do it like maintain 1 tag field in database table like 1 for iOS device and 2 for android device. I have implemented same functionality and below is code for sending push notification accordingly.

//This function determines which is the device and send notification accordingly.
function sendPushNotificaitonToAllUser($NotificationMsg)
{
    $sql = "select ID,DeviceToken,DeviceType from TblDeviceToken";
    $rs  = mysql_query($sql);
    $num = mysql_num_rows($rs);

    if($num >= 1)
    {
        while($row = mysql_fetch_array($rs))
        {
            $deviceToken = $row['DeviceToken'];
            if($deviceToken!='' || $deviceToken!='NULL')
            {
                if($row['DeviceType']==1)   
                    deliverApplePushNotification($deviceToken,$NotificationMsg);
                else if($row['DeviceType']==2)  
                    sendAndroidPushNotification($deviceToken,$NotificationMsg);
            }
        }
    }     
}

//APPLE PUSH NOTIFICATION DELIVERY
function deliverApplePushNotification($deviceToken,$message)
{
    //Create context
    $ctx = stream_context_create();
    stream_context_set_option($ctx, 'ssl', 'local_cert', PEM_FILE_NAME);
    stream_context_set_option($ctx, 'ssl', 'passphrase', APPLE_PEM_PASSPHRASE);

    //Establish connection
    $fp = stream_socket_client(APPLE_URL, $err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);

    /*
        if (!$fp)
            exit("Failed to connect: $err $errstr" . PHP_EOL);
    */  

    $body['aps'] = array('alert' => $message,   'sound' => 'default'); // Create the payload body
    $payload = json_encode($body); // Encode the payload as JSON
    $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;// Build the binary notification
    $result = fwrite($fp, $msg, strlen($msg));// Send it to the server


    //If want to keep track of delivery can be done from here.
    /*if (!$result)
        echo '<br/>Message not delivered-->$deviceToken' . PHP_EOL;
    else
        echo '<br/>Message successfully delivered-->$deviceToken' . PHP_EOL;        
    */

    fclose($fp); // Close the connection to the server
}

function sendAndroidPushNotification($deviceRegistrationId,$messageText)
{   
    $authenticationID=googleAuthenticate(ANDROID_USERNAME,ANDROID_PASSWORD,ANDROID_SOURCE,ANDROID_SERVICE);
    $result= sendMessageToPhone($authenticationID,$deviceRegistrationId,ANDROID_MSGTYPE,$messageText);
}   

function googleAuthenticate($username, $password, $source="Company-AppName-Version", $service="ac2dm") 
{    
    session_start();
    if( isset($_SESSION['google_auth_id']) && $_SESSION['google_auth_id'] != null)
        return $_SESSION['google_auth_id'];

    // get an authorization token
    $ch = curl_init();
    if(!ch){
        return false;
    }

    curl_setopt($ch, CURLOPT_URL, "https://www.google.com/accounts/ClientLogin");
    $post_fields = "accountType=" . urlencode('HOSTED_OR_GOOGLE')
        . "&Email=" . urlencode($username)
        . "&Passwd=" . urlencode($password)
        . "&source=" . urlencode($source)
        . "&service=" . urlencode($service);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);    
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    // for debugging the request
    //curl_setopt($ch, CURLINFO_HEADER_OUT, true); // for debugging the request

    $response = curl_exec($ch);

    //var_dump(curl_getinfo($ch)); //for debugging the request
    //var_dump($response);

    curl_close($ch);

    if (strpos($response, '200 OK') === false) {
        return false;
    }

    // find the auth code
    preg_match("/(Auth=)([\w|-]+)/", $response, $matches);

    if (!$matches[2]) {
        return false;
    }

    $_SESSION['google_auth_id'] = $matches[2];
    return $matches[2];
}

function sendMessageToPhone($authCode, $deviceRegistrationId, $msgType, $messageText) 
{
    $headers = array('Authorization: GoogleLogin auth=' . $authCode);
    $data = array(
                            'registration_id' => $deviceRegistrationId,
                            'collapse_key' => $msgType,
                            'data.message' => $messageText //TODO Add more params with just simple data instead           
                        );

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, "https://android.apis.google.com/c2dm/send");
    if ($headers)
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

    $response = curl_exec($ch);

    curl_close($ch);

    return $response;
}

NOTE : Feel free to contact in case of any doubts/query. Leave comment

9 Comments

Thanks for reply.I have some questions as i am new to this.Is there any framework required to implement this?And can i directly use your code into my webservice or should i have to make changes for that.
You can directly add your code but you need to do change in select query. You need to declare few constants in your configuration file. I appologize but this code is for PHP. Wait for while will give you solution for .net too for iOS push notification.
Check my other answer for .Net based code for Push Notification.
Thanks for reply.I will try to implement your code and if there is any query then will ask you.
hey as you have said i need to declare few constants in my configuration file.Is it required for .net webservice also?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.