Coder Social home page Coder Social logo

sdac / apns2 Goto Github PK

View Code? Open in Web Editor NEW

This project forked from sideshow/apns2

0.0 2.0 0.0 110 KB

⚡ HTTP/2 Apple Push Notification Service (APNs) push provider for Go — Send push notifications to iOS, tvOS, and OSX apps, using the new APNs HTTP/2 protocol.

License: MIT License

Go 100.00%

apns2's Introduction

APNS/2

NOTE: This is an experimental branch for the purpose of testing the new token based authentication

APNS/2 is a go package designed for simple, flexible and fast Apple Push Notifications on iOS, OSX and Safari using the new HTTP/2 Push provider API.

Build Status Coverage Status GoDoc

Features

  • Uses new Apple APNs HTTP/2 connection
  • Supports new Apple Token Based Authentication (JWT)
  • Works with older versions of go (1.5.x) not just 1.6
  • Supports new iOS 10 features such as Collapse IDs, Subtitles and Mutable Notifications
  • Supports persistent connections to APNs
  • Fast, modular & easy to use
  • Tested and working in APNs production environment

Install

  • Make sure you have Go installed and have set your GOPATH.

  • Download and install the dependencies:

    go get -u golang.org/x/net/http2
    go get -u golang.org/x/crypto/pkcs12
  • Install apns2:

    go get -u github.com/sideshow/apns2

Example

package main

import (
  apns "github.com/sideshow/apns2"
  "github.com/sideshow/apns2/certificate"
  "log"
)

func main() {

  cert, pemErr := certificate.FromPemFile("../cert.pem", "")
  if pemErr != nil {
    log.Println("Cert Error:", pemErr)
  }

  notification := &apns.Notification{}
  notification.DeviceToken = "11aa01229f15f0f0c52029d8cf8cd0aeaf2365fe4cebc4af26cd6d76b7919ef7"
  notification.Topic = "com.sideshow.Apns2"
  notification.Payload = []byte(`{"aps":{"alert":"Hello!"}}`) // See Payload section below

  client := apns.NewClient(cert).Production()
  res, err := client.Push(notification)

  if err != nil {
    log.Println("Error:", err)
    return
  }

  log.Println("APNs ID:", res.ApnsID)
}

Notification

At a minimum, a Notification needs a DeviceToken, a Topic and a Payload.

notification := &Notification{
  DeviceToken: "11aa01229f15f0f0c52029d8cf8cd0aeaf2365fe4cebc4af26cd6d76b7919ef7",
  Topic: "com.sideshow.Apns2",
  Payload: []byte(`{"aps":{"alert":"Hello!"}}`),
}

You can also set an optional ApnsID, Expiration or Priority.

notification.ApnsID =  "40636A2C-C093-493E-936A-2A4333C06DEA"
notification.Expiration = time.Now()
notification.Priority = apns.PriorityLow

Payload

You can use raw bytes for the notification.Payload as above, or you can use the payload builder package which makes it easy to construct APNs payloads.

// {"aps":{"alert":"hello","badge":1},"key":"val"}

payload := NewPayload().Alert("hello").Badge(1).Custom("key", "val")

notification.Payload = payload
client.Push(notification)

Refer to the payload docs for more info.

Response, Error handling

APNS/2 draws the distinction between a valid response from Apple indicating whether or not the Notification was sent or not, and an unrecoverable or unexpected Error;

  • An Error is returned if a non-recoverable error occurs, i.e. if there is a problem with the underlying http.Client connection or Certificate, the payload was not sent, or a valid Response was not received.
  • A Response is returned if the payload was successfully sent to Apple and a documented response was received. This struct will contain more information about whether or not the push notification succeeded, its apns-id and if applicable, more information around why it did not succeed.

To check if a Notification was successfully sent;

res, err := client.Push(notification)
if err != nil {
  log.Println("There was an error", err)
  return
}
if res.Sent() {
  log.Println("APNs ID:", res.ApnsID)
}

Command line tool

APNS/2 has a command line tool that can be installed with go get github.com/sideshow/apns2/apns2. Usage:

apns2 --help
usage: apns2 --certificate-path=CERTIFICATE-PATH --topic=TOPIC [<flags>]

Listens to STDIN to send nofitications and writes APNS response code and reason to STDOUT.

The expected format is: <DeviceToken> <APNS Payload>
Example: aff0c63d9eaa63ad161bafee732d5bc2c31f66d552054718ff19ce314371e5d0 {"aps": {"alert": "hi"}}
Flags:
      --help               Show context-sensitive help (also try --help-long and --help-man).
  -c, --certificate-path=CERTIFICATE-PATH
                           Path to certificate file.
  -t, --topic=TOPIC        The topic of the remote notification, which is typically the bundle ID for your app
  -m, --mode="production"  APNS server to send notifications to. `production` or `development`. Defaults to `production`
      --version            Show application version.

License

The MIT License (MIT)

Copyright (c) 2016 Adam Jones

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

apns2's People

Contributors

alissonsales avatar appleboy avatar c3mb0 avatar imhoffd avatar sdac avatar shawnps avatar sideshow avatar unrolled avatar xrisk avatar

Watchers

 avatar  avatar

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.