Skip to content

Go Examples

Ready-to-use Go code for common Pixlpay API operations.

Setup

Client Package

go
package pixlpay

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
)

type Client struct {
    BaseURL    string
    APIToken   string
    HTTPClient *http.Client
}

func NewClient(subdomain, apiToken string) *Client {
    return &Client{
        BaseURL:    fmt.Sprintf("https://%s.pixlpay.net/api/external/v1", subdomain),
        APIToken:   apiToken,
        HTTPClient: &http.Client{},
    }
}

func (c *Client) doRequest(method, endpoint string, body interface{}) ([]byte, int, error) {
    var reqBody io.Reader
    if body != nil {
        jsonBody, err := json.Marshal(body)
        if err != nil {
            return nil, 0, err
        }
        reqBody = bytes.NewBuffer(jsonBody)
    }

    req, err := http.NewRequest(method, c.BaseURL+endpoint, reqBody)
    if err != nil {
        return nil, 0, err
    }

    req.Header.Set("Authorization", "Bearer "+c.APIToken)
    req.Header.Set("Accept", "application/json")
    req.Header.Set("Content-Type", "application/json")

    resp, err := c.HTTPClient.Do(req)
    if err != nil {
        return nil, 0, err
    }
    defer resp.Body.Close()

    data, err := io.ReadAll(resp.Body)
    return data, resp.StatusCode, err
}

func (c *Client) Get(endpoint string) ([]byte, int, error) {
    return c.doRequest("GET", endpoint, nil)
}

func (c *Client) Post(endpoint string, body interface{}) ([]byte, int, error) {
    return c.doRequest("POST", endpoint, body)
}

Data Types

go
package pixlpay

type Product struct {
    ID          int     `json:"id"`
    Name        string  `json:"name"`
    Slug        string  `json:"slug"`
    Description string  `json:"description"`
    Price       string  `json:"price"`
    Type        string  `json:"type"`
    IsActive    bool    `json:"is_active"`
}

type Order struct {
    ID            int         `json:"id"`
    OrderNumber   string      `json:"order_number"`
    Status        string      `json:"status"`
    PaymentStatus string      `json:"payment_status"`
    Total         string      `json:"total"`
    Customer      Customer    `json:"customer"`
    Items         []OrderItem `json:"items"`
}

type Customer struct {
    ID    int    `json:"id"`
    Email string `json:"email"`
}

type OrderItem struct {
    ProductID   int    `json:"product_id"`
    ProductName string `json:"product_name"`
    Quantity    int    `json:"quantity"`
    Price       string `json:"price"`
}

type Response[T any] struct {
    Success bool `json:"success"`
    Data    T    `json:"data"`
}

Fetching Products

go
package main

import (
    "encoding/json"
    "fmt"
    "os"
)

func main() {
    client := pixlpay.NewClient("yourstore", os.Getenv("PIXLPAY_TOKEN"))

    data, status, err := client.Get("/products")
    if err != nil {
        fmt.Println("Error:", err)
        return
    }

    if status == 200 {
        var response pixlpay.Response[[]pixlpay.Product]
        json.Unmarshal(data, &response)

        for _, product := range response.Data {
            fmt.Printf("%s - $%s\n", product.Name, product.Price)
        }
    }
}

Fulfilling Orders

go
package main

import (
    "encoding/json"
    "fmt"
    "os"
)

func fulfillOrder(client *pixlpay.Client, orderID int) error {
    body := map[string]string{
        "note": "Delivered via API",
    }

    data, status, err := client.Post(fmt.Sprintf("/orders/%d/fulfill", orderID), body)
    if err != nil {
        return err
    }

    if status == 200 {
        fmt.Println("Order fulfilled successfully!")
    } else {
        fmt.Printf("Error: %s\n", string(data))
    }
    return nil
}

Webhook Handler

go
package main

import (
    "crypto/hmac"
    "crypto/sha256"
    "encoding/hex"
    "encoding/json"
    "io"
    "net/http"
    "os"
)

type WebhookEvent struct {
    Event string          `json:"event"`
    Data  json.RawMessage `json:"data"`
}

func verifySignature(payload []byte, signature, secret string) bool {
    mac := hmac.New(sha256.New, []byte(secret))
    mac.Write(payload)
    computed := hex.EncodeToString(mac.Sum(nil))
    return hmac.Equal([]byte(computed), []byte(signature))
}

func webhookHandler(w http.ResponseWriter, r *http.Request) {
    payload, _ := io.ReadAll(r.Body)
    signature := r.Header.Get("X-Pixlpay-Signature")
    secret := os.Getenv("PIXLPAY_WEBHOOK_SECRET")

    if !verifySignature(payload, signature, secret) {
        http.Error(w, "Invalid signature", http.StatusUnauthorized)
        return
    }

    var event WebhookEvent
    json.Unmarshal(payload, &event)

    switch event.Event {
    case "order.paid":
        var order pixlpay.Order
        json.Unmarshal(event.Data, &order)
        handleOrderPaid(order)
    case "order.completed":
        var order pixlpay.Order
        json.Unmarshal(event.Data, &order)
        handleOrderCompleted(order)
    }

    w.WriteHeader(http.StatusOK)
}

func handleOrderPaid(order pixlpay.Order) {
    fmt.Printf("Order paid: %s\n", order.OrderNumber)
}

func handleOrderCompleted(order pixlpay.Order) {
    fmt.Printf("Order completed: %s\n", order.OrderNumber)
}

func main() {
    http.HandleFunc("/webhooks/pixlpay", webhookHandler)
    http.ListenAndServe(":3000", nil)
}

Creating Webhooks

go
package main

import (
    "encoding/json"
    "fmt"
    "os"
)

type WebhookResponse struct {
    ID     int    `json:"id"`
    URL    string `json:"url"`
    Secret string `json:"secret"`
}

func createWebhook(client *pixlpay.Client) (*WebhookResponse, error) {
    body := map[string]interface{}{
        "url":    "https://yoursite.com/webhooks/pixlpay",
        "events": []string{"order.paid", "order.completed"},
    }

    data, status, err := client.Post("/webhooks", body)
    if err != nil {
        return nil, err
    }

    if status == 201 {
        var response pixlpay.Response[WebhookResponse]
        json.Unmarshal(data, &response)
        fmt.Printf("Webhook created! Secret: %s\n", response.Data.Secret)
        return &response.Data, nil
    }

    return nil, fmt.Errorf("failed to create webhook: %s", string(data))
}

Error Handling

go
package main

import (
    "encoding/json"
    "fmt"
)

type ErrorResponse struct {
    Success bool   `json:"success"`
    Error   string `json:"error"`
    Message string `json:"message"`
}

func handleError(data []byte, status int) {
    var errResp ErrorResponse
    json.Unmarshal(data, &errResp)

    fmt.Printf("Error: %s\n", errResp.Message)

    switch status {
    case 401:
        fmt.Println("Check your API token")
    case 404:
        fmt.Println("Resource not found")
    case 429:
        fmt.Println("Rate limited - slow down!")
    }
}

Built for game developers, by game developers.