PushSDK

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2020 License: MIT Imports: 19 Imported by: 0

README

PushSDK

PkgGoDev

Go-PushSDK 给APNS发推送消息。包括iOS、华为、小米、魅族、OPPO、vivo

▶ 待完善

🍬 Add the library to your $GOPATH/src

go get github.com/xxgail/PushSDK

example

package main

import (
    "fmt"
    "github.com/xxgail/PushSDK"
)

func main() {
    // 1. 推送消息体
    message := PushSDK.NewMessage()
    message.SetTitle("title").SetContent("content")
    // 2. 发送
    send := PushSDK.NewSend()
    send.SetChannel("ios") // 发送渠道
    send.SetPushId([]string{"xxxx"}) // 发送用户device_token,数组格式
    send.SetPlatForm("{app_id:xxxx}") // 渠道对应参数,详见下表 channel-param
    response,_ := send.SendMessage(message) // 发送
    fmt.Println(response)
}

channel-param

channel plat
ios {"key_id":"xxx","team_id":"xxx","bundle_id":"xxx","auth_token_path":"xxx.p8"}
mi {"app_secret":"xxx","restricted_package_name":"xxx"}
hw {"app_id":"xxx","client_secret":"xxx"}
mz {"app_id":"xxx","app_secret":"xxx"}
oppo {"app_key":"xxx","master_secret":"xxx"}
vivo {"app_id":"xxx","app_key":"xxx","app_secret":"xxx"}

具体传输方式

channel device_token来源 请求方式 URL Content-Type request-header 消息体结构 device_token位置
iOS device_token POST https://api.development.push.apple.com/3/device/+token application/json "apns-topic":bundleID
"Authorization":"bearer "+ authtoken
json格式 连接到URL后面
小米 regId POST https://api.xmpush.xiaomi.com/v3/message/regid application/x-www-form-urlencoded "Authorization": appSecret key:value格式 在消息体中,作为key传输
华为 token POST https://push-api.cloud.huawei.com/v1/messages:send application/json "Authorization": "Bearer " + authtoken json格式 在json消息体中,数组格式
魅族 pushId POST http://server-api-push.meizu.com/garcia/api/server/push/varnished/pushByPushId application/x-www-form-urlencoded 没有token,消息体中有sign的key-value key:value格式 在消息体中,作为key传输
oppo pushId POST https://api.push.oppomobile.com/server/v1/message/notification/unicast_batch application/x-www-form-urlencoded "auth_token": authtoken key:value格式 在messages的json消息体中,分配到每个消息数组中
vivo regId POST https://api-push.vivo.com.cn/message/send application/json "authToken" = authToken json格式 在json消息体中

参考来源

Local and Remote Notification Programming Guide https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html#//apple_ref/doc/uid/TP40008194-CH11-SW1 hw推送服务-HTTPS下行消息 https://developer.huawei.com/consumer/cn/doc/HMSCore-References-V5/https-send-api-0000001050986197-V5#ZH-CN_TOPIC_0000001050986197__section723545214380

Documentation

Index

Constants

View Source
const (
	HTTPOK      = 200
	HTTPERROR   = 500
	SendSuccess = 0
	SendError   = 1
)
View Source
const (
	HWProductionHost = "https://push-api.cloud.huawei.com/v1/"

	HWMessageURL = "/messages:send"

	HWTokenURL  = "https://oauth-login.cloud.huawei.com/oauth2/v3/token"
	HWGrantType = "client_credentials"
)
View Source
const (
	HWSuccess              = "80000000"
	HWPartTokenSendSuccess = "80100000"
)
View Source
const (
	IOSProductionHost = "https://api.development.push.apple.com"
	IOSMessageURL     = "/3/device/"
	IOSTokenTimeout   = 3000
)
View Source
const (
	IOSSuccess                     = 200 // 成功
	IOSErrorRequest                = 400 // 错误的请求
	IOSErrorAuthToken              = 403
	IOSErrorMethod                 = 405
	IOSTimeOutDeviceToken          = 410
	IOSNotificationPayloadTooLarge = 413
	IOSTooManyRequest              = 429
	IOSInternalServerError         = 500
	IOSServerUnavailable           = 503
)
View Source
const (
	MiProductionHost  = "https://api.xmpush.xiaomi.com"
	MiMessageRegIdURL = "/v3/message/regid"
	MiMultiRegIdURL   = "/v2/multi_messages/regids"
)
View Source
const (
	MiSuccess             = 0
	MiNetWorkErrorTimeOut = -1
)
View Source
const (
	MZProductionHost = "http://server-api-push.meizu.com"

	MZMessageURL = "/garcia/api/server/push/varnished/pushByPushId" // pushId推送
	MZToAppURL   = "/garcia/api/server/push/pushTask/pushToApp"
)
View Source
const (
	MZSuccess        = "200"
	MZOtherError     = "500"
	MZSystemError    = "1001"
	MZServerBusy     = "1003"
	MZParamError     = "1005"
	MZAuthTokenError = "1006"
	MZAppIdIllegal   = "110000"
	MZAppKeyIllegal  = "110001"
	MZParamEmpty     = "110004"
	MZAppInBlackList = "110009"
)
View Source
const (
	OPPOProductionHost = "https://api.push.oppomobile.com"
	OPPOMessageURL     = "/server/v1/message/notification/unicast_batch" // pushId推送
	OPPOTokenURL       = "/server/v1/auth"
)
View Source
const (
	OPPOSuccess                     = 0
	OPPOServiceInFlowControl        = -2
	OPPOServiceCurrentlyUnavailable = -1
	OPPOInvalidAuthToken            = 11
	OPPOHttpActionNotAllowed        = 12
	OPPOAppCallLimited              = 13
)
View Source
const (
	VIVOProductUrl   = "https://api-push.vivo.com.cn"
	VIVOAuthUrl      = "/message/auth"
	VIVOSingleSend   = "/message/send"
	VIVOGroupTask    = "/message/saveListPayload"
	VIVOGroupSend    = "/message/pushToList"
	VIVOTokenTimeout = 3600
)
View Source
const (
	VIVOSuccess = 0
	V10050      = "alias和regId不能为空"
	V10051      = "暂不支持该消息类型"
	V10054      = "notifyType不合法"
	V10055      = "title不能为空"
	V10056      = "title不能超过40个字符串"
)
View Source
const (
	VIVOAuthSuccess          = 0
	VIVOAuthAppIdEmpty       = 10200
	VIVOAuthAppKeyEmpty      = 10201
	VIVOAuthAppKeyIllegal    = 10202
	VIVOAuthTimestampEmpty   = 10203
	VIVOAuthSignEmpty        = 10204
	VIVOAuthAppIdNotExist    = 10205
	VIVOAuthSignError        = 10206
	VIVOAuthTimestampIllegal = 10207
	VIVOAuthExceededLimit    = 10250
)

Variables

View Source
var (
	AvailableChannel = []string{"ios", "mi", "hw", "oppo", "vivo", "mz"}
)

Functions

func GetAuthTokenIOS

func GetAuthTokenIOS(authTokenPath string, keyID string, teamID string) (string, error)

func GetAuthTokenV

func GetAuthTokenV(appId, appKey, appSecret string) string

Types

type Alert

type Alert struct {
	Title string `json:"title"`
	Body  string `json:"body"`
}

type Android

type Android struct {
	CollapseKey  int                 `json:"collapse_key"` // 缓存。0-只缓存新的一条,-1对所有离线消息都缓存、1-100分组缓存
	Notification AndroidNotification `json:"notification"`
}

type AndroidNotification

type AndroidNotification struct {
	Title       string      `form:"title" json:"title"`
	Body        string      `form:"body" json:"body"`
	Icon        string      `json:"icon"` // 小图标
	Tag         string      `json:"tag"`  // 消息标签
	ClickAction ClickAction `json:"click_action"`
}

type Aps

type Aps struct {
	Alert Alert `json:"alert"`
	Badge int   `json:"badge"` // 右上角小图标
}

type AuthTokenResult

type AuthTokenResult struct {
	Result    int    `json:"result"`
	Desc      string `json:"desc"`
	AuthToken string `json:"authToken"`
}

type BadgeNotification

type BadgeNotification struct {
	AddNum int    `json:"add_num"`
	Class  string `json:"class"`   // 应用入口Activity类全路径。 样例:com.example.hmstest.MainActivity
	SetNum int    `json:"set_num"` // 角标设置数字,大于等于0小于100的整数。如果set_num与add_num同时存在时,以set_num为准
}

type ClickAction

type ClickAction struct {
	Type   int    `json:"type"`   // 1-打开应自定义页面、2-打开URL、3-打开应用APP
	Intent string `json:"intent"` // 自定义页面中intent的实现
	Url    string `json:"url"`
	Action string `json:"action"` // 设置通过action打开应用自定义页面时,本字段填写要打开的页面activity对应的action。
}

type ClickTypeInfo

type ClickTypeInfo struct {
	ClickType       int               `json:"clickType"`       // 点击动作 0-打开应用(默认)、1-打开应用页面、2-打开URI页面、3-应用客户端自定义
	Url             string            `json:"url"`             // clickType=2时必填
	Parameters      map[string]string `json:"parameters"`      // json 格式 非必填
	Activity        string            `json:"activity"`        // clickType=1时必填。格式:pkg.activity
	CustomAttribute string            `json:"customAttribute"` // clickType=3时必填
}

type Data

type Data struct {
	MessageId      string `json:"messageId"`
	RegistrationId string `json:"registrationId"`
	ErrorCode      int    `json:"errorCode"`
	ErrorMessage   string `json:"errorMessage"`
}

type ErrResult

type ErrResult struct {
	Reason string `json:"reason"`
}

type Extra

type Extra struct {
	NotifyEffect int    `json:"notify_effect"` // “1″:通知栏点击后打开app的Launcher Activity。 “2″:通知栏点击后打开app的任一Activity(开发者还需要传入extra.intent_uri)。 “3″:通知栏点击后打开网页(开发者还需要传入extra.web_uri)。
	IntentUri    string `json:"intent_uri"`
	WebUri       string `json:"web_uri"`
}

type GroupMessage

type GroupMessage struct {
	NotifyType  int    `json:"notifyType"` // 通知类型 1.无、2-响铃、3-振动、4-响铃和振动
	Title       string `json:"title"`
	Content     string `json:"content"`
	TimeToLive  int    `json:"timeToLive"`  // 消息保留时长 单位:秒,取值至少60秒,最长7天。当值为空时,默认一天
	SkipType    int    `json:"skipType"`    // 跳转类型。1-打开APP首页、2-打开链接、3-自定义、4-打开APP内指定页面
	SkipContent string `json:"skipContent"` // 跳转类型为2时,跳转内容最大1000个字符,跳转类型为3或4时,跳转内容最大1024个字符,skipType传3需要在onNotificationMessageClicked回调函数中自己写处理逻辑
	//ClientCustomMap string `json:"clientCustomMap"` // 客户端自定义键值对
	RequestId string `json:"requestId"` // 消息唯一标识
}

type HW

type HW struct {
	sync.Mutex
	AppId        string `json:"app_id"`
	ClientSecret string `json:"client_secret"`
}

func (*HW) SendMessage

func (h *HW) SendMessage(m *Message, token []string) (*Response, error)

type HWFields

type HWFields struct {
	Message MessageNotification `json:"message"`
}

type HWResult

type HWResult struct {
	Code      string `json:"code"`                //80000000表示成功,非80000000表示失败
	Msg       string `json:"msg"`                 //错误码描述
	RequestId string `json:"requestId,omitempty"` //请求标识。
}

type IOS

type IOS struct {
	sync.Mutex
	KeyId         string `json:"key_id"`
	TeamId        string `json:"team_id"`
	BundleId      string `json:"bundle_id"`
	AuthTokenPath string `json:"auth_token_path"`
	Bearer        string `json:"bearer"`
	IssuedAt      int64  `json:"issued_at"`
}

func (*IOS) Expired

func (i *IOS) Expired() bool

func (*IOS) Generate

func (i *IOS) Generate() (bool, error)

func (*IOS) SendMessage

func (i *IOS) SendMessage(m *Message, token []string) (*Response, error)

type IOSFields

type IOSFields struct {
	Aps Aps `json:"aps"`
}

type IOSResult

type IOSResult struct {
	ApnsId string `json:"apns-id"`
	Status int    `json:"status"`
	Reason string `json:"reason"`
}

type MI

type MI struct {
	AppSecret             string `json:"app_secret"`
	RestrictedPackageName string `json:"restricted_package_name"`
}

func (*MI) SendMessage

func (mi *MI) SendMessage(m *Message, regIds []string) (*Response, error)

type MIFields

type MIFields struct {
	Payload               string `json:"payload"`                 //消息内容
	RestrictedPackageName string `json:"restricted_package_name"` //支持多包名
	Title                 string `json:"title"`                   //在通知栏的标题,长度小于16
	Description           string `json:"description"`             //在通知栏的描述,长度小于128
	NotifyType            string `json:"notify_type"`             //通知类型 可组合 (-1 Default_all,1 Default_sound,2 Default_vibrate(震动),4 Default_lights)
	NotifyId              string `json:"notify_id"`               //同一个notifyId在通知栏只会保留一条
	TimeToLive            string `json:"time_to_live"`            //可选项,当用户离线是,消息保留时间,默认两周,单位ms
	TimeToSend            string `json:"time_to_send"`            //可选项,定时发送消息,用自1970年1月1日以来00:00:00.0 UTC时间表示(以毫秒为单位的时间)。
	Extra                 string `json:"extra"`
}

type MIResult

type MIResult struct {
	Code        int64       `json:"code"`                  //0表示成功,非0表示失败
	Result      string      `json:"result"`                //"ok" 表示成功,"error" 表示失败
	Description string      `json:"description,omitempty"` //对发送消息失败原因的解释
	Info        string      `json:"info,omitempty"`        //详细信息
	Reason      string      `json:"reason,omitempty"`      //失败原因
	Data        *ResultData `json:"data,omitempty"`        //本身就是一个json字符串
}

type MZ

type MZ struct {
	AppSecret string `json:"app_secret"`
	AppId     string `json:"app_id"`
}

func (*MZ) SendMessage

func (mz *MZ) SendMessage(m *Message, pushIds []string) (*Response, error)

type MZResult

type MZResult struct {
	Code     string `json:"code"`
	Message  string `json:"message"`
	Value    string `json:"value"`
	Redirect string `json:"redirect"`
	MsgId    string `json:"msgId"`
}

type Message

type Message struct {
	Title        string
	Desc         string
	ApnsId       string
	ClickType    string
	ClickContent string
	Err          error
}

消息体

func NewMessage

func NewMessage() *Message

func (*Message) SetApnsId

func (m *Message) SetApnsId(str string) *Message

func (*Message) SetClickContent

func (m *Message) SetClickContent(str string) *Message

func (*Message) SetClickType

func (m *Message) SetClickType(str string) *Message

func (*Message) SetContent

func (m *Message) SetContent(str string) *Message

func (*Message) SetTitle

func (m *Message) SetTitle(str string) *Message

type MessageFields

type MessageFields struct {
	TargetType   int              `json:"target_type"`
	TargetValue  string           `json:"target_value"`
	Notification OPPONotification `json:"notification"`
}

type MessageJson

type MessageJson struct {
	NoticeBarInfo    NoticeBarInfo    `json:"noticeBarInfo"`
	NoticeExpandInfo NoticeExpandInfo `json:"noticeExpandInfo"`
	ClickTypeInfo    ClickTypeInfo    `json:"clickTypeInfo"`
	PushTimeInfo     PushTimeInfo     `json:"pushTimeInfo"`
}

type MessageNotification

type MessageNotification struct {
	Notification Notification `form:"notification" json:"notification"`
	Android      Android      `form:"android" json:"android"`
	Token        []string     `json:"token"`
}

type MobileChannel

type MobileChannel interface {
	SendMessage(m *Message, pushId []string) (*Response, error)
}

type NoticeBarInfo

type NoticeBarInfo struct {
	NoticeBarType int    `json:"noticeBarType"` // 通知栏样式 0-标准 2-安卓原生 【int 非必填,值为0】
	Title         string `json:"title"`         // 推送标题 【string 必填,字数限制1-32字符】
	Content       string `json:"content"`       // 推送内容 【string 必填,字数限制1-100字符】
}

type NoticeExpandInfo

type NoticeExpandInfo struct {
	NoticeExpandType    int    `json:"noticeExpandType"`    // 0-标准、1-文本 int 非必填
	NoticeExpandContent string `json:"noticeExpandContent"` // 展示内容、为文本时必填
}

type Notification

type Notification struct {
	Title string `form:"title" json:"title"`
	Body  string `form:"body" json:"body"`
}

type OPPO

type OPPO struct {
	AppKey       string `json:"app_key"`
	MasterSecret string `json:"master_secret"`
}

func (*OPPO) SendMessage

func (o *OPPO) SendMessage(m *Message, pushIds []string) (*Response, error)

type OPPONotification

type OPPONotification struct {
	AppMessageId        string `json:"app_message_id"`   // 消息tag
	Style               int    `json:"style"`            // 1-标准样式(默认1) 2-长文本 3-大图
	BigPictureId        string `json:"big_picture_id"`   // 大图id
	SmallPictureId      string `json:"small_picture_id"` // 图标
	Title               string `json:"title"`
	SubTitle            string `json:"sub_title"`
	Content             string `json:"content"`
	ClickActionType     int    `json:"click_action_type"`     //点击动作类型0,启动应用;1,打开应用内页(activity的intent action);2,打开网页;4,打开应用内页(activity);【非必填,默认值为0】;5,Intent scheme URL
	ClickActionActivity string `json:"click_action_activity"` // 应用内页地址【click_action_type为1/4/ 时必填,长度500】
	ClickActionUrl      string `json:"click_action_url"`      // 网页地址或【click_action_type为2与5时必填
	ActionParameters    string `json:"action_parameters"`     // 传递给网页或应用的参数 json 格式
}

type OPPOResult

type OPPOResult struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    []Data `json:"data"`
}

type OPPOTokenData

type OPPOTokenData struct {
	AuthToken  string `json:"auth_token"`
	CreateTime int    `json:"create_time"`
}

type OPPOTokenResult

type OPPOTokenResult struct {
	Code    int           `json:"code"`
	Message string        `json:"message"`
	Data    OPPOTokenData `json:"data"`
}

type Payload

type Payload struct {
	PushTitle    string `json:"push_title"`
	PushBody     string `json:"push_body"`
	IsShowNotify string `json:"is_show_notify"`
	Ext          string `json:"ext"`
}

消息payload,根据业务自定义

type PushTimeInfo

type PushTimeInfo struct {
	OffLine   int `json:"offLine"`   // 是否是离线消息 0-否、1-是(默认)
	ValidTime int `json:"validTime"` // 有效时长(1-72小时内的正整数,默认24
}

type Response

type Response struct {
	Code      int
	Reason    string
	ApnsId    string
	TimeStamp time.Time
}

type ResultData

type ResultData struct {
	BadRegIds string `json:"bad_regIds"` //推送失败的ids
	Id        string `json:"id"`         //消息的Id
}

type Send

type Send struct {
	Channel  string
	PushId   []string
	PlatForm string
	Err      error
}

func NewSend

func NewSend() *Send

func (*Send) SendMessage

func (s *Send) SendMessage(message *Message) (*Response, error)

func (*Send) SetChannel

func (s *Send) SetChannel(channel string) *Send

设置渠道

func (*Send) SetPlatForm

func (s *Send) SetPlatForm(plat string) *Send

func (*Send) SetPushId

func (s *Send) SetPushId(pushId []string) *Send

设置推送用户

type TokenResult

type TokenResult struct {
	AccessToken string `json:"access_token"`
	ExpiresIn   int    `json:"expires_in"`
	TokenType   string `json:"token_type"`
}

type VFieldGroup

type VFieldGroup struct {
	RegIds    []string `json:"regIds"`
	TaskId    string   `json:"taskId"`
	RequestId string   `json:"requestId"`
}

type VFieldSingle

type VFieldSingle struct {
	RegId       string `json:"regId"`
	NotifyType  int    `json:"notifyType"` // 通知类型 1.无、2-响铃、3-振动、4-响铃和振动
	Title       string `json:"title"`
	Content     string `json:"content"`
	TimeToLive  int    `json:"timeToLive"`  // 消息保留时长 单位:秒,取值至少60秒,最长7天。当值为空时,默认一天
	SkipType    int    `json:"skipType"`    // 跳转类型。1-打开APP首页、2-打开链接、3-自定义、4-打开APP内指定页面
	SkipContent string `json:"skipContent"` // 跳转类型为2时,跳转内容最大1000个字符,跳转类型为3或4时,跳转内容最大1024个字符,skipType传3需要在onNotificationMessageClicked回调函数中自己写处理逻辑
	//ClientCustomMap string `json:"clientCustomMap"` // 客户端自定义键值对
	RequestId string `json:"requestId"` // 消息唯一标识
}

type VIVO

type VIVO struct {
	sync.Mutex
	AppID     string `json:"app_id"`
	AppKey    string `json:"app_key"`
	AppSecret string `json:"app_secret"`
	AuthToken string `json:"auth_token"`
	IssuedAt  int64  `json:"issued_at"`
}

func (*VIVO) Expired

func (v *VIVO) Expired() bool

func (*VIVO) Generate

func (v *VIVO) Generate() (bool, error)

func (*VIVO) SendMessage

func (v *VIVO) SendMessage(m *Message, pushId []string) (*Response, error)

type VResult

type VResult struct {
	Result      int    `json:"result"`      // 状态码
	Desc        string `json:"desc"`        // 文字描述接口调用情况
	TaskId      string `json:"taskId"`      // 任务编号
	InvalidUser string `json:"invalidUser"` // 非法用户信息
}

Jump to

Keyboard shortcuts

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