lomi.
SDKs

SDK Go

SDK Go officiel pour l’API de paiement lomi.

SDK Go

SDK Go officiel pour l’API de paiement lomi. Compatible Go 1.18 et versions ultérieures.

Installation

go get github.com/lomiafrica/lomi-go-sdk

Démarrage rapide

package main

import (
    "context"
    "fmt"
    "os"

    lomi "github.com/lomiafrica/lomi-go-sdk"
)

func main() {
    configuration := lomi.NewConfiguration()
    client := lomi.NewAPIClient(configuration)

    // Configuration de l’authentification
    auth := context.WithValue(
        context.Background(),
        lomi.ContextAPIKeys,
        map[string]lomi.APIKey{
            "ApiKeyAuth": {Key: os.Getenv("LOMI_API_KEY")},
        },
    )

    // Utilisez ensuite ce contexte pour tous les appels API
}

Exemples

Lister les clients

customers, _, err := client.CustomersAPI.ListCustomers(auth).Execute()
if err != nil {
    fmt.Printf("Erreur : %v\n", err)
    return
}

for _, customer := range customers.Data {
    fmt.Printf("%s: %s\n", *customer.Id, *customer.Name)
}

Créer un client

customerData := lomi.CustomersCreate{
    Name:        lomi.PtrString("Moussa Keita"),
    Email:       lomi.PtrString("moussa@example.com"),
    PhoneNumber: lomi.PtrString("+22370123456"),
}

customer, _, err := client.CustomersAPI.CreateCustomer(auth).
    CustomersCreate(customerData).
    Execute()

if err != nil {
    fmt.Printf("Erreur : %v\n", err)
    return
}

fmt.Printf("Client créé : %s\n", *customer.Id)

Créer une session de paiement

sessionData := lomi.CheckoutSessionsCreate{
    Amount:     lomi.PtrInt32(5000), // 5,000 F CFA
    Currency:   lomi.PtrString("XOF"),
    SuccessUrl: lomi.PtrString("https://yoursite.com/success"),
    CancelUrl:  lomi.PtrString("https://yoursite.com/cancel"),
}

session, _, err := client.CheckoutSessionsAPI.CreateCheckoutSession(auth).
    CheckoutSessionsCreate(sessionData).
    Execute()

if err != nil {
    fmt.Printf("Erreur : %v\n", err)
    return
}

// Rediriger le client vers session.Url
fmt.Printf("URL de tunnel : %s\n", *session.Url)

Lister les transactions

transactions, _, err := client.TransactionsAPI.ListTransactions(auth).Execute()
if err != nil {
    fmt.Printf("Erreur : %v\n", err)
    return
}

for _, tx := range transactions.Data {
    fmt.Printf("%s: %d %s - %s\n", *tx.Id, *tx.Amount, *tx.Currency, *tx.Status)
}

Créer un lien de paiement

linkData := lomi.PaymentLinksCreate{
    Amount:      lomi.PtrInt32(10000),
    Currency:    lomi.PtrString("XOF"),
    Description: lomi.PtrString("Abonnement Premium"),
    Reusable:    lomi.PtrBool(true),
}

link, _, err := client.PaymentLinksAPI.CreatePaymentLink(auth).
    PaymentLinksCreate(linkData).
    Execute()

if err != nil {
    fmt.Printf("Erreur : %v\n", err)
    return
}

fmt.Printf("Partagez ce lien : %s\n", *link.Url)

Gestion des erreurs

customer, response, err := client.CustomersAPI.RetrieveCustomer(auth, "invalid_id").Execute()

if err != nil {
    // Détails d’erreur API
    if apiErr, ok := err.(*lomi.GenericOpenAPIError); ok {
        fmt.Printf("Erreur API : %s\n", apiErr.Error())
        fmt.Printf("Corps de la réponse : %s\n", string(apiErr.Body()))
    }

    // Code de statut HTTP
    if response != nil {
        fmt.Printf("Code HTTP : %d\n", response.StatusCode)
    }
    return
}

Réception des webhooks

package main

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

type WebhookEvent struct {
    Type string                 `json:"type"`
    Data map[string]interface{} `json:"data"`
}

func webhookHandler(w http.ResponseWriter, r *http.Request) {
    signature := r.Header.Get("x-lomi-signature")
    secret := os.Getenv("LOMI_WEBHOOK_SECRET")

    body, err := io.ReadAll(r.Body)
    if err != nil {
        http.Error(w, "Corps illisible", http.StatusBadRequest)
        return
    }

    // Vérifier la signature
    mac := hmac.New(sha256.New, []byte(secret))
    mac.Write(body)
    expectedSignature := hex.EncodeToString(mac.Sum(nil))

    if !hmac.Equal([]byte(signature), []byte(expectedSignature)) {
        http.Error(w, "Signature invalide", http.StatusBadRequest)
        return
    }

    var event WebhookEvent
    if err := json.Unmarshal(body, &event); err != nil {
        http.Error(w, "JSON invalide", http.StatusBadRequest)
        return
    }

    switch event.Type {
    case "PAYMENT_SUCCEEDED":
        log.Printf("Paiement réussi : %v", event.Data)
        // Traiter le paiement

    default:
        log.Printf("Événement non géré : %s", event.Type)
    }

    w.WriteHeader(http.StatusOK)
    json.NewEncoder(w).Encode(map[string]bool{"received": true})
}

func main() {
    http.HandleFunc("/webhook", webhookHandler)
    log.Println("Écoute webhook sur :3000")
    log.Fatal(http.ListenAndServe(":3000", nil))
}

Fonctions utilitaires pour les pointeurs

Le SDK fournit des fonctions d’aide pour les types scalaires (champs optionnels) :

// Champs optionnels
name := lomi.PtrString("Nom du client")
amount := lomi.PtrInt32(5000)
active := lomi.PtrBool(true)
rate := lomi.PtrFloat64(0.025)

API disponibles

APIMéthodes
CustomersAPIListCustomers, CreateCustomer, RetrieveCustomer, UpdateCustomer, DeleteCustomer
CheckoutSessionsAPIListCheckoutSessions, CreateCheckoutSession, RetrieveCheckoutSession, UpdateCheckoutSession, DeleteCheckoutSession
TransactionsAPIListTransactions, RetrieveTransaction
PaymentLinksAPIListPaymentLinks, CreatePaymentLink, RetrievePaymentLink, UpdatePaymentLink, DeletePaymentLink
ProductsAPIListProducts, CreateProduct, RetrieveProduct, UpdateProduct, DeleteProduct
SubscriptionsAPIListSubscriptions, CreateSubscription, RetrieveSubscription, UpdateSubscription, DeleteSubscription
RefundsAPIListRefunds, CreateRefund, RetrieveRefund
PayoutsAPIListPayouts, CreatePayout, RetrievePayout
BeneficiaryPayoutsAPIListBeneficiaryPayouts, CreateBeneficiaryPayout, RetrieveBeneficiaryPayout
PaymentRequestsAPIListPaymentRequests, CreatePaymentRequest, RetrievePaymentRequest
DiscountCouponsAPIListDiscountCoupons, CreateDiscountCoupon, RetrieveDiscountCoupon, UpdateDiscountCoupon, DeleteDiscountCoupon
WebhookDeliveryLogsAPIListWebhookDeliveryLogs, RetrieveWebhookDeliveryLog
WebhooksAPIListWebhooks, CreateWebhook, RetrieveWebhook, UpdateWebhook, DeleteWebhook

Besoin d’aide ?

Sur cette page