nexmo

package module
Version: v2.0.0+incompatible Latest Latest
Warning

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

Go to latest
Published: Feb 2, 2018 License: BSD-2-Clause Imports: 9 Imported by: 2

README

gonexmo GoDoc

gonexmo is a Go library tailored for sending SMS's with Nexmo.

Installation

Assuming you have a working Go environment, installation is simple:

go get "gopkg.in/njern/gonexmo.v2"

You can take a look at the documentation locally with:

godoc github.com/njern/gonexmo

The included tests in gonexmo_test.go also illustrate usage of the package.

Note: You must enter valid API credentials and a valid phone number in gonexmo_test.go or the tests will fail! I didn't feel like draining my own Nexmo account or receiving thousands of test SMS's - sorry :)

Usage

import "gopkg.in/njern/gonexmo.v2"

nexmoClient, _ := nexmo.NewClient("API_KEY_GOES_HERE", "API_SECRET_GOES_HERE")

// Test if it works by retrieving your account balance
balance, err := nexmoClient.Account.GetBalance()

// Send an SMS
// See https://docs.nexmo.com/index.php/sms-api/send-message for details.
message := &nexmo.SMSMessage{
	From:           "go-nexmo",
    To:              "00358123412345",
	Type:            nexmo.Text,
	Text:            "Gonexmo test SMS message, sent at " + time.Now().String(),
	ClientReference: "gonexmo-test " + strconv.FormatInt(time.Now().Unix(), 10),
	Class:           nexmo.Standard,
}

messageResponse, err := nexmoClient.SMS.Send(message)

Receiving inbound messages

import (
    "gopkg.in/njern/gonexmo.v2"
    "log"
    "net/http"
)

func main() {
    messages := make(chan *nexmo.RecvdMessage)
    h := nexmo.NewMessageHandler(messages,false)

    go func() {
        for {
            msg := <-messages
            log.Printf("%v\n",msg)
        }
    }()

    // Set your Nexmo callback url to http://<domain or ip>:8080/get/
    http.HandleFunc("/get/", h)
    if err := http.ListenAndServe(":8080", nil); err != nil {
        log.Fatal("ListenAndServe: ", err)
    }

}

Future plans

  • Implement the rest of the Nexmo API

How can you help?

  • Let me know if you're using gonexmo by dropping me a line at [github user name] at walkbase.com
  • Let me know about any bugs / annoyances the same way

Documentation

Overview

Package nexmo implements a simple client library for accessing the Nexmo API.

Usage is simple. Create a nexmo.Client instance with NewClientFromAPI(), provide your API key and API secret. Compose a new Message and then call Client.SMS.Send(Message). The API will return a MessageResponse which you can use to see if your message went through, how much it cost, etc.

Index

Constants

View Source
const (
	TextMessage = iota + 1
	UnicodeMessage
	BinaryMessage
)

Message types

View Source
const (
	Text    = "text"
	Binary  = "binary"
	WAPPush = "wappush"
	Unicode = "unicode"
	VCal    = "vcal"
	VCard   = "vcard"
)

SMS message types.

Variables

This section is empty.

Functions

func IsTrustedIP

func IsTrustedIP(ipStr string) bool

IsTrustedIP returns true if the provided IP address came from a trusted Nexmo server.

func NewDeliveryHandler

func NewDeliveryHandler(out chan *DeliveryReceipt, verifyIPs bool) http.HandlerFunc

NewDeliveryHandler creates a new http.HandlerFunc that can be used to listen for delivery receipts from the Nexmo server. Any receipts received will be decoded nad passed to the out chan.

func NewMessageHandler

func NewMessageHandler(out chan *ReceivedMessage, verifyIPs bool) http.HandlerFunc

NewMessageHandler creates a new http.HandlerFunc that can be used to listen for new messages from the Nexmo server. Any new messages received will be decoded and passed to the out chan.

Types

type Account

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

Account represents the user's account. Used when retrieving e.g current balance.

func (*Account) GetBalance

func (nexmo *Account) GetBalance() (float64, error)

GetBalance retrieves the current balance of your Nexmo account in Euros (€)

type Client

type Client struct {
	Account    *Account
	SMS        *SMS
	USSD       *USSD
	Verify     *Verification
	HTTPClient *http.Client
	// contains filtered or unexported fields
}

Client encapsulates the Nexmo functions. Should be created with NewClient()

func NewClient

func NewClient(apiKey, apiSecret string) (*Client, error)

NewClient creates a new Client type with the provided API key / API secret.

type DeliveryReceipt

type DeliveryReceipt struct {
	To              string    `json:"to"`
	NetworkCode     string    `json:"network-code"`
	MessageID       string    `json:"messageId"`
	MSISDN          string    `json:"msisdn"`
	Status          string    `json:"status"`
	ErrorCode       string    `json:"err-code"`
	Price           string    `json:"price"`
	SCTS            time.Time `json:"scts"`
	Timestamp       time.Time `json:"message-timestamp"`
	ClientReference string    `json:"client-ref"`
}

DeliveryReceipt is a delivery receipt for a single SMS sent via the Nexmo API

type MessageClass

type MessageClass int

MessageClass will be one of the following:

- Flash
- Standard
- SIMData
- Forward
const (
	// This type of SMS message is displayed on the mobile screen without being
	// saved in the message store or on the SIM card; unless explicitly saved
	// by the mobile user.
	Flash MessageClass = iota

	// This message is to be stored in the device memory or the SIM card
	// (depending on memory availability).
	Standard

	// This message class carries SIM card data. The SIM card data must be
	// successfully transferred prior to sending acknowledgment to the service
	// center. An error message is sent to the service center if this
	// transmission is not possible.
	SIMData

	// This message is forwarded from the receiving entity to an external
	// device. The delivery acknowledgment is sent to the service center
	// regardless of whether or not the message was forwarded to the external
	// device.
	Forward
)

SMS message classes.

func (MessageClass) String

func (m MessageClass) String() string

type MessageReport

type MessageReport struct {
	Status           ResponseCode `json:"status,string"`
	MessageID        string       `json:"message-id"`
	To               string       `json:"to"`
	ClientReference  string       `json:"client-ref"`
	RemainingBalance string       `json:"remaining-balance"`
	MessagePrice     string       `json:"message-price"`
	Network          string       `json:"network"`
	ErrorText        string       `json:"error-text"`
}

MessageReport is the "status report" for a single SMS sent via the Nexmo API

type MessageResponse

type MessageResponse struct {
	MessageCount int             `json:"message-count,string"`
	Messages     []MessageReport `json:"messages"`
}

MessageResponse contains the response from Nexmo's API after we attempt to send any kind of message. It will contain one MessageReport for every 160 chars sent.

type MessageType

type MessageType int

MessageType can be one of the following:

 - TextMessage
	- UnicodeMessage
	- BinaryMessage

func (MessageType) String

func (m MessageType) String() string

type ReceivedMessage

type ReceivedMessage struct {
	// Expected values are "text" or "binary".
	Type MessageType

	// Recipient number (your long virtual number).
	To string

	// Sender ID.
	MSISDN string

	// Optional unique identifier of a mobile network MCCMNC.
	NetworkCode string

	// Nexmo message ID.
	ID string

	// Time when Nexmo started to push the message to you.
	Timestamp time.Time

	// Parameters for conactenated messages:
	Concatenated bool // Set to true if a MO concatenated message is detected.
	Concat       struct {

		// Transaction reference. All message parts will share the same
		//transaction reference.
		Reference string

		// Total number of parts in this concatenated message set.
		Total int

		// The part number of this message withing the set (starts at 1).
		Part int
	}

	// When Type == text:
	Text string // Content of the message

	Keyword string // First word in the message body, typically used with short codes

	// Content of the message.
	Data []byte

	// User Data Header.
	UDH []byte
}

ReceivedMessage represents a message that was received from the Nexmo API.

type ResponseCode

type ResponseCode int

A ResponseCode will be returned whenever an SMSMessage is sent.

const (
	ResponseSuccess ResponseCode = iota
	ResponseThrottled
	ResponseMissingParams
	ResponseInvalidParams
	ResponseInvalidCredentials
	ResponseInternalError
	ResponseInvalidMessage
	ResponseNumberBarred
	ResponsePartnerAcctBarred
	ResponsePartnerQuotaExceeded
	ResponseUnused //This is not used  yet.Left blank by  Nexmo for the time being.
	ResponseRESTNotEnabled
	ResponseMessageTooLong
	ResponseCommunicationFailed
	ResponseInvalidSignature
	ResponseInvalidSenderAddress
	ResponseInvalidTTL
	ResponseFacilityNotAllowed
	ResponseInvalidMessageClass
)

Possible response codes

func (ResponseCode) String

func (c ResponseCode) String() string

String implements the fmt.Stringer interface

type SMS

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

SMS represents the SMS API functions for sending text messages.

func (*SMS) Send

func (c *SMS) Send(msg *SMSMessage) (*MessageResponse, error)

Send the message using the specified SMS client.

type SMSMessage

type SMSMessage struct {
	From                 string       `json:"from"`
	To                   string       `json:"to"`
	Type                 string       `json:"type"`
	Text                 string       `json:"text,omitempty"`              // Optional.
	StatusReportRequired int          `json:"status-report-req,omitempty"` // Optional.
	ClientReference      string       `json:"client-ref,omitempty"`        // Optional.
	NetworkCode          string       `json:"network-code,omitempty"`      // Optional.
	VCard                string       `json:"vcrad,omitempty"`             // Optional.
	VCal                 string       `json:"vcal,omitempty"`              // Optional.
	TTL                  int          `json:"ttl,omitempty"`               // Optional.
	Class                MessageClass `json:"message-class,omitempty"`     // Optional.
	Body                 []byte       `json:"body,omitempty"`              // Required for Binary message.
	UDH                  []byte       `json:"udh,omitempty"`               // Required for Binary message.

	Title    string `json:"title,omitempty"`    // Title shown to recipient
	URL      string `json:"url,omitempty"`      // WAP Push URL
	Validity int    `json:"validity,omitempty"` // Duration WAP Push is available in milliseconds
	// contains filtered or unexported fields
}

SMSMessage defines a single SMS message.

func (*SMSMessage) MarshalJSON

func (m *SMSMessage) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaller interface

type USSD

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

USSD represents the USSD API functions for sending USSD push and prompt messages.

func (*USSD) Send

func (c *USSD) Send(msg *USSDMessage) (*MessageResponse, error)

Send the message using the specified USSD client.

type USSDMessage

type USSDMessage struct {
	From                 string
	To                   string
	Text                 string
	StatusReportRequired bool   // Optional.
	ClientReference      string // Optional.
	NetworkCode          string // Optional.

	// Optional: If true, message will be a USSD prompt type,
	// otherwise it will be a push.
	Prompt bool
}

USSDMessage represents a single USSD message.

type Verification

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

Verification wraps a client to be able to use local verify methods.

func (*Verification) Check

Check (by sending a PIN to a user) whether a user can be contacted at his given phone number. https://developer.nexmo.com/api/verify#verify-check

func (*Verification) Search

Search sends the verify search request to Nexmo. https://developer.nexmo.com/api/verify#verify-search

func (*Verification) Send

Send makes the actual HTTP request to the endpoint and returns the response.

type VerifyCheckRequest

type VerifyCheckRequest struct {
	RequestID string `json:"request_id"`
	Code      string `json:"code"`
	IPAddress string `json:"ip_address,omitempty"`
	// contains filtered or unexported fields
}

A VerifyCheckRequest is sent to Nexmo when we want to verify a user has the phone number he says he does.

func (*VerifyCheckRequest) MarshalJSON

func (m *VerifyCheckRequest) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface

type VerifyCheckResponse

type VerifyCheckResponse struct {
	Status    ResponseCode `json:"status,string"`
	EventID   string       `json:"event_id"`
	Price     string       `json:"price"`
	Currency  string       `json:"currency"`
	ErrorText string       `json:"error_text"`
}

A VerifyCheckResponse is received from Nexmo after verifying a user has the phone number he says he does.

type VerifyMessageRequest

type VerifyMessageRequest struct {
	Number        string `json:"number"`
	Brand         string `json:"brand"`
	SenderID      string `json:"sender_id,omitempty"`
	Country       string `json:"country,omitempty"`
	Language      string `json:"lg,omitempty"`
	CodeLength    int    `json:"code_length,omitempty"`
	PINExpiry     int    `json:"pin_expiry,omitempty"`
	NextEventWait int    `json:"next_event_wait,omitempty"`
	// contains filtered or unexported fields
}

VerifyMessageRequest is the request struct for initiating the verification process for a phone number.

func (*VerifyMessageRequest) MarshalJSON

func (m *VerifyMessageRequest) MarshalJSON() ([]byte, error)

MarshalJSON returns a byte slice with the serialized JSON of the VerifyMessageRequest struct.

type VerifyMessageResponse

type VerifyMessageResponse struct {
	Status    ResponseCode `json:"status,string"`
	RequestID string       `json:"request_id"`
	ErrorText string       `json:"error_text"`
}

VerifyMessageResponse is the struct for the response from the verify endpoint.

type VerifySearchRequest

type VerifySearchRequest struct {
	RequestID string `json:"request_id,omitempty"`
	// contains filtered or unexported fields
}

A VerifySearchRequest is sent to Nexmo when searching for the status of a Verify request.

func (*VerifySearchRequest) MarshalJSON

func (m *VerifySearchRequest) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface

type VerifySearchResponse

type VerifySearchResponse struct {
	RequestID      string `json:"request_id"`
	AccountID      string `json:"account_id"`
	Number         string `json:"number"`
	SenderID       string `json:"sender_id"`
	DateSubmitted  string `json:"date_submitted"`
	DateFinalized  string `json:"date_finalized"`
	FirstEventDate string `json:"first_event_date"`
	LastEventDate  string `json:"last_event_date"`
	Status         string `json:"status"`
	Checks         []struct {
		DateReceived string `json:"date_received"`
		Code         string `json:"code"`
		Status       string `json:"status"`
		IPAddress    string `json:"ip_address,omitempty"`
	} `json:"checks"`
	Price     string `json:"price"`
	Currency  string `json:"currency"`
	ErrorText string `json:"error_text"`
}

A VerifySearchResponse is received from Nexmo in response to a VerifySearchRequest

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL