如何使用ASP.NET Web服务创建自定义推送通知?

6

我有一款可用于iPhone和安卓的单一应用程序。我想使用asp.net网络服务在我的应用程序中实现自定义推送通知。

我该如何做呢?

是否有任何样例代码可以与网络服务管理数据?请建议我如何为此管理网络服务。

谢谢。

2个回答

3
请使用以下 GitHub上的代码 来进行 .Net 推送通知。您需要在其中提供 .p12 文件,并根据您的需求设置开发者/生产模式。

是这样吗?我在我们社区中没有找到任何提到这个规则的地方。 - Janak Nirmal
你可能会对这个链接感兴趣:http://meta.stackexchange.com/questions/25209/what-is-the-official-etiquette-on-answering-a-question-twice。 - Janak Nirmal
请参考Moderator Jeff Atwood在Lance Robert的回答下方的评论,以及他自己的回答来解释此问题。 - Parth Bhatt
答案可能对正在寻找PHP解决方案的其他人有用,我认为不应该删除。如果您仍然希望被删除,请标记给版主注意并让他决定如何处理。 - Janak Nirmal
没问题。不用管它。我的兴趣不在于让你的回答被删除。但如果你能合并这些答案,那就太好了。没有个人恩怨。 - Parth Bhatt

2

以下代码是PHP代码.

没有现成的代码可用。您可以在数据库表中维护1个标签字段,例如1表示iOS设备,2表示Android设备。我已经实现了相同的功能,并且以下是根据情况发送推送通知的代码。

//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;
}

注意:如有任何疑问或查询,请随时联系。请在评论区留言。


谢谢回复。我有一些问题,因为我是新手。实现这个需要使用任何框架吗?我可以直接将您的代码用于我的网络服务,还是需要进行修改? - Developer
这里的APPLE_URL是什么? - Vaibhav Agarwal
@Akash 对于沙盒环境应该使用 gateway.sandbox.push.apple.com,而生产环境则使用 gateway.push.apple.com。 - Janak Nirmal
k.. 你能告诉我一个问题吗?iPhone应用程序的设备令牌对于所有用户都保持不变,如果不是这样,我该如何动态获取它...还有一件事,我如何在没有用户ID的情况下向特定用户发送通知。 - Vaibhav Agarwal
这是用于推送通知的服务器端代码。如果您有其他问题,请发布它,我会帮助解决。 - Janak Nirmal
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接