chapa

package module
v0.0.0-...-73963fc Latest Latest
Warning

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

Go to latest
Published: Dec 20, 2024 License: MIT Imports: 16 Imported by: 0

README

Chapa Logo

Go SDK for chapa

build-workflow

Unofficial Golang SDK for Chapa ET API

Todo

  • We could add nice validations on demand.
  • Add implementation for the remaining API endpoints.

Usage

1. Installation

    go get github.com/Chapa-Et/chapa-go
API_KEY

Add your API_KEY: CHASECK_xxxxxxxxxxxxxxxx inside config.yaml file. If you want to run the githb action on your forked repository, you have to create a secrete key named API_KEY.

2. Setup
    package main

    import (
        chapa "github.com/Chapa-Et/chapa-go"
    )

    func main(){
        chapaAPI := chapa.New()
    }
3. Accept Payments
    request := &chapaAPI.PaymentRequest{
        Amount:         10,
        Currency:       "ETB",
        FirstName:      "Chapa",
        LastName:       "ET",
        Email:          "chapa@et.io",
        CallbackURL:    "https://posthere.io/e631-44fe-a19e",
        TransactionRef: RandomString(20),
        Customization: map[string]interface{}{
            "title":       "A Unique Title",
            "description": "This a perfect description",
            "logo":        "https://your.logo",
        },
    }

    response, err := chapaAPI.PaymentRequest(request)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    fmt.Printf("payment response: %+v\n", response)
4. Verify Payment Transactions
    response, err := chapaAPI.Verify("your-txn-ref")
    if err != nil {
         fmt.Println(err)
         os.Exit(1)
    }

    fmt.Printf("verification response: %+v\n", response)
5. Transfer to bank
    request := &BankTransfer{
     AccountName:     "Yinebeb Tariku", 
     AccountNumber:   "34264263", 
     Amount:          10,
     BeneficiaryName: "Yinebeb Tariku",
     Currency:        "ETB",
     Reference:       "3264063st01",
     BankCode:        "32735b19-bb36-4cd7-b226-fb7451cd98f0",
 }
  
 response, err := chapaAPI.TransferToBank(request)
 fmt.Printf("transfer response: %+v\n", response)
6. Get transactions
 response, err := chapaAPI.getTransactions()
 fmt.Printf("transactions response: %+v\n", response)
7. Get banks
 response, err := chapaAPI.getBanks()
 fmt.Printf("banks response: %+v\n", response)
8. Bulk transfer
 bulkData := BulkData{
    AccountName:   "Leul Abay Ejigu",
    AccountNumber: "1000212482106",
    Amount:        10,
    Reference:     "3241342142sfdd",
    BankCode:      "946",
   }

    request := &BulkTransferRequest{
        Title:    "Transfer to leul",
        Currency: "ETB",
        BulkData: []BulkData{bulkData},
    }

    response, err := chapaAPI.bulkTransfer(request)
    fmt.Printf("bulk transfer response: %+v\n", response)

Resources

Quirks

Suggestions on how to improve the API:

  • Introduction of status codes would be a nice to have in the future. Status codes are better than the message in a way considering there are so many reasons a transaction could fail. e.g
    1001: Success
    4001: DuplicateTransaction
    4002: InvalidCurrency
    4003: InvalidAmount 
    4005: InsufficientBalance  
    5000: InternalServerError
    5001: GatewayError
    5002: RejectedByGateway

Just an example!

Contributions

  • Highly welcome

Documentation

Index

Constants

View Source
const (
	FailedTransactionStatus  TransactionStatus = "failed"
	PendingTransactionStatus TransactionStatus = "pending"
	SuccessTransactionStatus TransactionStatus = "success"
	ETB                      Currency          = "ETB"
	USD                      Currency          = "USD"
)

Variables

View Source
var (
	Customers = []Customer{
		{
			ID:        1002,
			FirstName: firstName1,
			LastName:  lastName1,
			Email:     email1,
		},
		{
			ID:        1032,
			FirstName: firstName2,
			LastName:  lastName2,
			Email:     email2,
		},
	}
)

Placeholder data

Functions

func InitConfig

func InitConfig()

func RandomString

func RandomString(length int) string

Types

type API

type API interface {
	PaymentRequest(request *PaymentRequest) (*PaymentResponse, error)
	Verify(txnRef string) (*VerifyResponse, error)
	TransferToBank(request *BankTransfer) (*BankTransferResponse, error)
	GetTransactions() (*TransactionsResponse, error)
	GetBanks() (*BanksResponse, error)
	BulkTransfer(*BulkTransferRequest) (*BulkTransferResponse, error)
}

func New

func New() API

type AppExamplePaymentService

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

func NewExamplePaymentService

func NewExamplePaymentService(
	paymentGatewayProvider API,
) *AppExamplePaymentService

func (*AppExamplePaymentService) Checkout

func (s *AppExamplePaymentService) Checkout(ctx context.Context, CustomerID int64, form CheckoutForm) (*Transaction, error)

func (*AppExamplePaymentService) CustomerByID

func (s *AppExamplePaymentService) CustomerByID(_ context.Context, CustomerID int64) (Customer, error)

CustomerByID you'd fetch Customer from the db

func (*AppExamplePaymentService) ListTransactions

func (s *AppExamplePaymentService) ListTransactions(_ context.Context) (TransactionList, error)

func (*AppExamplePaymentService) SaveTransaction

func (s *AppExamplePaymentService) SaveTransaction(_ context.Context, transaction Transaction) error

type Bank

type Bank struct {
	ID            int64    `json:"id"`
	Swift         string   `json:"swift"`
	Name          string   `json:"name"`
	AcctLength    int64    `json:"acct_length"`
	CountryID     int64    `json:"country_id"`
	CreatedAt     string   `json:"created_at"`
	UpdatedAt     string   `json:"updated_at"`
	IsRTGS        int64    `json:"is_rtgs"`
	IsMobileMoney int64    `json:"is_mobilemoney"`
	Currency      Currency `json:"currency"`
}

type BankTransfer

type BankTransfer struct {
	// AccountName is the recipient Account Name matches on their bank account.
	AccountName string `json:"account_name"`
	// AccountNumber is the recipient Account Number.
	AccountNumber string `json:"account_number"`
	// Amount is the amount to be transferred to the recipient.
	Amount float64 `json:"amount"`
	// Currency is the currency for the Transfer. Expected value is ETB.
	Currency string `json:"currency"`
	// Reference is merchant’s uniques reference for the transfer,
	// it can be used to query for the status of the transfer.
	Reference string `json:"reference"`
	// BankCode is the recipient bank code.
	// You can see a list of all the available banks and their codes from the get banks endpoint.
	BankCode string `json:"bank_code"`
}

BankTransfer is an object used in bank transfer.

func (BankTransfer) Validate

func (t BankTransfer) Validate() error

type BankTransferResponse

type BankTransferResponse struct {
	Message string `json:"message"`
	Status  string `json:"status"`
	Data    string `json:"data"`
}

type BanksResponse

type BanksResponse struct {
	Message string `json:"message"`
	Data    []Bank `json:"data"`
}

type BulkData

type BulkData struct {
	AccountName   string `json:"account_name"`
	AccountNumber string `json:"account_number"`
	Amount        int64  `json:"amount"`
	Reference     string `json:"reference"`
	BankCode      string `json:"bank_code"`
}

type BulkTransferRequest

type BulkTransferRequest struct {
	Title    string     `json:"title"`
	Currency string     `json:"currency"`
	BulkData []BulkData `json:"bulk_data"`
}

func (BulkTransferRequest) Validate

func (t BulkTransferRequest) Validate() error

type BulkTransferResponse

type BulkTransferResponse struct {
	Message string                   `json:"message"`
	Status  string                   `json:"status"`
	Data    BulkTransferResponseData `json:"data"`
}

type BulkTransferResponseData

type BulkTransferResponseData struct {
	ID        int    `json:"id"`
	CreatedAt string `json:"created_at"`
}

type CheckoutForm

type CheckoutForm struct {
	Amount   decimal.Decimal `json:"amount"`
	Currency string          `json:"currency"`
}

type Currency

type Currency string

type Customer

type Customer struct {
	ID        int64  `json:"id"`
	Email     string `json:"email"`
	FirstName string `json:"first_name"`
	LastName  string `json:"last_name"`
	Mobile    string `json:"mobile"`
}

type ExamplePaymentService

type ExamplePaymentService interface {
	Checkout(ctx context.Context, CustomerID int64, form *CheckoutForm) (*PaymentResponse, error)
	ListTransactions(ctx context.Context) (*TransactionList, error)
}

type Pagination

type Pagination struct {
	PerPage      int    `json:"per_page"`
	CurrentPage  int    `json:"current_page"`
	FirstPageURL string `json:"first_page_url"`
	NextPageURL  string `json:"next_page_url"`
	PrevPageURL  string `json:"prev_page_url"`
}

type PaymentRequest

type PaymentRequest struct {
	Amount         decimal.Decimal        `json:"amount"`
	Currency       string                 `json:"currency"`
	Email          string                 `json:"email"`
	FirstName      string                 `json:"first_name"`
	LastName       string                 `json:"last_name"`
	Phone          string                 `json:"phone"`
	CallbackURL    string                 `json:"callback_url"`
	TransactionRef string                 `json:"tx_ref"`
	Customization  map[string]interface{} `json:"customization"`
}

func (PaymentRequest) Validate

func (p PaymentRequest) Validate() error

type PaymentResponse

type PaymentResponse struct {
	Message string `json:"message"`
	Status  string `json:"status"`
	Data    struct {
		CheckoutURL string `json:"checkout_url"`
	}
}

type Transaction

type Transaction struct {
	Status        TransactionStatus `json:"status"`
	RefID         string            `json:"ref_id"`
	Type          string            `json:"type"`
	CreatedAt     string            `json:"created_at"`
	Currency      string            `json:"currency"`
	Amount        decimal.Decimal   `json:"amount"`
	Charge        string            `json:"charge"`
	TransID       string            `json:"trans_id"`
	PaymentMethod string            `json:"payment_method"`
	Customer      Customer          `json:"customer"`
}

type TransactionList

type TransactionList struct {
	Transactions []Transaction `json:"transactions"`
	Pagination   Pagination    `json:"pagination"`
}

type TransactionStatus

type TransactionStatus string

type TransactionsResponse

type TransactionsResponse struct {
	Message string          `json:"message"`
	Status  string          `json:"status"`
	Data    TransactionList `json:"data"`
}

type VerifyResponse

type VerifyResponse struct {
	Message string `json:"message"`
	Status  string `json:"status"`
	Data    struct {
		Charge float64 `json:"charge"`
	}
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL