toss

package module
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: Jul 19, 2025 License: MIT Imports: 11 Imported by: 0

README

[!WARNING] 이 프로젝트는 Toss Payments 비공식 라이브러리 입니다.

Toss Payments API의 Go 클라이언트 라이브러리입니다. 일반결제, 자동결제, 거래내역 조회, 정산내역 조회 등 주요 기능을 제공합니다.

go get -u github.com/fluffy-melli/toss-api
API 항목 API 기능 구현 여부 테스트키 실사용키
일반결제 결제승인 O O ? (미테스트)
일반결제 결제취소 O O ? (미테스트)
일반결제 주문ID로 결제조회 O O ? (미테스트)
일반결제 결제키로 결제조회 O O ? (미테스트)
일반결제 가상계좌발급 O O ? (미테스트)
자동결제 자동결제 키발급 O O ? (미테스트)
자동결제 자동결제승인 O O ? (미테스트)
거래내역 거래내역조회 O O ? (미테스트)
정산내역 정산내역조회 O X (빈배열 응답) ? (미테스트)
정산내역 수동정산 X X (미구현) X (미구현)
지급대행 잔액조회 X X (미구현) X (미구현)
지급대행 셀러등록 X X (미구현) X (미구현)
지급대행 셀러수정 X X (미구현) X (미구현)
지급대행 셀러삭제 X X (미구현) X (미구현)
지급대행 셀러단건조회 X X (미구현) X (미구현)
지급대행 셀러조회 X X (미구현) X (미구현)
지급대행 지급대행요청 X X (미구현) X (미구현)
지급대행 지급대행요청취소 X X (미구현) X (미구현)
지급대행 지급요청단건조회 X X (미구현) X (미구현)
지급대행 지급요청조회 X X (미구현) X (미구현)
프로모션 전체프로모션조회 X X (미구현) X (미구현)
프로모션 카드프로모션조회 X X (미구현) X (미구현)
현금영수증 현금영수증발급 X X (미구현) X (미구현)
현금영수증 현금영수증발급취소 X X (미구현) X (미구현)
현금영수증 현금영수증조회 X X (미구현) X (미구현)

자세한 API 문서는 Toss Payments 공식 API 레퍼런스를 참고하세요.

Documentation

Index

Constants

View Source
const (
	API = "https://api.tosspayments.com/"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Billing added in v0.0.5

type Billing struct {
	MID             string       `json:"mId"`
	BillingKey      string       `json:"billingKey"`
	CustomerKey     string       `json:"customerKey"`
	AuthenticatedAt time.Time    `json:"authenticatedAt"`
	Method          types.Method `json:"method"`
	Card            PaymentCard  `json:"card"`
	CardCompany     string       `json:"cardCompany"`
	CardNumber      string       `json:"cardNumber"`
}

type BillingOptions added in v0.0.5

type BillingOptions struct {
	CustomerEmail      *string
	CustomerName       *string
	TaxFreeAmount      *int
	TaxExemptionAmount *int
}

type Client

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

func NewClient

func NewClient(apiKey string) *Client

NewClient 토스페이먼츠 클라이언트 생성 토스페이먼츠 API를 사용하기 위한 클라이언트를 생성합니다. API 키는 토스페이먼츠 개발자 센터에서 발급받을 수 있습니다.

Parameters:

  • apiKey: 토스페이먼츠에서 발급받은 API 키 (시크릿 키)

Returns:

  • *Client: 초기화된 토스페이먼츠 클라이언트 객체

Example:

client := toss.NewClient("test_sk_zXLkKEypNArWmo50nX3lmeaxYG5R")
payment, err := client.PaymentConfirm("paymentKey", "orderId", 15000)

func (*Client) BillingConfirm added in v0.0.5

func (c *Client) BillingConfirm(billingKey, customerKey, orderId, orderName string, amount int, o *BillingOptions) (*Payment, error)

BillingConfirm 빌링키 결제 승인 발급된 빌링키를 사용하여 결제를 승인합니다. 자동결제(정기결제) 처리에 활용하세요.

Parameters:

  • billingKey: 빌링키
  • customerKey: 고객 식별 키
  • orderId: 주문 ID
  • orderName: 주문명
  • amount: 결제 금액
  • o: 결제 옵션 (nil 가능)
  • CustomerEmail: 고객 이메일
  • CustomerName: 고객 이름
  • TaxFreeAmount: 비과세 금액
  • TaxExemptionAmount: 과세 면제 금액

Returns:

  • *Payment: 결제 정보
  • error: 결제 실패 시 에러

Example:

// 기본 빌링키 결제
payment, err := client.BillingConfirm("billing_key_123", "customer_001", "order_456", "정기결제", 10000, nil)
// 옵션 포함 빌링키 결제
options := &BillingOptions{
    CustomerEmail: "customer@example.com",
    CustomerName: "홍길동",
    TaxFreeAmount: 1000,
}
payment, err := client.BillingConfirm("billing_key_123", "customer_001", "order_456", "정기결제", 10000, options)

func (*Client) BillingIssue added in v0.0.5

func (c *Client) BillingIssue(authKey, customerKey string) (*Billing, error)

BillingIssue 빌링키 발급 고객의 결제 수단을 등록하고 빌링키를 발급합니다. 자동결제(정기결제) 서비스에 활용하세요.

Parameters:

  • authKey: 결제 수단 인증 키
  • customerKey: 고객 식별 키

Returns:

  • *Billing: 빌링키 정보
  • error: 발급 실패 시 에러

Example:

// 빌링키 발급
billing, err := client.BillingIssue("auth_key_123", "customer_001")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("빌링키: %s\n", billing.BillingKey)

func (*Client) PaymentCancel

func (c *Client) PaymentCancel(paymentKey, cancelReason string, o *PaymentCancelOptions) (*Payment, error)

PaymentCancel 결제 취소 승인된 결제를 전액 또는 부분 취소합니다. 취소 후에는 되돌릴 수 없으니 신중하게 사용하세요.

Parameters:

  • paymentKey: 취소할 결제의 고유 키
  • cancelReason: 취소 사유 (필수, 최대 200자)
  • o: 취소 옵션 (nil 가능)
  • CancelAmount: 부분 취소 금액 (nil이면 전액 취소)
  • RefundReceiveAccount: 환불 계좌 정보 (계좌이체 결제시 필요)
  • TaxFreeAmount: 면세 금액
  • Currency: 통화 코드

Returns:

  • *Payment: 취소 처리된 결제 정보 객체
  • error: 취소 실패 시 에러 (이미 취소됨, 취소 불가 상태 등)

Example:

// 전액 취소
payment, err := client.PaymentCancel("tgen_20240101000000_ABC123", "고객 요청", nil)

// 부분 취소 (5,000원만 취소)
options := &PaymentCancelOptions{
    CancelAmount: 5000,
}
payment, err := client.PaymentCancel("tgen_20240101000000_ABC123", "부분 환불", options)

func (*Client) PaymentCheckByOrderID

func (c *Client) PaymentCheckByOrderID(orderId string) (*Payment, error)

PaymentCheckByOrderID 주문 ID로 결제 조회 상점에서 생성한 주문 ID로 결제 정보를 조회합니다. 주문 상태 확인이나 결제 정보 조회 시 사용하세요.

Parameters:

  • orderId: 결제 요청 시 생성한 주문 ID

Returns:

  • *Payment: 결제 정보 객체
  • error: 조회 실패 시 에러 (존재하지 않는 주문 등)

Example:

payment, err := client.PaymentCheckByOrderID("order_12345")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("결제 상태: %s, 금액: %d원\n", payment.Status, payment.TotalAmount)

func (*Client) PaymentCheckByPaymentKey

func (c *Client) PaymentCheckByPaymentKey(paymentKey string) (*Payment, error)

PaymentCheckByPaymentKey 결제 키로 결제 조회 토스페이먼츠에서 발급한 결제 키로 결제 정보를 조회합니다. 결제 승인 후 받은 paymentKey로 언제든지 결제 정보를 확인할 수 있습니다.

Parameters:

  • paymentKey: 결제 승인 후 받은 결제 고유 키

Returns:

  • *Payment: 결제 정보 객체
  • error: 조회 실패 시 에러 (존재하지 않는 결제 등)

Example:

payment, err := client.PaymentCheckByPaymentKey("tgen_20240101000000_ABC123")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("결제 방법: %s, 승인 시간: %s\n", payment.Method, payment.ApprovedAt)

func (*Client) PaymentConfirm

func (c *Client) PaymentConfirm(paymentKey, orderId string, amount int) (*Payment, error)

PaymentConfirm 결제 승인 토스페이먼츠 결제 위젯에서 결제 인증 완료 후 반드시 호출해야 하는 API입니다. 결제 인증 후 10분 이내에 호출하지 않으면 결제가 자동으로 만료됩니다.

Parameters:

  • paymentKey: 결제 위젯에서 전달받은 결제 고유 키
  • orderId: 결제 요청 시 생성한 주문 ID (최대 64자)
  • amount: 실제 결제 금액 (위젯에서 전달받은 금액과 일치해야 함)

Returns:

  • *Payment: 승인된 결제 정보 객체
  • error: 승인 실패 시 에러 (금액 불일치, 만료, 중복 승인 등)

Example:

payment, err := client.PaymentConfirm("tgen_20240101000000_ABC123", "order_12345", 15000)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("결제 승인 완료: %s\n", payment.OrderID)

func (*Client) SettlementsCheck added in v0.0.3

func (c *Client) SettlementsCheck(startDate, endDate time.Time, o *SettlementOptions) ([]Settlement, error)

SettlementsCheck 정산 내역 조회 지정한 날짜 정보로 정산 기록을 조회합니다. 정산 관리, 매출 분석, 수수료 확인 등에 활용하세요.

Parameters:

  • startDate: 조회 시작 날짜 (정산 처리 시점 기준)
  • endDate: 조회 종료 날짜 (정산 처리 시점 기준)
  • o: 조회 옵션 (nil 가능)
  • Page: 페이지 번호 (1부터 시작)
  • Size: 페이지당 조회할 정산 수 (최대 100개, 기본값 20개)

Returns:

  • []Settlement: 정산 내역 배열
  • error: 조회 실패 시 에러

Example:

// 최근 30일 정산 내역 조회
startDate := time.Now().AddDate(0, 0, -30)
endDate := time.Now()
settlements, err := client.SettlementsCheck(startDate, endDate, nil)

// 페이징으로 50개씩 조회
options := &SettlementOptions{
    Page: 1,
    Size: 50,
}
settlements, err := client.SettlementsCheck(startDate, endDate, options)

func (*Client) TransactionsCheck added in v0.0.2

func (c *Client) TransactionsCheck(startDate, endDate time.Time, o *TransactionOptions) ([]Transaction, error)

TransactionsCheck 거래 내역 조회 특정 기간의 모든 거래 기록을 조회합니다. 정산, 매출 분석, 거래 내역 확인 등에 활용하세요.

Parameters:

  • startDate: 조회 시작 날짜 (거래 처리 시점 기준)
  • endDate: 조회 종료 날짜 (거래 처리 시점 기준)
  • o: 조회 옵션 (nil 가능)
  • startingAfter: 페이징을 위한 커서 (이전 조회 결과의 마지막 거래 ID)
  • limit: 조회할 거래 수 (최대 100개, 기본값 20개)

Returns:

  • []Transaction: 거래 내역 배열
  • error: 조회 실패 시 에러

Example:

// 최근 7일 거래 내역 조회
startDate := time.Now().AddDate(0, 0, -7)
endDate := time.Now()
transactions, err := client.TransactionsCheck(startDate, endDate, nil)

// 페이징으로 100개씩 조회
options := &TransactionOptions{
    Limit: 100,
}
transactions, err := client.TransactionsCheck(startDate, endDate, options)

func (*Client) VirtualAccountsIssue added in v0.0.8

func (c *Client) VirtualAccountsIssue(bank bankcode.Bank, customerName, orderId, orderName string, amount int, e []VirtualAccountsEscrowProducts, o *VirtualAccountsOptions) (*Payment, error)

type Payment

type Payment struct {
	Version             string                  `json:"version"`
	PaymentKey          string                  `json:"paymentKey"`
	Type                types.Payment           `json:"type"`
	OrderId             string                  `json:"orderId"`
	OrderName           string                  `json:"orderName"`
	MID                 string                  `json:"mId"`
	Currency            string                  `json:"currency"`
	Method              types.Method            `json:"method,omitempty"`
	TotalAmount         int                     `json:"totalAmount"`
	BalanceAmount       int                     `json:"balanceAmount"`
	Status              status.Payment          `json:"status"`
	RequestedAt         time.Time               `json:"requestedAt"`
	ApprovedAt          *time.Time              `json:"approvedAt,omitempty"`
	UseEscrow           bool                    `json:"useEscrow"`
	LastTransactionKey  string                  `json:"lastTransactionKey,omitempty"`
	SuppliedAmount      int                     `json:"suppliedAmount"`
	Vat                 int                     `json:"vat"`
	CultureExpense      bool                    `json:"cultureExpense"`
	TaxFreeAmount       int                     `json:"taxFreeAmount"`
	TaxExemptionAmount  int                     `json:"taxExemptionAmount"`
	Cancels             []PaymentCancel         `json:"cancels,omitempty"`
	IsPartialCancelable bool                    `json:"isPartialCancelable"`
	Card                *PaymentCard            `json:"card,omitempty"`
	VirtualAccount      *PaymentVirtualAccount  `json:"virtualAccount,omitempty"`
	Secret              string                  `json:"secret,omitempty"`
	MobilePhone         *PaymentMobilePhone     `json:"mobilePhone,omitempty"`
	GiftCertificate     *PaymentGiftCertificate `json:"giftCertificate,omitempty"`
	Transfer            *PaymentTransfer        `json:"transfer,omitempty"`
	Metadata            map[string]any          `json:"metadata,omitempty"`
	Receipt             *PaymentURL             `json:"receipt,omitempty"`
	Checkout            *PaymentURL             `json:"checkout,omitempty"`
	EasyPay             *PaymentEasyPay         `json:"easyPay,omitempty"`
	Country             string                  `json:"country"`
	Failure             *PaymentFailure         `json:"failure,omitempty"`
	CashReceipt         *PaymentCashReceipt     `json:"cashReceipt,omitempty"`
	CashReceipts        []PaymentCashReceipts   `json:"cashReceipts,omitempty"`
	Discount            *PaymentDiscount        `json:"discount,omitempty"`
}

type PaymentCancel added in v0.0.6

type PaymentCancel struct {
	CancelAmount           int       `json:"cancelAmount"`
	CancelReason           string    `json:"cancelReason"`
	TaxFreeAmount          int       `json:"taxFreeAmount"`
	TaxExemptionAmount     int       `json:"taxExemptionAmount"`
	RefundableAmount       int       `json:"refundableAmount"`
	TransferDiscountAmount int       `json:"transferDiscountAmount"`
	EasyPayDiscountAmount  int       `json:"easyPayDiscountAmount"`
	CanceledAt             time.Time `json:"canceledAt"`
	TransactionKey         string    `json:"transactionKey"`
	ReceiptKey             string    `json:"receiptKey,omitempty"`
	CancelStatus           string    `json:"cancelStatus"`
	CancelRequestId        string    `json:"cancelRequestId"`
}

type PaymentCancelOptions

type PaymentCancelOptions struct {
	CancelAmount         *int
	RefundReceiveAccount *PaymentCancelOptionsRefundReceiveAccount
	TaxFreeAmount        *int
	Currency             *string
}

type PaymentCancelOptionsRefundReceiveAccount

type PaymentCancelOptionsRefundReceiveAccount struct {
	Bank          *bankcode.Card
	AccountNumber *string
	HolderName    *string
}

type PaymentCard

type PaymentCard struct {
	Amount                int                 `json:"amount"`
	IssuerCode            bankcode.Card       `json:"issuerCode"`
	AcquirerCode          bankcode.Card       `json:"acquirerCode,omitempty"`
	Number                string              `json:"number"`
	InstallmentPlanMonths int                 `json:"installmentPlanMonths"`
	ApproveNo             string              `json:"approveNo"`
	UseCardPoint          bool                `json:"useCardPoint"`
	CardType              types.Card          `json:"cardType"`
	OwnerType             types.Owner         `json:"ownerType"`
	AcquireStatus         status.Acquire      `json:"acquireStatus"`
	IsInterestFree        bool                `json:"isInterestFree"`
	InterestPayer         types.InterestPayer `json:"interestPayer,omitempty"`
}

type PaymentCashReceipt

type PaymentCashReceipt struct {
	Type          string `json:"type"`
	ReceiptKey    string `json:"receiptKey"`
	IssueNumber   string `json:"issueNumber"`
	ReceiptUrl    string `json:"receiptUrl"`
	Amount        int    `json:"amount"`
	TaxFreeAmount int    `json:"taxFreeAmount"`
}

type PaymentCashReceipts

type PaymentCashReceipts struct {
	ReceiptKey             string          `json:"receiptKey"`
	OrderId                string          `json:"orderId"`
	OrderName              string          `json:"orderName"`
	Type                   string          `json:"type"`
	IssueNumber            string          `json:"issueNumber"`
	ReceiptUrl             string          `json:"receiptUrl"`
	BusinessNumber         string          `json:"businessNumber"`
	TransactionType        string          `json:"transactionType"`
	Amount                 int             `json:"amount"`
	TaxFreeAmount          int             `json:"taxFreeAmount"`
	IssueStatus            string          `json:"issueStatus"`
	Failure                *PaymentFailure `json:"failure,omitempty"`
	CustomerIdentityNumber string          `json:"customerIdentityNumber"`
	RequestedAt            time.Time       `json:"requestedAt"`
}

type PaymentDiscount

type PaymentDiscount struct {
	Amount int `json:"amount"`
}

type PaymentEasyPay

type PaymentEasyPay struct {
	Provider       bankcode.EasyPay `json:"provider"`
	Amount         int              `json:"amount"`
	DiscountAmount int              `json:"discountAmount"`
}

type PaymentFailure

type PaymentFailure struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

type PaymentGiftCertificate

type PaymentGiftCertificate struct {
	ApproveNo        string            `json:"approveNo"`
	SettlementStatus status.Settlement `json:"settlementStatus"`
}

type PaymentMobilePhone

type PaymentMobilePhone struct {
	CustomerMobilePhone string            `json:"customerMobilePhone"`
	SettlementStatus    status.Settlement `json:"settlementStatus"`
	ReceiptUrl          string            `json:"receiptUrl"`
}

type PaymentRefundReceiveAccount

type PaymentRefundReceiveAccount struct {
	BankCode      bankcode.Card `json:"bankCode"`
	AccountNumber string        `json:"accountNumber"`
	HolderName    string        `json:"holderName"`
}

type PaymentTransfer

type PaymentTransfer struct {
	BankCode         bankcode.Card     `json:"bankCode"`
	SettlementStatus status.Settlement `json:"settlementStatus"`
}

type PaymentURL

type PaymentURL struct {
	URL string `json:"url"`
}

type PaymentVirtualAccount

type PaymentVirtualAccount struct {
	AccountType          types.Account               `json:"accountType"`
	AccountNumber        string                      `json:"accountNumber"`
	BankCode             bankcode.Card               `json:"bankCode"`
	CustomerName         string                      `json:"customerName"`
	DueDate              time.Time                   `json:"dueDate"`
	RefundStatus         status.Refund               `json:"refundStatus"`
	Expired              bool                        `json:"expired"`
	SettlementStatus     status.Settlement           `json:"settlementStatus"`
	RefundReceiveAccount PaymentRefundReceiveAccount `json:"refundReceiveAccount,omitempty"`
}

type Settlement added in v0.0.3

type Settlement struct {
	MID             string                  `json:"mId"`
	PaymentKey      string                  `json:"paymentKey"`
	TransactionKey  string                  `json:"transactionKey"`
	OrderId         string                  `json:"orderId"`
	Currency        string                  `json:"currency"`
	Method          types.Method            `json:"method"`
	Amount          int                     `json:"amount"`
	InterestFee     int                     `json:"interestFee"`
	Fees            []SettlementFee         `json:"fees"`
	SupplyAmount    int                     `json:"supplyAmount"`
	Vat             int                     `json:"vat"`
	PayOutAmount    int                     `json:"payOutAmount"`
	ApprovedAt      time.Time               `json:"approvedAt"`
	SoldDate        string                  `json:"soldDate"`
	PaidOutDate     string                  `json:"paidOutDate"`
	Card            *PaymentCard            `json:"card,omitempty"`
	EasyPay         *PaymentEasyPay         `json:"easyPay,omitempty"`
	GiftCertificate *PaymentGiftCertificate `json:"giftCertificate,omitempty"`
	MobilePhone     *PaymentMobilePhone     `json:"mobilePhone,omitempty"`
	Transfer        *PaymentTransfer        `json:"transfer,omitempty"`
	VirtualAccount  *PaymentVirtualAccount  `json:"virtualAccount,omitempty"`
	Cancels         []PaymentCancel         `json:"cancels,omitempty"`
}

type SettlementFee added in v0.0.3

type SettlementFee struct {
	Type types.Fees `json:"type"`
	Fee  int        `json:"fee"`
}

type SettlementOptions added in v0.0.3

type SettlementOptions struct {
	Page *int
	Size *int
}

type Transaction added in v0.0.2

type Transaction struct {
	MID            string         `json:"mId"`
	TransactionKey string         `json:"transactionKey"`
	PaymentKey     string         `json:"paymentKey"`
	OrderId        string         `json:"orderId"`
	Method         types.Method   `json:"method"`
	CustomerKey    string         `json:"customerKey"`
	UseEscrow      bool           `json:"useEscrow"`
	ReceiptUrl     string         `json:"receiptUrl"`
	Status         status.Payment `json:"status"`
	TransactionAt  time.Time      `json:"transactionAt"`
	Currency       string         `json:"currency"`
	Amount         int            `json:"amount"`
}

type TransactionOptions added in v0.0.3

type TransactionOptions struct {
	StartingAfter *string
	Limit         *int
}

type VirtualAccountsEscrowProducts added in v0.0.8

type VirtualAccountsEscrowProducts struct {
	ID        string
	Name      string
	Code      string
	UnitPrice int
	Quantity  int
}

type VirtualAccountsOptions added in v0.0.8

type VirtualAccountsOptions struct {
	ValidHours          *int
	DueDate             *time.Time
	CustomerEmail       *string
	CustomerMobilePhone *string
	TaxFreeAmount       *int
	UseEscrow           *bool
	CashReceipt         *VirtualAccountsOptionsCashReceipt
}

type VirtualAccountsOptionsCashReceipt added in v0.0.8

type VirtualAccountsOptionsCashReceipt struct {
	Type               *types.CashReceipt
	RegistrationNumber *string
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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