golang实现Zooz支付API集成客户端插件库zooz的使用

Golang实现Zooz支付API集成客户端插件库zooz的使用

安装

下载go-zooz包:

go get github.com/gojuno/go-zooz

客户端使用了github.com/pkg/errors,所以你可能也需要下载这个包:

go get github.com/pkg/errors

基本使用

要初始化客户端,你需要从Zooz账户配置中获取private_keyapp_id

import "github.com/gojuno/go-zooz"
...

// 初始化客户端
client := zooz.New(
    zooz.OptAppID("com.yourhost.go_client"),
    zooz.OptPrivateKey("a630518c-22da-4eaa-bb39-502ad7832030"),
)

// 创建新客户
customer, customerErr := client.Customer().New(
    context.Background(),
    "customer_idempotency_key",
    &zooz.CustomerParams{
        CustomerReference: "1234",
        FirstName:         "John",
        LastName:          "Doe",
    },
)

// 创建新支付方式
paymentMethod, paymentMethodErr := client.PaymentMethod().New(
    context.Background(),
    "payment_method_idempotency_key",
    customer.ID,
    "918a917e-4cf9-4303-949c-d0cd7ff7f619",
)

// 删除客户
deleteCustomerErr := client.Customer().Delete(context.Background(), customer.ID)

自定义HTTP客户端

默认情况下Zooz客户端使用http.DefaultClient。你可以使用zooz.OptHTTPClient选项设置自定义HTTP客户端:

httpClient := &http.Client{
    Timeout: time.Minute,
}

client := zooz.New(
    zooz.OptAppID("com.yourhost.go_client"),
    zooz.OptPrivateKey("a630518c-22da-4eaa-bb39-502ad7832030"),
    zooz.OptHTTPClient(httpClient),
)

你可以使用任何实现了zooz.HTTPClient接口的HTTP客户端,该接口包含方法Do(r *http.Request) (*http.Response, error)。内置的net/http客户端当然实现了这个接口。

测试/生产环境

Zooz支持测试和生产环境。环境由x-payments-os-env请求头定义。

默认情况下,客户端发送test值。你可以使用zooz.OptEnv(zooz.EnvLive)选项将其重定义为live

client := zooz.New(
    zooz.OptAppID("com.yourhost.go_client"),
    zooz.OptPrivateKey("a630518c-22da-4eaa-bb39-502ad7832030"),
    zooz.OptEnv(zooz.EnvLive),
)

令牌(Tokens)

这个客户端没有实现令牌相关的API方法,因为它们应该用于客户端而不是服务端。


更多关于golang实现Zooz支付API集成客户端插件库zooz的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang实现Zooz支付API集成客户端插件库zooz的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


Golang实现Zooz支付API集成客户端插件库

Zooz是一个流行的支付服务提供商,下面我将介绍如何使用Golang实现Zooz支付API的集成客户端。

基本概念

Zooz API提供了支付处理、客户管理、令牌化等功能。主要API端点包括:

  • 支付处理
  • 客户管理
  • 信用卡令牌化
  • 退款处理

实现步骤

1. 创建基础客户端结构

package zooz

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

const (
	baseURL = "https://api.paymentsos.com"
)

// Client represents Zooz API client
type Client struct {
	appID      string
	privateKey string
	httpClient *http.Client
}

// NewClient creates new Zooz API client
func NewClient(appID, privateKey string) *Client {
	return &Client{
		appID:      appID,
		privateKey: privateKey,
		httpClient: &http.Client{Timeout: 30 * time.Second},
	}
}

2. 实现请求方法

func (c *Client) doRequest(method, path string, body interface{}) ([]byte, error) {
	var reqBody []byte
	var err error

	if body != nil {
		reqBody, err = json.Marshal(body)
		if err != nil {
			return nil, fmt.Errorf("failed to marshal request body: %v", err)
		}
	}

	url := fmt.Sprintf("%s%s", baseURL, path)
	req, err := http.NewRequest(method, url, bytes.NewBuffer(reqBody))
	if err != nil {
		return nil, fmt.Errorf("failed to create request: %v", err)
	}

	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("API-Key", c.privateKey)
	req.Header.Set("app-id", c.appID)

	resp, err := c.httpClient.Do(req)
	if err != nil {
		return nil, fmt.Errorf("failed to send request: %v", err)
	}
	defer resp.Body.Close()

	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("failed to read response body: %v", err)
	}

	if resp.StatusCode >= 400 {
		return nil, fmt.Errorf("API error: %s, status: %d", string(respBody), resp.StatusCode)
	}

	return respBody, nil
}

3. 实现支付创建功能

// PaymentRequest represents payment request payload
type PaymentRequest struct {
	Amount      int64  `json:"amount"`
	Currency    string `json:"currency"`
	CustomerID  string `json:"customer_id,omitempty"`
	PaymentMethod PaymentMethod `json:"payment_method"`
	Description string `json:"description,omitempty"`
}

// PaymentMethod represents payment method details
type PaymentMethod struct {
	Type     string `json:"type"`
	Token    string `json:"token,omitempty"`
	Card     *Card  `json:"card,omitempty"`
}

// Card represents credit card details
type Card struct {
	CardNumber     string `json:"card_number"`
	HolderName     string `json:"holder_name"`
	ExpirationDate string `json:"expiration_date"`
	CVV            string `json:"cvv"`
}

// PaymentResponse represents payment response
type PaymentResponse struct {
	ID           string `json:"id"`
	Status       string `json:"status"`
	Amount       int64  `json:"amount"`
	Currency     string `json:"currency"`
	Created      string `json:"created"`
	Updated      string `json:"updated"`
	CustomerID   string `json:"customer_id"`
	PaymentMethod PaymentMethodResponse `json:"payment_method"`
}

// PaymentMethodResponse represents payment method in response
type PaymentMethodResponse struct {
	Type string `json:"type"`
	Token string `json:"token"`
}

// CreatePayment creates a new payment
func (c *Client) CreatePayment(paymentReq PaymentRequest) (*PaymentResponse, error) {
	path := "/payments"
	resp, err := c.doRequest("POST", path, paymentReq)
	if err != nil {
		return nil, err
	}

	var paymentResp PaymentResponse
	if err := json.Unmarshal(resp, &paymentResp); err != nil {
		return nil, fmt.Errorf("failed to unmarshal payment response: %v", err)
	}

	return &paymentResp, nil
}

4. 实现客户管理功能

// Customer represents customer details
type Customer struct {
	ID        string `json:"id,omitempty"`
	FirstName string `json:"first_name"`
	LastName  string `json:"last_name"`
	Email     string `json:"email"`
}

// CreateCustomer creates a new customer
func (c *Client) CreateCustomer(customer Customer) (*Customer, error) {
	path := "/customers"
	resp, err := c.doRequest("POST", path, customer)
	if err != nil {
		return nil, err
	}

	var createdCustomer Customer
	if err := json.Unmarshal(resp, &createdCustomer); err != nil {
		return nil, fmt.Errorf("failed to unmarshal customer response: %v", err)
	}

	return &createdCustomer, nil
}

// GetCustomer retrieves customer details
func (c *Client) GetCustomer(customerID string) (*Customer, error) {
	path := fmt.Sprintf("/customers/%s", customerID)
	resp, err := c.doRequest("GET", path, nil)
	if err != nil {
		return nil, err
	}

	var customer Customer
	if err := json.Unmarshal(resp, &customer); err != nil {
		return nil, fmt.Errorf("failed to unmarshal customer response: %v", err)
	}

	return &customer, nil
}

5. 使用示例

package main

import (
	"fmt"
	"log"
	"yourpackage/zooz"
)

func main() {
	// Initialize client
	client := zooz.NewClient("your-app-id", "your-private-key")

	// Create customer
	customer := zooz.Customer{
		FirstName: "John",
		LastName:  "Doe",
		Email:     "john.doe@example.com",
	}
	
	createdCustomer, err := client.CreateCustomer(customer)
	if err != nil {
		log.Fatalf("Failed to create customer: %v", err)
	}
	fmt.Printf("Created customer: %+v\n", createdCustomer)

	// Create payment
	payment := zooz.PaymentRequest{
		Amount:   1000, // $10.00
		Currency: "USD",
		CustomerID: createdCustomer.ID,
		PaymentMethod: zooz.PaymentMethod{
			Type: "tokenized",
			Token: "your-payment-token",
		},
		Description: "Test payment",
	}
	
	paymentResp, err := client.CreatePayment(payment)
	if err != nil {
		log.Fatalf("Failed to create payment: %v", err)
	}
	fmt.Printf("Created payment: %+v\n", paymentResp)
}

注意事项

  1. 安全性:确保妥善保管API密钥和私钥
  2. 错误处理:正确处理API返回的各种错误状态
  3. 重试机制:对于网络错误或临时性API错误实现重试逻辑
  4. 测试:编写全面的测试用例,包括模拟API响应
  5. 日志:记录请求和响应以便调试和审计

扩展功能

  1. 实现退款功能
  2. 添加webhook处理
  3. 实现支付状态查询
  4. 添加更多的支付方法支持

这个实现提供了Zooz支付API的基本集成功能,可以根据实际需求进行扩展和优化。

回到顶部