Git Product home page Git Product logo

tinkoff's Introduction

Golang Tinkoff Acquiring API (v2) client

The package allows to send token-signed requests to Tinkoff Acquiring API and parse incoming HTTP notifications.

Acquiring API Docs: https://www.tinkoff.ru/kassa/dev/payments/

Contents

Installation

go get github.com/nikita-vanyasin/tinkoff@latest

Usage

Automatically generated documentation can be found here.

Some examples of usage can be found in *_test.go files.

Create client

Provide terminal key and password from terminal settings page.

client := tinkoff.NewClientWithOptions(
  WithTerminalKey(terminalKey),
  WithPassword(password),
  // Optional override HTTP client:
  // WithHTTPClient(myClient),
  // Optional override base Tinkoff Acquiring API URL:
  // WithBaseURL(myURL),
)

Handle HTTP notification

Example using gin:

router.POST("/payment/notification/tinkoff", func(c *gin.Context) {
    notification, err := client.ParseNotification(c.Request.Body)
    if err != nil {
        handleInternalError(c, err)
        return
    }

    // handle notification, e.g. update payment status in your DB

    // response well-formed body back on success. If you don't do this, the bank will send notification again later
    c.String(http.StatusOK, client.GetNotificationSuccessResponse())
}

Create payment

req := &tinkoff.InitRequest{
    Amount:      60000,
    OrderID:     "123456",
    CustomerKey: "123",
    Description: "some really useful product",
    RedirectDueDate: tinkoff.Time(time.Now().Add(4 * 24 * time.Hour)),
    Receipt: &tinkoff.Receipt{
        Email: "[email protected]",
        Items: []*tinkoff.ReceiptItem{
            {
                Price:    60000,
                Quantity: "1",
                Amount:   60000,
                Name:     "Product #1",
                Tax:      tinkoff.VATNone,
            },
        },
        Taxation: tinkoff.TaxationUSNIncome,
        Payments: &tinkoff.ReceiptPayments{
            Electronic: 60000,
        },
    },
    Data: map[string]string{
        "custom data field 1": "aasd6da78dasd9",
        "custom data field 2": "0",
    },
}

// Set timeout for Init request:
ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()

// Execute:
res, err := client.InitWithContext(ctx, req)
// ...
fmt.Println("payment form url: %s", res.PaymentPageURL)

Create QR

req := &tinkoff.InitRequest{
    Amount:      1000,                 // минимум 1000 копеек 
    OrderID:     "123456",
    Data: map[string]string{"": "",},  // nil - недопустим.
res, err := client.Init(req)
// ...
gqr := &tinkoff.GetQrRequest{
    PaymentID: res.PayID,
}
resQR, errQ := client.GetQRWithContext(ctx, gqr)

Cancel or refund payment

req := &tinkoff.CancelRequest{
    PaymentID: "66623",
    Amount: 60000,
}
res, err := client.CancelWithContext(ctx, req)

Get payment state

res, err := client.GetStateWithContext(ctx, &tinkoff.GetStateRequest{PaymentID: "3293"})
// ...
if res.Status == tinkoff.StatusConfirmed {
    fmt.Println("payment completed")
}

Confirm two-step payment

res, err := client.ConfirmWithContext(ctx, &tinkoff.ConfirmRequest{PaymentID: "3294"})
// ...
if res.Status == tinkoff.StatusConfirmed {
    fmt.Println("payment completed")
}

Resend notifications

res, err := c.ResendWithContext(ctx)
// ...
fmt.Println("resend has been scheduled for %d notifications", res.Count)

Helper functions

client.PostRequest allows you to implement API requests which are not implemented in this package yet (e.g. when Tinkoff Bank adds new method to API). Use BaseRequest type to implement any API request:

type myCouponUpgradeRequest struct {
  tinkoff.BaseRequest
  PaymentID string `json:"PaymentId"`
  Coupon    string `json:"coupon"`
}
httpResp, err := client.PostRequestWithContext(ctx, &myCouponUpgradeRequest{PaymentID: "3293", Coupon: "whatever"})

References

The code in this repo based on some code from koorgoo/tinkoff. Differences:

  • Support for API v2
  • 'reflect' package is not used. Zero dependencies.
  • No additional error wrapping

Contribution

All contributions are welcome! There are plenty of API methods that are not implemented yet due to their rare use-cases:

  • FinishAuthorize
  • Submit3DSAuthorization
  • Charge
  • AddCustomer / GetCustomer / RemoveCustomer
  • GetCardList / RemoveCard

tinkoff's People

Contributors

alextransit avatar nikita-vanyasin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

tinkoff's Issues

Без указания Amount при отмене api ругается на невалидный токен

Привет!
Есть вызов:

req := &tinkoff.CancelRequest{
		PaymentID: payment.ID,
}
_, err = tinkoffClient.Cancel(req)
if err != nil {
	...
	return
}

При формировании токена Amount равен нулю и после конкатенации и вычисления хеша этот токен становится невалиден для api, видимо они вообще не хотят получать этот 0, судя по документации тинькофф вызов без Amount - вполне обычная ситуация, так как параметр необязателен, вот пример из их доки:

{
 "TerminalKey" :" TinkoffBankTest",
 "PaymentId" : "2164657",
 "Token" : "328a1ed43e3800c142b298fbb01772c739c524dd455717c8a9152428037439fb"
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.