apns

package module
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 21, 2018 License: MIT Imports: 13 Imported by: 0

README

go-apns

APNS

Example
  • First installation
go get github.com/king129/go-apns
  • Using p12 certificate
import (
   "github.com/king129/go-apns"
   "github.com/king129/go-apns/cer"
   "fmt"
)
    
cer, err := cert.FromP12File("xxxx", "xxx")
if err != nil {
	fmt.Println(err)
	return
}

client := apns.NewClientWithCer(cer)

m := &apns.Message{
	Topic: "me.kinghub.apns.demo",
	DeviceToken: "xxxxxxxxxxxxxxxxx",
	Payload: &apns.MessagePayload{
		Aps: &apns.MessageAps{
			Alert: &apns.MessageAlert{
				Title: "test",
				Body: "xxxxxx",
			},
			Badeg: 100,
			Sound: apns.MessageAPNSSoundDefault,
		},
	},
}

client.Push(m)

  • Using authKey
import (
	"github.com/king129/go-apns"
	"github.com/king129/go-apns/token"
	"fmt"
)


token, err := token.NewToken(authKeyPath, teamID, keyID)
if err != nil {
	fmt.Println(err)
	return
}
	
client := apns.NewClientWithToken(token)
	
m := &apns.Message{
	Topic: "me.kinghub.apns.demo",
	DeviceToken: "xxxxxxxxxxxxxxxxx",
	Payload: &apns.MessagePayload{
		Aps: &apns.MessageAps{
			Alert: &apns.MessageAlert{
				Title: "test",
				Body: "xxxxxx",
			},
			Badeg: 100,
			Sound: apns.MessageAPNSSoundDefault,
		},
	},
}
client.Push(m)

Documentation

Index

Constants

View Source
const (
	// 400 The collapse identifier exceeds the maximum allowed size
	ReasonBadCollapseID = "BadCollapseId"

	// 400 The specified device token was bad. Verify that the request contains a
	// valid token and that the token matches the environment.
	ReasonBadDeviceToken = "BadDeviceToken"

	// 400 The apns-expiration value is bad.
	ReasonBadExpirationDate = "BadExpirationDate"

	// 400 The apns-id value is bad.
	ReasonBadMessageID = "BadMessageId"

	// 400 The apns-priority value is bad.
	ReasonBadPriority = "BadPriority"

	// 400 The apns-topic was invalid.
	ReasonBadTopic = "BadTopic"

	// 400 The device token does not match the specified topic.
	ReasonDeviceTokenNotForTopic = "DeviceTokenNotForTopic"

	// 400 One or more headers were repeated.
	ReasonDuplicateHeaders = "DuplicateHeaders"

	// 400 Idle time out.
	ReasonIdleTimeout = "IdleTimeout"

	// 400 The device token is not specified in the request :path. Verify that the
	// :path header contains the device token.
	ReasonMissingDeviceToken = "MissingDeviceToken"

	// 400 The apns-topic header of the request was not specified and was
	// required. The apns-topic header is mandatory when the client is connected
	// using a certificate that supports multiple topics.
	ReasonMissingTopic = "MissingTopic"

	// 400 The message payload was empty.
	ReasonPayloadEmpty = "PayloadEmpty"

	// 400 Pushing to this topic is not allowed.
	ReasonTopicDisallowed = "TopicDisallowed"

	// 403 The certificate was bad.
	ReasonBadCertificate = "BadCertificate"

	// 403 The client certificate was for the wrong environment.
	ReasonBadCertificateEnvironment = "BadCertificateEnvironment"

	// 403 The provider token is stale and a new token should be generated.
	ReasonExpiredProviderToken = "ExpiredProviderToken"

	// 403 The specified action is not allowed.
	ReasonForbidden = "Forbidden"

	// 403 The provider token is not valid or the token signature could not be
	// verified.
	ReasonInvalidProviderToken = "InvalidProviderToken"

	// 403 No provider certificate was used to connect to APNs and Authorization
	// header was missing or no provider token was specified.
	ReasonMissingProviderToken = "MissingProviderToken"

	// 404 The request contained a bad :path value.
	ReasonBadPath = "BadPath"

	// 405 The specified :method was not POST.
	ReasonMethodNotAllowed = "MethodNotAllowed"

	// 410 The device token is inactive for the specified topic.
	ReasonUnregistered = "Unregistered"

	// 413 The message payload was too large. See Creating the Remote Notification
	// Payload in the Apple Local and Remote Notification Programming Guide for
	// details on maximum payload size.
	ReasonPayloadTooLarge = "PayloadTooLarge"

	// 429 The provider token is being updated too often.
	ReasonTooManyProviderTokenUpdates = "TooManyProviderTokenUpdates"

	// 429 Too many requests were made consecutively to the same device token.
	ReasonTooManyRequests = "TooManyRequests"

	// 500 An internal server error occurred.
	ReasonInternalServerError = "InternalServerError"

	// 503 The service is unavailable.
	ReasonServiceUnavailable = "ServiceUnavailable"

	// 503 The server is shutting down.
	ReasonShutdown = "Shutdown"
)

推送失败时 会返回具体错误原因 https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html#//apple_ref/doc/uid/TP40008194-CH11-SW1

View Source
const MessagePayloadMaxLength = 4096

HTTP/2 的APNS 协议支持最大长度为4kb 数据

Variables

View Source
var (
	MessageNotTopicError       = errors.New("topic cannot be empty")
	MessageNotDeviceTokenError = errors.New("deviceToken cannot be empty")
	MessageNotPayloadError     = errors.New("payload cannot be empty")
	MessagePayloadLargeError   = errors.New("the payload exceeds the maximum length and the maximum length is 4096 bytes")
)

Functions

This section is empty.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

func NewClientWithCer

func NewClientWithCer(certificate tls.Certificate) *Client

func NewClientWithToken

func NewClientWithToken(token *token.Token) *Client

func (*Client) Close

func (c *Client) Close()

func (*Client) CloseIdleConnections

func (c *Client) CloseIdleConnections()

func (*Client) Development

func (c *Client) Development() *Client

func (*Client) Host

func (c *Client) Host() string

func (*Client) Production

func (c *Client) Production() *Client

func (*Client) Push

func (c *Client) Push(m *Message) (*Response, error)

func (*Client) PushWithContext

func (c *Client) PushWithContext(ctx context.Context, m *Message) (*Response, error)

type Message

type Message struct {
	ApnsID      string          `json:"apns_id,omitempty"`
	CollapseID  string          `json:"collapse_id,omitempty"`
	DeviceToken string          `json:"device_token"` // App Bundle ID
	Topic       string          `json:"topic"`
	Expiration  int64           `json:"expiration,omitempty"`
	Priority    MessagePriority `json:"priority,omitempty"`
	Payload     *MessagePayload `json:"payload"`
}

官方文档 https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/sending_notification_requests_to_apns

type MessageAlert

type MessageAlert struct {
	Title           string `json:"title"`
	SubTitle        string `json:"subtitle,omitempty"`
	Body            string `json:"body,omitempty"`
	TitleLocKey     string `json:"title-loc-key,omitempty"`
	TitleLocArgs    string `json:"title-loc-args,omitempty"`
	SubTitleLocKey  string `json:"subtitle-loc-key,omitempty"`
	SubTitleLocArgs string `json:"subtitle-loc-args,omitempty"`
	ActionLocKey    string `json:"action-loc-key,omitempty"`
	LocKey          string `json:"loc-key,omitempty"`
	LocArgs         string `json:"loc-args,omitempty"`
	LaunchImage     string `json:"launch-image,omitempty"`
}

type MessageAps

type MessageAps struct {
	Alert            *MessageAlert `json:"alert"`
	Badge            int64         `json:"badge,omitempty"`
	Sound            string        `json:"sound,omitempty"`
	ThreadID         string        `json:"thread-id,omitempty"`
	ContentAvailable int           `json:"content-available,omitempty"`
	MutableContent   int           `json:"mutable-content,omitempty"`
	Category         string        `json:"category,omitempty"`
}

type MessagePayload

type MessagePayload struct {
	Aps    *MessageAps            `json:"aps"`
	Custom map[string]interface{} `json:"custom,omitempty"`
}
{
     "aps" : {
         "alert" : {   // string or dictionary
			"title"          :   "string",
			"subtitle"       :   "string",
            "body"           :   "string",
            "title-loc-key"  :   "string or null",
            "title-loc-args" :   "array of strings or null",
            "action-loc-key" :   "string or null",
            "loc-key"        :   "string",
            "loc-args"       :   "array of strings",
            "launch-image"   :   "string"
         },
          "badge"             :  number,
          "sound"             :  "string",
		  "content-available" :  number,
		  "mutable-content"   :  number,
          "category"          :  "string"
     },
}

aps:推送消息必须有的key alert:推送消息包含此key值,系统就会根据用户的设置展示标准的推送信息 badge:在app图标上显示消息数量,缺少此key值,消息数量就不会改变,消除标记时把此key对应的value设置为0 sound:设置推送声音的key值,系统默认提示声音对应的value值为default content-available:此key值设置为1,系统接收到推送消息时就会调用不同的回调方法,iOS7之后配置后台模式 category:UIMutableUserNotificationCategory's identifier 可操作通知类型的key值 title:简短描述此调推送消息的目的,适用系统iOS8.2之后版本 body:推送的内容 title-loc-key:功能类似title,附加功能是国际化,适用系统iOS8.2之后版本 title-loc-args:配合title-loc-key字段使用,适用系统iOS8.2之后版本 action-loc-key:可操作通知类型key值,不详细叙述 loc-key:参考title-loc-key loc-args:参考title-loc-args launch-image:点击推送消息或者移动事件滑块时,显示的图片。如果缺少此key值,会加载app默认的启动图片。

// 官方 json payload 定义 https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/creating_a_remote_notification_payload#2943363

type MessagePriority

type MessagePriority int
const (
	MessagePriortyLow       MessagePriority = 5  // 推送消息立即发送
	MessagePriortyHigh      MessagePriority = 10 // 推送消息在节省接收设备电源的时间发送
	MessageAPNSSoundDefault                 = "default"
)

type Response

type Response struct {
	StatusCode int    `json:"status_code,omitempty"`
	Reason     string `json:"reason,omitempty"`
	ApnsID     string `json:"apns_id,omitempty"`
	Timestamp  Time   `json:"timestamp,omitempty"`
}

func (*Response) Success

func (c *Response) Success() bool

type Time

type Time struct {
	time.Time
}

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(b []byte) error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL