Golang SDK
thông tin
Code demo: https://github.com/payOSHQ/payos-demo-golang
Tài liệu đầy đủ
Để biết thêm chi tiết về các phương thức, tham số và tính năng nâng cao (context support, auto-paging iterators, error handling, v.v.), vui lòng xem GitHub Repository.
Cài đặt
Cài đặt thư viện payos-lib-golang thông qua go get:
go get github.com/payOSHQ/payos-lib-golang/v2
Khởi tạo
Khởi tạo đối tượng PayOS với Client ID, API Key và Checksum Key:
import (
"context"
"os"
"github.com/payOSHQ/payos-lib-golang/v2/payos"
)
func main() {
ctx := context.Background()
client, err := payos.NewPayOS(&payos.PayOSOptions{
ClientId: os.Getenv("PAYOS_CLIENT_ID"),
ApiKey: os.Getenv("PAYOS_API_KEY"),
ChecksumKey: os.Getenv("PAYOS_CHECKSUM_KEY"),
})
if err != nil {
log.Fatal(err)
}
}
Tạo link thanh toán
Sử dụng phương thức PaymentRequests.Create() để tạo link thanh toán:
item := payos.PaymentLinkItem{
Name: "Sản phẩm A",
Quantity: 1,
Price: 50000,
}
paymentRequest := payos.CreatePaymentLinkRequest{
OrderCode: 123456,
Amount: 50000,
Description: "Thanh toán đơn hàng",
Items: []payos.PaymentLinkItem{item},
CancelUrl: "https://your-domain.com/cancel",
ReturnUrl: "https://your-domain.com/success",
}
paymentLink, err := client.PaymentRequests.Create(ctx, paymentRequest)
if err != nil {
log.Fatalf("Không thể tạo link thanh toán: %v", err)
}
fmt.Println(paymentLink.CheckoutUrl)
Xác minh webhook
Sử dụng phương thức Webhooks.VerifyData() để xác thực dữ liệu webhook:
import (
"encoding/json"
"net/http"
)
func webhookHandler(w http.ResponseWriter, r *http.Request) {
var webhookData map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&webhookData); err != nil {
http.Error(w, "Invalid request", http.StatusBadRequest)
return
}
verifiedData, err := client.Webhooks.VerifyData(ctx, webhookData)
if err != nil {
log.Printf("Webhook không hợp lệ: %v", err)
http.Error(w, "Invalid webhook", http.StatusBadRequest)
return
}
log.Printf("Thanh toán thành công")
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}
Tạo payout
Sử dụng phương thức Payouts.Batch.Create() để tạo payout theo lô:
import "time"
referenceId := fmt.Sprintf("payout_%d", time.Now().Unix())
payoutBatch := payos.PayoutBatchRequest{
ReferenceId: referenceId,
Category: []string{"salary"},
ValidateDestination: true,
Payouts: []payos.PayoutBatchItem{
{
ReferenceId: fmt.Sprintf("%s_1", referenceId),
Amount: 2000,
Description: "Thanh toán lương",
ToBin: "970422",
ToAccountNumber: "0123456789",
},
{
ReferenceId: fmt.Sprintf("%s_2", referenceId),
Amount: 3000,
Description: "Thanh toán thưởng",
ToBin: "970422",
ToAccountNumber: "0987654321",
},
},
}
payout, err := client.Payouts.Batch.Create(ctx, payoutBatch)
if err != nil {
log.Fatalf("Không thể tạo payout: %v", err)
}
fmt.Printf("Payout ID: %s\n", payout.Id)