ippanel

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Feb 18, 2020 License: BSD-3-Clause Imports: 10 Imported by: 0

README

IPPANEL SMS api SDK

This repository contains open source Go client for ippanel api. Documentation can be found at: http://docs.ippanel.com.

Build Status GoDoc

Installation

If you are using go modules, just install it with go mod install or go build ., Otherwise you can use go get ./...

go get github.com/ippanel/go-rest-sdk

Examples

After installing ippanel sdk with above methods, you can import it in your project like this:

import "github.com/ippanel/go-rest-sdk"

For using sdk, after importing, you have to create a client instance that gives you available methods on API

// you api key that generated from panel
apiKey := "api-key"

// create client instance
sms := ippanel.New(apiKey)

...
Credit check
// return float64 type credit amount
credit, err := sms.GetCredit()
if err != nil {
    t.Error("error occurred ", err)
}
Send one to many

For sending sms, obviously you need originator number, recipients and message.

bulkID, err := sms.Send("+9810001", []string{"98912xxxxxxx"}, "ippanel is awesome")
if err != nil {
    t.Error("error occurred ", err)
}

If send is successful, a unique tracking code returned and you can track your message status with that.

Get message summery
bulkID := "message-tracking-code"

message, err := sms.GetMessage(bulkID)
if err != nil {
    t.Error("error occurred ", err)
}

fmt.Println(message.Status) // get message status
fmt.Println(message.Cost)   // get message cost
fmt.Println(message.Payack) // get message payback
Get message delivery statuses
bulkID := "message-tracking-code"
// pagination params for defining fetch size and offset
paginationParams := ippanel.ListParams{Page: 0, Limit: 10}

statuses, paginationInfo, err := sms.FetchStatuses(bulkID, paginationParams)
if err != nil {
    t.Error("error occurred ", err)
}

// you can loop in messages statuses list
for _, status := range statuses {
    fmt.Printf("Recipient: %s, Status: %s", status.Recipient, status.Status)
}

fmt.Println("Total: ", paginationInfo.Total)
Inbox fetch

fetch inbox messages

paginationParams := ippanel.ListParams{Page: 0, Limit: 10}

messages, paginationInfo, err := sms.FetchInbox(paginationParams)
if err != nil {
    t.Error("error occurred ", err)
}
Pattern create

For sending messages with predefined pattern(e.g. verification codes, ...), you hav to create a pattern. a pattern at least have a parameter. parameters defined with %param_name%.

pattern, err := sms.CreatePattern("%name% is awesome", false)
if err != nil {
    t.Error("error occurred ", err)
}
Send with pattern
patternValues := map[string]string{
    "name": "IPPANEL",
}

bulkID, err := sms.SendPattern(
    "t2cfmnyo0c",   // pattern code
    "+9810001",     // originator
    "98912xxxxxxx", // recipient
    patternValues,  // pattern values
)
if err != nil {
    t.Error("error occurred ", err)
}
Error checking
_, err := sms.Send("9810001", []string{"98912xxxxx"}, "ippanel is awesome")
if err != nil {
    // check that error is type of ippanel standard error
    if e, ok := err.(Error); ok {
        // after casting, you have access to error code and error message
        switch e.Code {
        // its special type of error, occurred when POST form data validation failed
        case ErrUnprocessableEntity:
            // for accessing field level errors you have to cast it to FieldErrors type
            fieldErrors := e.Message.(FieldErrs)
            for field, fieldError := range fieldErrors {
                t.Log(field, fieldError)
            }
        // in other error types, e.Message is string
        default:
            errMsg := e.Message.(string)
            t.Log(errMsg)
        }
    }
}

Documentation

Overview

Package ippanel is an official library for working with ippanel sms api. brief documentation for ippanel sms api provided at http://docs.ippanel.com

Index

Constants

View Source
const (
	// ClientVersion is used in User-Agent request header to provide server with API level.
	ClientVersion = "1.0.1"

	// Endpoint points you to Ippanel REST API.
	Endpoint = "http://rest.ippanel.com/v1"
)

Variables

View Source
var (
	// ErrUnexpectedResponse is used when there was an internal server error and nothing can be done at this point.
	ErrUnexpectedResponse = errors.New("The Ippanel API is currently unavailable")
)

Functions

func ParseErrors

func ParseErrors(res *BaseResponse) error

ParseErrors ...

Types

type BaseResponse

type BaseResponse struct {
	Status string          `json:"status"`
	Code   ResponseCode    `json:"code"`
	Data   json.RawMessage `json:"data"`
	Meta   *PaginationInfo `json:"meta"`
}

BaseResponse base response model

type Error

type Error struct {
	Code    ResponseCode
	Message interface{}
}

Error general service error

func (Error) Error

func (e Error) Error() string

Error implement error interface

type FieldErr

type FieldErr struct {
	Code string `json:"code"`
	Err  string `json:"err"`
}

FieldErr input field level error

type FieldErrs

type FieldErrs map[string][]FieldErr

FieldErrs input field level errors

type InboxMessage

type InboxMessage struct {
	Number    string    `json:"number"`
	Message   string    `json:"message"`
	Sender    string    `json:"sender"`
	CreatedAt time.Time `json:"time"`
	Type      string    `json:"type"`
}

InboxMessage inbox message

type Ippanel

type Ippanel struct {
	AccessKey string
	Client    *http.Client
	BaseURL   *url.URL
}

Ippanel ...

func New

func New(accesskey string) *Ippanel

New create new ippanel sms instance

func (*Ippanel) CreatePattern

func (sms *Ippanel) CreatePattern(pattern string, isShared bool) (*Pattern, error)

CreatePattern create new pattern

func (*Ippanel) FetchInbox

func (sms *Ippanel) FetchInbox(pp ListParams) ([]InboxMessage, *PaginationInfo, error)

FetchInbox fetch inbox messages list

func (*Ippanel) FetchStatuses

func (sms *Ippanel) FetchStatuses(bulkID int64, pp ListParams) ([]MessageRecipient, *PaginationInfo, error)

FetchStatuses get message recipients statuses

func (*Ippanel) GetCredit

func (sms *Ippanel) GetCredit() (float64, error)

GetCredit get credit for user

func (*Ippanel) GetMessage

func (sms *Ippanel) GetMessage(bulkID int64) (*Message, error)

GetMessage get a message by bulk_id

func (*Ippanel) Send

func (sms *Ippanel) Send(originator string, recipients []string, message string) (int64, error)

Send send a message

func (*Ippanel) SendPattern

func (sms *Ippanel) SendPattern(patternCode string, originator string, recipient string, values map[string]string) (int64, error)

SendPattern send a message with pattern

type ListParams

type ListParams struct {
	Limit int64 `json:"limit"`
	Page  int64 `json:"page"`
}

ListParams ...

type Message

type Message struct {
	BulkID               int64               `json:"bulk_id"`
	Number               string              `json:"number"`
	Message              string              `json:"message"`
	Status               MessageStatus       `json:"status"`
	Type                 MessageType         `json:"type"`
	ConfirmState         MessageConfirmState `json:"confirm_state"`
	CreatedAt            time.Time           `json:"created_at"`
	SentAt               time.Time           `json:"sent_at"`
	RecipientsCount      int64               `json:"recipients_count"`
	ValidRecipientsCount int64               `json:"valid_recipients_count"`
	Page                 int64               `json:"page"`
	Cost                 float64             `json:"cost"`
	PaybackCost          float64             `json:"payback_cost"`
	Description          string              `json:"description"`
}

Message message model

type MessageConfirmState

type MessageConfirmState string

MessageConfirmState message confirm state

const (
	// MessageConfirmeStatePending pending
	MessageConfirmeStatePending MessageConfirmState = "pending"
	// MessageConfirmeStateConfirmed confirmed
	MessageConfirmeStateConfirmed MessageConfirmState = "confirmed"
	// MessageConfirmeStateRejected rejected
	MessageConfirmeStateRejected MessageConfirmState = "rejected"
)

type MessageRecipient

type MessageRecipient struct {
	Recipient string `json:"recipient"`
	Status    string `json:"status"`
}

MessageRecipient message recipient status

type MessageStatus

type MessageStatus string

MessageStatus message status

const (
	// MessageStatusActive ...
	MessageStatusActive MessageStatus = "active"
)

TODO: Add other message status codes

type MessageType

type MessageType string

MessageType message type

const (
	// MessageTypeNormal normal message
	MessageTypeNormal MessageType = "normal"
)

TODO: Add other message types

type PaginationInfo

type PaginationInfo struct {
	Total int64   `json:"total"`
	Limit int64   `json:"limit"`
	Page  int64   `json:"page"`
	Pages int64   `json:"pages"`
	Prev  *string `json:"prev"`
	Next  *string `json:"next"`
}

PaginationInfo ...

type Pattern

type Pattern struct {
	Code     string        `json:"code"`
	Status   PatternStatus `json:"status"`
	Message  string        `json:"message"`
	IsShared bool          `json:"is_shared"`
}

Pattern pattern

type PatternStatus

type PatternStatus string

PatternStatus ...

const (
	// PatternStatusActive active
	PatternStatusActive PatternStatus = "active"
	// PatternStatusInactive inactive
	PatternStatusInactive PatternStatus = "inactive"
	// PatternStatusPending pending
	PatternStatusPending PatternStatus = "pending"
)

type ResponseCode

type ResponseCode string

ResponseCode api response code error type

const (
	// ErrCredential error when executing repository query
	ErrCredential ResponseCode = "10001"
	// ErrMessageBodyIsEmpty message body is empty
	ErrMessageBodyIsEmpty ResponseCode = "10002"
	// ErrUserLimitted user is limited
	ErrUserLimitted ResponseCode = "10003"
	// ErrNumberNotAssignedToYou line not assigned to you
	ErrNumberNotAssignedToYou ResponseCode = "10004"
	// ErrRecipientsEmpty recipients is empty
	ErrRecipientsEmpty ResponseCode = "10005"
	// ErrCreditNotEnough credit not enough
	ErrCreditNotEnough ResponseCode = "10006"
	// ErrNumberNotProfitForBulkSend line not profit for bulk send
	ErrNumberNotProfitForBulkSend ResponseCode = "10007"
	// ErrNumberDeactiveTemp line deactivated temporally
	ErrNumberDeactiveTemp ResponseCode = "10008"
	// ErrMaximumRecipientExceeded maximum recipients number exceeded
	ErrMaximumRecipientExceeded ResponseCode = "10009"
	// ErrGatewayOffline gateway is offline
	ErrGatewayOffline ResponseCode = "10010"
	// ErrNoPricing pricing not defined for user
	ErrNoPricing ResponseCode = "10011"
	// ErrTicketIsInvalid ticket is invalid
	ErrTicketIsInvalid ResponseCode = "10012"
	// ErrAccessDenied access denied
	ErrAccessDenied ResponseCode = "10013"
	// ErrPatternIsInvalid pattern is invalid
	ErrPatternIsInvalid ResponseCode = "10014"
	// ErrPatternParamettersInvalid pattern parameters is invalid
	ErrPatternParamettersInvalid ResponseCode = "10015"
	// ErrPatternIsInactive pattern is inactive
	ErrPatternIsInactive ResponseCode = "10016"
	// ErrPatternRecipientInvalid pattern recipient invalid
	ErrPatternRecipientInvalid ResponseCode = "10017"
	// ErrItsTimeToSleep send time is 8-23
	ErrItsTimeToSleep ResponseCode = "10019"
	// ErrDocumentsNotApproved one/all of users documents not approved
	ErrDocumentsNotApproved ResponseCode = "10021"
	// ErrInternal internal error
	ErrInternal ResponseCode = "10022"
	// ErrNumberNotFound provided number not valid
	ErrNumberNotFound ResponseCode = "10023"
	// ErrGatewayDisabled gateway disabled
	ErrGatewayDisabled ResponseCode = "10024"

	// ErrUnprocessableEntity inputs have some problems
	ErrUnprocessableEntity ResponseCode = "422"
	// ErrUnauthorized unauthorized
	ErrUnauthorized ResponseCode = "1401"
	// ErrKeyNotValid api key is not valid
	ErrKeyNotValid ResponseCode = "1402"
	// ErrKeyRevoked api key revoked
	ErrKeyRevoked ResponseCode = "1403"
)

Jump to

Keyboard shortcuts

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