# SDK Go
Source: https://docs.lomi.africa/build/sdks/go

SDK Go officiel pour l’API de paiement lomi.

***

title: 'SDK Go'
description: 'SDK Go officiel pour l’API de paiement lomi.'
-----------------------------------------------------------

import { Callout } from '@/components/docs/docs-callout';

# SDK Go

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

## Installation

```bash
go get github.com/lomiafrica/lomi./apps/sdks/go
```

## Démarrage rapide

```go
package main

import (
    "context"
    "fmt"
    "os"

    lomi "github.com/lomiafrica/lomi./apps/sdks/go"
)

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_SECRET_KEY")},
        },
    )

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

## Exemples

### Lister les clients

```go
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

```go
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

```go
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

```go
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

```go
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

```go
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

```go
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) :

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

## API disponibles

| API                      | Méthodes                                                                                                                     |
| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------- |
| `CustomersAPI`           | `ListCustomers`, `CreateCustomer`, `RetrieveCustomer`, `UpdateCustomer`, `DeleteCustomer`                                    |
| `CheckoutSessionsAPI`    | `ListCheckoutSessions`, `CreateCheckoutSession`, `RetrieveCheckoutSession`, `UpdateCheckoutSession`, `DeleteCheckoutSession` |
| `TransactionsAPI`        | `ListTransactions`, `RetrieveTransaction`                                                                                    |
| `PaymentLinksAPI`        | `ListPaymentLinks`, `CreatePaymentLink`, `RetrievePaymentLink`, `UpdatePaymentLink`, `DeletePaymentLink`                     |
| `ProductsAPI`            | `ListProducts`, `CreateProduct`, `RetrieveProduct`, `UpdateProduct`, `DeleteProduct`                                         |
| `SubscriptionsAPI`       | `ListSubscriptions`, `CreateSubscription`, `RetrieveSubscription`, `UpdateSubscription`, `DeleteSubscription`                |
| `RefundsAPI`             | `ListRefunds`, `CreateRefund`, `RetrieveRefund`                                                                              |
| `PayoutsAPI`             | `ListPayouts`, `CreatePayout`, `RetrievePayout` (self et beneficiary via `destination`)                                      |
| `ChargesAPI`             | `CreateWaveCharge`, `CreateMtnCharge`, `CreateCardCharge`, `GetCardCharge`, `CancelCardCharge`                               |
| `PaymentRequestsAPI`     | `ListPaymentRequests`, `CreatePaymentRequest`, `RetrievePaymentRequest`                                                      |
| `DiscountCouponsAPI`     | `ListDiscountCoupons`, `CreateDiscountCoupon`, `RetrieveDiscountCoupon`, `UpdateDiscountCoupon`, `DeleteDiscountCoupon`      |
| `WebhookDeliveryLogsAPI` | `ListWebhookDeliveryLogs`, `RetrieveWebhookDeliveryLog`                                                                      |
| `WebhooksAPI`            | `ListWebhooks`, `CreateWebhook`, `RetrieveWebhook`, `UpdateWebhook`, `DeleteWebhook`                                         |

## Besoin d’aide ?

* [Référence API](/api): documentation complète de l’API
* [Issues GitHub](https://github.com/lomiafrica/lomi./issues): signaler des anomalies
* [Discord](https://discord.gg/yb4FnBmh): communauté
