1

嗨,我需要使用 PHP 从我的 Windows 手机应用程序发送 toast 推送通知。我使用了一些代码,但我无法发送推送通知。

我的代码如下:

        private void Click_Login(object sender, RoutedEventArgs e)
        {
        string url = "http://www.best.com/Best_Windows/Login.php";

        Uri uri = new Uri(url, UriKind.Absolute);

        StringBuilder postData = new StringBuilder();
        postData.AppendFormat("{0}={1}", "sUsername", HttpUtility.UrlEncode(this.txtEmailaddress.Text));
        postData.AppendFormat("&{0}={1}", "sPassword", HttpUtility.UrlEncode(this.txtPassword.Password.ToString()));

        WebClient client = default(WebClient);
        client = new WebClient();
        client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
        client.Headers[HttpRequestHeader.ContentLength] = postData.Length.ToString();

        client.UploadStringCompleted += client_UploadStringCompleted;
        client.UploadProgressChanged += client_UploadProgressChanged;

        client.UploadStringAsync(uri, "POST", postData.ToString());

        prog = new ProgressIndicator();
        prog.IsIndeterminate = true;
        prog.IsVisible = true;
        SystemTray.SetProgressIndicator(this, prog);

    }


    private void client_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
    {
        if (e.Cancelled == false & e.Error == null)
        {
            prog.IsVisible = false;

            string[] result = e.Result.ToString().Split('|');
            string strStatus = result[0].ToString();
            strcustomer_id_k = result[1].ToString();
            string strError = result[2].ToString();

            if (strStatus == "0")
            {
                MessageBox.Show(strError);
                LoginPage.strcustomer_id_k = null;
            }
            else
            {
                save_pendingmessage();
            }     




       public void save_pendingmessage()
       { 

         HttpNotificationChannel pushChannel;

        // The name of our push channel.
        string channelName = "ToastSampleChannel";

        // Try to find the push channel.
        pushChannel = HttpNotificationChannel.Find(channelName);
        // If the channel was not found, then create a new connection to the push service.
        if (pushChannel == null)
        {
            pushChannel = new HttpNotificationChannel(channelName);

            // Register for all the events before attempting to open the channel.
            pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
            pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);

            // Register for this notification only if you need to receive the notifications while your application is running.
            pushChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(PushChannel_ShellToastNotificationReceived);

            pushChannel.Open();

            // Bind this new channel for toast events.
            pushChannel.BindToShellToast();

        }
        else
        {
            // The channel was already open, so just register for all the events.
            pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
            pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);

            // Register for this notification only if you need to receive the notifications while your application is running.
            pushChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(PushChannel_ShellToastNotificationReceived);

            // Display the URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
            System.Diagnostics.Debug.WriteLine(pushChannel.ChannelUri.ToString());

        }            

        string url = "http://www.best.com/Best_Windows/send_message.php";
        Uri uri = new Uri(url, UriKind.Absolute);


        StringBuilder postData = new StringBuilder();
        postData.AppendFormat("{0}={1}", "customer_id", HttpUtility.UrlEncode(strcustomer_id_k));
        postData.AppendFormat("&{0}={1}", "device_uri", HttpUtility.UrlEncode(pushChannel.ChannelUri.ToString()));
        WebClient client = default(WebClient);
        client = new WebClient();
        client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
        client.Headers[HttpRequestHeader.ContentLength] = postData.Length.ToString();

        client.UploadStringCompleted += client_SaveStringCompleted;

        client.UploadStringAsync(uri, "POST", postData.ToString());

        prog = new ProgressIndicator();
        prog.IsVisible = true;
       // prog.Text = "Loading....";
    }
    private void client_SaveStringCompleted(object sender, UploadStringCompletedEventArgs e)
    {

        if (e.Cancelled == false && e.Error == null)
        {
            string[] result = e.Result.ToString().Split('|');
            //*** Check Status
            if (result[0].ToString() == "0")
            {
                MessageBox.Show(result[0].ToString());
            }
            else
            {
                MessageBox.Show(result[0].ToString());
               // NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
            }

            prog.IsVisible = false;
        }
    }  

我的php代码如下

send_message.php

<?php
 $con=mysqli_connect("localhost","user","pass","dbname");
 if (isset($_POST["customer_id"]) && isset($_POST["device_uri"])) 
 {
  $notif_url = $_POST["device_uri"];
  $customer_id =  $_POST["customer_id"];

  $getregid = mysqli_query($con,"select * from pim_offerstatus where customer_id='6' and device_uri = 'fghfhghfghfgh' ");
  if (mysqli_num_rows($getregid) > 0) 
  {
   $query = mysqli_query($con,"select count(offer) as count from pim_offerstatus where         customer_id='6' and offer!=''");
   $count = mysqli_fetch_array($query);
   $msg = $count['count'];
   $message = array("offer" => $msg." "."The offers received");
   include_once './windowspush.php';
   $windows_push = new WindowsPhonePushNotification($notif_url);
   $res = $windows_push->push($target,$message,$notif_url);

   $response["success"] = 1;
   $response["message"] = "gum registration id is successfully updated";
    // echoing JSON response
  echo json_encode($response);
  }
}
  else 
 {
  required field is missing
  $response["success"] = 0;
  $response["message"] = "Required field(s) is missing";

  echoing JSON response
  echo json_encode($response);
 }
 ?>

windowsphone.php

<?php 
 final class WindowsPhonePushDelay
 {

  const Immediate=0;

  private function __construct(){}
}

class WindowsPhonePushNotification
{
  private $notif_url = '';

  function WindowsPhonePushNotification($notif_url)
  {
    $this->notif_url = $notif_url;
  }
  public function push($target,$message_id,$message1,$notif_url)
  {

  // Create the toast message
  $toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" .
            "<wp:Notification xmlns:wp=\"WPNotification\">" .
               "<wp:Toast>" .
                    "<wp:Text1>" . "SendToast" . "</wp:Text1>" .
                    "<wp:Text2>" . $message1 . "</wp:Text2>" .
                    ""<wp:Param>/BestDeal.xaml?=Toast Notification</wp:Param>" .
                    "</wp:Toast> " .
            "</wp:Notification>";

   // Create request to send
   $r = curl_init();
   curl_setopt($r, CURLOPT_URL,$notif_url);
   curl_setopt($r, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($r, CURLOPT_POST, true);
   curl_setopt($r, CURLOPT_HEADER, true); 

  // add headers
   $httpHeaders=array('Content-type: text/xml; charset=utf-8', 'X-WindowsPhone-Target: toast',
                'Accept: application/*', 'X-NotificationClass: 2','Content-Length:'.strlen($toastMessage));
curl_setopt($r, CURLOPT_HTTPHEADER, $httpHeaders);

// add message
curl_setopt($r, CURLOPT_POSTFIELDS, $toastMessage);

// execute request
$output = curl_exec($r);
curl_close($r);

 }
}

?>

嗨,这是我的代码,当客户成功登录时,我需要在我的应用程序中发送接收推送通知。你能告诉我为什么我会遇到这个问题以及如何解决它吗?

4

0 回答 0