ajay1212122/sms-gateway-go-client
Sobre
Go client library sending and managing SMS through the SMS Gateway Android API
Ferramentas de desenvolvimentoO que você pode fazer
- Text, data, and outgoing MMS payloads with base64 attachment handling
- Per-message controls priority, device and SIM selection, delivery reports, TTL, validity windows, and scheduled delivery
- Inbox listing and refresh with pagination, filters, MMS attachment metadata, encryption-state flags, and disabled, individual, or batch webhook delivery
- Device listing and deletion, health checks, logs, and device settings through get, patch, and replace operations
Crescimento medido de estrelas
- em 24 h
- 0
- em 7 dias
- Coletando histórico
- em 15 dias
- Coletando histórico
- em 1 mês
- Coletando histórico
Variações líquidas em períodos sobrepostos, não totais diários. Medições ausentes ficam em branco. Estrelas indicam interesse, não qualidade.
README.md
OriginalA typed Go client the SMS Gateway Android API, exposing message dispatch, inbox operations, device management, and webhook handling through a small set of idiomatic packages. The library targets Go 1.22+ and relies solely on the standard library, so it stays dependency-light across production and test builds. Construct a client with smsgateway.NewClient, supply Basic or JWT credentials, and call methods such as Send or ListMessages with context-aware options.
📋 System Requirements
- Windows 10 or Windows 11
- PowerShell 5.1 or newer (already available on Windows)
- Active network connection
- No admin rights needed
Features
Typed Go client the SMS Gateway Android™ API covering message send, state retrieval, listing, filtering, sorting, content inclusion, and cancellation
- Text, data, and outgoing MMS payloads with base64 attachment handling
- Per-message controls priority, device and SIM selection, delivery reports, TTL, validity windows, and scheduled delivery
- Inbox listing and refresh with pagination, filters, MMS attachment metadata, encryption-state flags, and disabled, individual, or batch webhook delivery
- Device listing and deletion, health checks, logs, and device settings through get, patch, and replace operations
- Webhook registration with typed event constants and payload DTOs
- Webhook payload signature verification incoming requests, including an optional freshness window to reject stale timestamps
- JWT access-token generation, refresh, and revocation with scopes and TTL
- Optional versioned public-key fields on device and mobile request DTOs E2E key metadata
- CSR submission and status retrieval through the dedicated
capackage - Pluggable
*http.Clientand base URL overrides testing or private deployments - Go 1.22+ with zero runtime dependencies
Quick Start
Construct a client with a smsgateway.Config value, then call the message, inbox, device, or token methods on it. The zero-value client falls back to http.DefaultClient, so the only required fields are credentials or a token:
client:= smsgateway.NewClient(smsgateway.Config{
User: os.Getenv("ASG_USERNAME"),
Password: os.Getenv("ASG_PASSWORD"),
})
Send a text message and read back the queued state:
state, err:= client.Send(context.Background(), smsgateway.Message{
PhoneNumbers: []string{"+15555550100"},
TextMessage: &smsgateway.TextMessage{Text: "hello"},
})
if err!= nil {
log.Fatal(err)
}
log.Printf("queued: %s", state.ID)
Options are passed as functional arguments to Send and control phone-number validation and active-device filtering:
state, err:= client.Send(ctx, message,
smsgateway.WithSkipPhoneValidation(false),
smsgateway.WithDeviceActiveWithin(24),
)
List messages with pagination and content options:
limit:= 50
includeContent:= true
messages, total, err:= client.ListMessages(ctx, smsgateway.ListMessagesOptions{
PaginationOptions: smsgateway.PaginationOptions{Limit: &limit},
IncludeContent: &includeContent,
})
if err!= nil {
log.Fatal(err)
}
log.Printf("loaded %d of %d", len(messages), total)
Swap Basic credentials a bearer token when you need scoped access. Generate a token with a Basic-authenticated client, then build a second client from the returned value:
token, err:= client.GenerateToken(ctx, smsgateway.TokenRequest{
Scopes: []smsgateway.JWTScope{
smsgateway.ScopeMessagesSend,
smsgateway.ScopeMessagesRead,
},
TTL: 3600,
})
if err!= nil {
log.Fatal(err)
}
jwtClient:= smsgateway.NewClient(smsgateway.Config{Token: token.AccessToken})
A configured token takes priority over Basic credentials. Every method accepts a context.Context as its first argument, so cancelation and deadlines propagate to the underlying HTTP request. To target a private deployment or a test server, supply Config.Client with a custom *http.Client and adjust the base URL on the config; the ca package exposes the same capability through ca.WithClient.
API Reference
Construct a client with smsgateway.NewClient(smsgateway.Config{...}). Config accepts User, Password, and Token credentials, an optional Client *http.Client (defaults to http.DefaultClient), and an optional base URL private deployments. All methods take a context.Context as their first argument.
Messages
state, err:= client.Send(ctx, message, opts...)
Send validates Message and any SendOptions before issuing the request. Message supports PhoneNumbers []string, a TextMessage, DataMessage, or outgoing MMSMessage with base64 attachments, plus Priority, DeviceID, SIMNumber, WithDeliveryReport, TTL, validity window, and scheduled delivery fields.
SendOptions modifiers include WithSkipPhoneValidation(bool) and WithDeviceActiveWithin(hours int).
Retrieve and manage individual messages:
state, err:= client.GetMessageState(ctx, messageID)
messages, total, err:= client.ListMessages(ctx, smsgateway.ListMessagesOptions{
PaginationOptions: smsgateway.PaginationOptions{Limit: &limit, Offset: &offset},
IncludeContent: &includeContent,
})
err = client.CancelMessage(ctx, messageID)
ListMessagesOptions combines shared date-range, pagination, state, device, sort, and content options.
Inbox
items, total, err:= client.ListInbox(ctx, smsgateway.ListInboxOptions{...})
err = client.RefreshInbox(ctx)
Inbox listing supports pagination, filters, MMS attachment metadata, and encryption-state flags. Webhook delivery inbox events can be disabled, individual, or batched.
Devices
devices, err:= client.ListDevices(ctx)
err = client.DeleteDevice(ctx, deviceID)
Device records expose optional VersionedPublicKey fields (PublicKey, KeyVersion) E2E key metadata.
Health, Logs, and Settings
health, err:= client.GetHealth(ctx)
logs, err:= client.GetLogs(ctx, smsgateway.LogsOptions{...})
settings, err:= client.GetDeviceSettings(ctx, deviceID)
err = client.PatchDeviceSettings(ctx, deviceID, patch)
err = client.ReplaceDeviceSettings(ctx, deviceID, settings)
Settings support get, patch, and replace operations.
Webhooks
err = client.RegisterWebhook(ctx, smsgateway.WebhookRegistration{...})
Typed event constants and payload DTOs are exported handler signatures. Verify incoming requests before decoding:
body, _:= io.ReadAll(r.Body)
sig:= r.Header.Get(smsgateway.WebhookSignatureHeader)
ts:= r.Header.Get(smsgateway.WebhookTimestampHeader)
if!smsgateway.VerifyWebhookSignatureWithin(signingKey, body, ts, sig, 5*time.Minute) {
http.Error(w, "invalid signature", http.StatusUnauthorized)
return
}
The signature is the hex HMAC-SHA256 digest of the raw body followed by the timestamp. Pass the body bytes exactly as received. VerifyWebhookSignature skips the freshness window; use VerifyWebhookSignatureWithin to bound replay age.
JWT Tokens
token, err:= client.GenerateToken(ctx, smsgateway.TokenRequest{
Scopes: []smsgateway.JWTScope{smsgateway.ScopeMessagesSend, smsgateway.ScopeMessagesRead},
TTL: 3600,
})
refreshed, err:= jwtClient.RefreshToken(ctx, token.RefreshToken)
err = jwtClient.RevokeToken(ctx, token.AccessToken)
A configured token takes priority over Basic credentials.
CA Package
caClient:= ca.NewClient(ca.WithClient(httpClient))
status, err:= caClient.SubmitCSR(ctx, csr)
status, err = caClient.GetCSRStatus(ctx, requestID)
The ca package does not use SMSGate 3rd-party credentials.
Shared REST Layer
The rest package exposes the low-level HTTP client and typed error classification consumed by both clients. Errors returned by public methods wrap a rest.Error carrying the status code and response body programmatic inspection.
All exported types serialize with standard encoding/json. Public-key fields provide schema and serialization support only; the client does not generate keys or encrypt payloads.
Examples
Send a text message:
client:= smsgateway.NewClient(smsgateway.Config{
User: os.Getenv("ASG_USERNAME"),
Password: os.Getenv("ASG_PASSWORD"),
})
state, err:= client.Send(context.Background(), smsgateway.Message{
PhoneNumbers: []string{"+15555550100"},
TextMessage: &smsgateway.TextMessage{Text: "Hello from Go"},
})
Send with options and a scheduled validity window:
state, err:= client.Send(ctx, smsgateway.Message{
PhoneNumbers: []string{"+15555550100"},
TextMessage: &smsgateway.TextMessage{Text: "Scheduled notice"},
Priority: smsgateway.PriorityHigh,
}, smsgateway.WithDeviceActiveWithin(24))
Submit a data message with a base64 attachment and SIM selection:
data, _:= os.ReadFile("report.pdf")
msg:= smsgateway.Message{
PhoneNumbers: []string{"+15555550100"},
DataMessage: &smsgateway.DataMessage{
Data: base64.StdEncoding.EncodeToString(data),
FileName: "report.pdf",
},
SIMNumber: 1,
}
if _, err:= client.Send(ctx, msg); err!= nil {
log.Fatal(err)
}
Retrieve a message state and cancel it:
state, err:= client.GetMessageState(ctx, messageID)
if err!= nil {
return err
}
if err:= client.CancelMessage(ctx, messageID); err!= nil {
return err
}
List messages with filtering, sorting, and pagination:
limit:= 50
includeContent:= true
messages, total, err:= client.ListMessages(ctx, smsgateway.ListMessagesOptions{
PaginationOptions: smsgateway.PaginationOptions{Limit: &limit},
SortOptions: smsgateway.SortOptions{Field: "createdAt", Direction: "desc"},
IncludeContent: &includeContent,
})
if err!= nil {
return err
}
log.Printf("loaded %d of %d messages", len(messages), total)
Read the inbox with batch webhook delivery disabled:
inbox, err:= client.ListInbox(ctx, smsgateway.ListInboxOptions{
WebhookDelivery: smsgateway.WebhookDeliveryDisabled,
})
if err!= nil {
return err
}
_, item:= range inbox.Items {
log.Printf("%s <- %s", item.ID, item.Address)
}
Register a webhook and verify inbound payloads:
_, err:= client.RegisterWebhook(ctx, smsgateway.WebhookRegisterRequest{
URL: "https://example.internal/hooks/sms",
Events: []smsgateway.WebhookEvent{smsgateway.EventMessageReceived},
})
if err!= nil {
return err
}
func handler(w http.ResponseWriter, r *http.Request) {
body, err:= io.ReadAll(r.Body)
if err!= nil {
http.Error(w, "cannot read body", http.StatusBadRequest)
return
}
signature:= r.Header.Get(smsgateway.WebhookSignatureHeader)
timestamp:= r.Header.Get(smsgateway.WebhookTimestampHeader)
if!smsgateway.VerifyWebhookSignatureWithin(signingKey, body, timestamp, signature, 5*time.Minute) {
http.Error(w, "invalid signature", http.StatusUnauthorized)
return
}
w.WriteHeader(http.StatusNoContent)
}
List devices, fetch logs, and patch device settings:
devices, err:= client.ListDevices(ctx)
if err!= nil {
return err
}
logs, err:= client.GetLogs(ctx, devices[0].ID)
if err!= nil {
return err
}
if err:= client.PatchDeviceSettings(ctx, devices[0].ID, smsgateway.DeviceSettingsPatch{
Messages: &smsgateway.MessageSettingsPatch{},
}); err!= nil {
return err
}
Generate, refresh, and revoke a JWT with scoped access:
token, err:= client.GenerateToken(ctx, smsgateway.TokenRequest{
Scopes: []smsgateway.JWTScope{smsgateway.ScopeMessagesSend},
TTL: 3600,
})
if err!= nil {
return err
}
refreshed, err:= jwtClient.RefreshToken(ctx, token.AccessToken)
if err!= nil {
return err
}
if err:= jwtClient.RevokeToken(ctx, refreshed.AccessToken); err!= nil {
return err
}
Submit a Certificate Signing Request through the ca package:
caClient:= ca.NewClient(ca.WithClient(customHTTPClient))
req, err:= caClient.SubmitCSR(ctx, ca.CSRRequest{CSR: pemEncodedCSR})
if err!= nil {
return err
}
status, err:= caClient.GetCSRStatus(ctx, req.ID)
if err!= nil {
return err
}
log.Printf("csr %s: %s", status.ID, status.State)
Supply a custom transport testing or private deployments:
client:= smsgateway.NewClient(smsgateway.Config{
BaseURL: "https://gateway.internal",
Client: &http.Client{Timeout: 10 * time.Second},
Token: os.Getenv("ASG_TOKEN"),
})
Configuration
smsgateway.Config
| Field | Type | Default | Purpose |
|---|---|---|---|
Client |
*http.Client |
http.DefaultClient |
Custom HTTP transport, proxy, TLS, or timeout. |
BaseURL |
string |
Package default | Overrides the API endpoint private deployments or test servers. |
User |
string |
empty | Basic-auth username supplied by the consuming application. |
Password |
string |
empty | Basic-auth password supplied by the consuming application. |
Token |
string |
empty | JWT bearer token; when set, takes priority over Basic credentials. |
The library does not read environment variables. Resolve credentials in the calling application and pass them explicitly.
Per-Request SendOptions
Client.Send accepts functional options applied before the request is issued:
WithSkipPhoneValidation(bool)toggles server-side phone-number validation.WithDeviceActiveWithin(int)restricts delivery to devices active within the given number of hours.
CA Client Options
The ca package accepts functional options:
ca.WithClientsupplies a custom*http.Clientand defaults tohttp.DefaultClient.ca.WithBaseURLoverrides the CA endpoint private deployments or test servers.
Versioned Public-Key DTOs
VersionedPublicKey models optional E2E key metadata:
PublicKeyis a base64-encoded RSA public key.KeyVersionidentifies the key version and is intended rotation tracking.
The type is embedded in Device and MobileRegisterRequest; MobileUpdateRequest receives the fields through its embedded MobileRegisterRequest. These fields provide API schema and serialization support only. The client does not generate keys, encrypt or decrypt message payloads, or automatically attach keys to messages.
License
Distributed under the Apache License 2.0. The complete license text is provided in the LICENSE file at the repository root and governs all use, modification, and redistribution of this module.
Copyright SMS Gateway Go Client contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License the specific language governing permissions and
limitations under the License.
The Apache 2.0 grant is irrevocable and royalty-uncharged both commercial and non-commercial use, subject to the notice and attribution requirements above. Downstream distributions must preserve the LICENSE and NOTICE files.
Contributions submitted to this project are accepted under the same terms unless a separate written agreement states otherwise. No contributor license agreement is required to submit a pull request.
Explore projetos relacionados
Carregando…

