Giter Club home page Giter Club logo

alternate-push-channel's Introduction

⚠️⚠️⚠️ UNSUPPORTED ⚠️⚠️⚠️

This is now unsupported and does not work. You cannot use alternate push channels on UWP apps.

Alternate Push Channels (Web Push for Windows apps)

How to use the alternate push channel for Windows apps

Super quick start

  1. Clone this repository
  2. Open the VS solution located in src
  3. Build, deploy, and launch the app
  4. Copy your SubscriptionJson from the app
  5. Go to this website, paste your SubscriptionJson, type a message, and click Send
  6. A notification should appear on your computer!

Integrate into your own apps...

1. Create a new Windows app

Create a new UWP app, or open an existing one.

2. Add the library

Install the NuGet package, AlternatePushChannel.Library (be sure to include prerelease as it's currently in alpha).

3. Create your application server keys

To use alternate push channels, you need to have a pair of public and private server keys, exactly like Web Push.

You can easily generate a public and private key at this website: https://web-push-codelab.glitch.me/

4. Create the push subscription

Create a subscription, passing in your public server key. You also get to create up to 1,000 different channels, so pick a channel of your choice.

You'll want to grab the subscriptionJson as you'll need that to send a push notification.

var subscription = await PushManager.SubscribeAsync("YOUR_PUBLIC_KEY", "myChannel1");

var subscriptionJson = subscription.ToJson();

// TODO: Display the subscriptionJson or send that to your push server

5. Handle background task activation

Your app's background task will be activated when you receive a push (the foreground event listener doesn't work). In your App.xaml.cs, add the following code and call this from your app's constructor

public App()
{
    this.InitializeComponent();
    this.Suspending += OnSuspending;

    // Call the new method
    RegisterPushBackgroundTask();
}

// New method
private void RegisterPushBackgroundTask()
{
    try
    {
        const string PushBackgroundTaskName = "Push";
        if (!BackgroundTaskRegistration.AllTasks.Any(i => i.Value.Name == PushBackgroundTaskName))
        {
            var builder = new BackgroundTaskBuilder();
            builder.Name = PushBackgroundTaskName;
            builder.SetTrigger(new PushNotificationTrigger());
            builder.Register();
        }
    }
    catch (Exception ex)
    {
    }
}

// New method
protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args)
{
    // We need to get a deferral since we'll be doing async code
    var deferral = args.TaskInstance.GetDeferral();

    try
    {
        RawNotification notification = (RawNotification)args.TaskInstance.TriggerDetails;

        // Decrypt the content
        string payload = await PushManager.GetDecryptedContentAsync(notification);

        // Show a notification
        // You'll need Microsoft.Toolkit.Uwp.Notifications NuGet package installed for this code
        ToastContent content = new ToastContent()
        {
            Visual = new ToastVisual()
            {
                BindingGeneric = new ToastBindingGeneric()
                {
                    Children =
                    {
                        new AdaptiveText()
                        {
                            Text = "Push notification received"
                        },

                        new AdaptiveText()
                        {
                            Text = payload
                        }
                    }
                }
            }
        };

        ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(content.GetXml()));
    }
    catch
    {
        // Decryption probably failed, did your server use the correct keys to sign?
    }

    // Complete the deferral, telling the OS that we're done
    deferral.Complete();
}

6. Launch app!

Launch your app and grab your subscription details!

7. Test pushing to your app

Go to https://interactivenotifs.azurewebsites.net/webpush, enter your public and private key from earlier, paste in your subscription JSON from your app, and click send!

8. You should see a notification appear!

Your background task should be triggered and a notification should appear!

9. Pushing to your app from your own server

Follow any online instructions for sending web push notifications from your server's choice of language (the server-side code is identical to web push notifications). For C#, we like the WebPush NuGet package for its simplicity and ease-of-use.

Here's a C# sample using the NuGet package...

public static class WebPush
{
    // Keys generated from step #3 (don't store private in public source code)
    // Note that this is the same public key you include in your app in step #4
    private const string PublicKey = "BGg3UxX...";
    private const string PrivateKey = "_RwmE...";

    private static WebPushClient _webPushClient = new WebPushClient();

    public class Subscription
    {
        public string Endpoint { get; set; }
        public SubscriptionKeys Keys { get; set; }
    }

    public class SubscriptionKeys
    {
        public string P256DH { get; set; }
        public string Auth { get; set; }
    }

    public static async Task SendAsync(string subscriptionJson, string payload)
    {
        var subscription = JsonConvert.DeserializeObject<Subscription>(subscriptionJson);

        try
        {
            await _webPushClient.SendNotificationAsync(
                subscription: new PushSubscription(
                    endpoint: subscription.Endpoint,
                    p256dh: subscription.Keys.P256DH,
                    auth: subscription.Keys.Auth),
                payload: payload,
                vapidDetails: new VapidDetails(
                    subject: "mailto:[email protected]",
                    publicKey: PublicKey,
                    privateKey: PrivateKey));
        }
        catch (Exception ex)
        {
            Debugger.Break();
            throw ex;
        }
        return;
    }
}

alternate-push-channel's People

Contributors

andrewleader avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar

Forkers

perkio

alternate-push-channel's Issues

Received unexpected response code: 401

It was working fine few months back. Now when trying to run "AlternatePushChannel.SampleApp" its throwing error

at _webPushClient.SendNotificationAsync( getting error
Headers: {x-wns-error-description: AppId is not allowed to post Webpush notifications to WNS
Strict-Transport-Security: max-age=31536000; includeSubDomains
Date: Fri, 01 Jul 2022 03:16:44 GMT
x-wns-status: dropped
x-wns-notificationstatus: dropped
ms-cv: eXJI1AUNQ0KwOrCZLNPfvQ.0
x-wns-debug-trace: BL2PEPF0000958B
x-wns-msg-id: 2A2C4C264C920F83

Received unexpected response code: 401

Missing Unsubscribe(channelId)

Would be great if you could expose a way to Unsubscribe a channel entirely, I know there's no API for it after serialization occurs but at least add a way to remove all subscription entries from storage so received notifications from that point onward would be discarded.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.