redsys

package module
v0.6.8 Latest Latest
Warning

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

Go to latest
Published: Feb 2, 2025 License: MIT Imports: 13 Imported by: 0

README

redsys-golang

Go Reference

Redsys integration for Go.

Install

go get github.com/altipla-consulting/redsys-golang

Usage

Follow this steps to integrate with Redsys:

  1. First and foremost you will need to request the bank credentials in person at your entity. The will provide you with access to the test environment along with the following important information:

    • Merchant code.
    • Terminal number.
    • A signing key.

    In the test environment, you will have access to PDFs describing the integration process we are preparing. We recommend reading these documents thoroughly to understand how the different methods work.

    You can also read this more concise documentation: https://pagosonline.redsys.es/conexion-redireccion.html

  2. Sign the payment server-side with this library:

    sess := redsys.Session{
      Order:  "0001abcdabcd",
      Lang:   redsys.LangES,
      Client: "John Doe",
      Amount: 1234,
      Product: "My Awesome Product",
      URLOK:   "https://www.example.com/order-confirmed",
      URLKO:   "https://www.example.com/order-cancelled",
      Data:    "custom-data",
    }
    merchant := redsys.Merchant{
      Code:     "1234_YOUR_MERCHANT_CODE",
      Name:     "My Awesome Shop",
      Terminal: 1234,
      Secret:   "YOUR_SECRET",
      URLNotification: "https://www.example.com/background-notification",
      Debug:    true,
    }
    signed, err := redsys.Sign(ctx, merchant, rs)
    if err != nil {
      return nil, errors.Trace(err)
    }
    
  3. Send a form from the browser to the bank. It is important to send it client-side; it can't be a POST request from Go. Sending the form will redirect the user to the bank to make the payment.

    You can prepare a HTML form:

    <form method="POST" action="{{.Signed.Endpoint}}">
      <input type="hidden" name="Ds_SignatureVersion" value="{{.Signed.SignatureVersion}}">
      <input type="hidden" name="Ds_Signature" value="{{.Signed.Signature}}">
      <input type="hidden" name="Ds_MerchantParameters" value="{{.Signed.Params}}">
    
      <button type="submit">Submit</button>
    </form>
    

    If you are in a more dynamic environment (e.g. with React or Vue using APIs to sign the transaction) you can also use a pure Javascript solution to build and send the form:

    // DOM manipulation to create a fake form that we can send to the
    // remote POST endpoint of the bank network.
    let form = document.createElement('form')
    form.setAttribute('method', 'POST')
    form.setAttribute('action', params.url)
    
    let input = document.createElement('input')
    input.setAttribute('type', 'hidden')
    input.setAttribute('name', 'Ds_SignatureVersion')
    input.value = params.signatureVersion
    form.appendChild(input)
    
    input = document.createElement('input')
    input.setAttribute('type', 'hidden')
    input.setAttribute('name', 'Ds_Signature')
    input.value = params.signature
    form.appendChild(input)
    
    input = document.createElement('input')
    input.setAttribute('type', 'hidden')
    input.setAttribute('name', 'Ds_MerchantParameters')
    input.value = params.params
    form.appendChild(input)
    document.body.appendChild(form)
    
    form.submit()
    
  4. The user will complete the transaction, cancel, verify its credit card, etc. on the bank page. When the transaction finishes (successfully or not), a background notification will be sent automatically to the configured endpoint. In parallel, the user will be redirected to the OK/KO page. Both requests will have parameters in the query string that can be read.

  5. Verify the received parameters. Since anyone can send requests to public pages, you need to ensure the bank has signed the data and everything is legal and secure. Use our library to verify the parameters:

    signed := redsys.Signed{
      SignatureVersion: r.FormValue("Ds_SignatureVersion"),
      Params:           r.FormValue("Ds_MerchantParameters"),
      Signature:        r.FormValue("Ds_Signature"),
    }
    operation, err := redsys.Confirm(ctx, "YOUR_SECRET", signed)
    if err != nil {
      return nil, errors.Trace(err)
    }    
    
  6. Use the operation variable to show messages to the user, approve the transaction and perform any necessary actions according to its status and data.

Contributing

You can make pull requests or create issues in GitHub. Any code you send should be formatted using make gofmt.

License

MIT License

Documentation

Index

Constants

View Source
const (
	EndpointProduction = "https://sis.redsys.es/sis/realizarPago"
	EndpointDebug      = "https://sis-t.redsys.es:25443/sis/realizarPago"
)
View Source
const (
	LangES = Lang("001")
	LangEN = Lang("002")
	LangCA = Lang("003")
	LangFR = Lang("004")
	LangDE = Lang("005")
	LangIT = Lang("007")
	LangPT = Lang("009")
)
View Source
const (
	PaymentMethodCreditCard = PaymentMethod("C")
	PaymentMethodBizum      = PaymentMethod("z")
	PaymentMethodPaypal     = PaymentMethod("P")
)
View Source
const (
	// StatusUnknown means the transaction has not been correctly detected. You can error out as a cancellation
	// or as an error depending on the context.
	StatusUnknown = Status("")

	// StatusApproved means the transaction was approved by the bank and the money was transferred.
	StatusApproved = Status("approved")

	// StatusCancelled means the transaction was cancelled by the user.
	StatusCancelled = Status("cancelled")

	// StatusRepeated means the transaction has been sent repeatedly to the bank. It is a programming error that should
	// not happen if a different Order code is used for each retry.
	StatusRepeated = Status("repeated")
)
View Source
const (
	CurrencyEuros = Currency(978)
)
View Source
const (
	TransactionTypeSimpleAuthorization = TransactionType(0)
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Currency

type Currency int64

type Lang

type Lang string

type Merchant

type Merchant struct {
	// Merchant code assigned by the bank.
	Code string

	// Merchant name to show in the receipt. You can freely use any appropiate name.
	Name string

	// Terminal number assigned by the bank.
	Terminal int64

	// Secret to sign transactions assigned by the bank.
	Secret string

	// URL where the asynchronous background notification will be sent.
	URLNotification string

	// Send the data to the test endpoint of the bank.
	Debug bool
}

Merchant data provided by the bank itself during the integration.

type Operation

type Operation struct {
	// Status of the operation.
	Status Status

	// Sent date of the operation.
	Sent time.Time

	// All the parsed parameters of the transaction.
	Params Params

	// True if the transaction was a credit card payment.
	IsCreditCard bool

	// Raw response code of the bank.
	ResponseCode int64
}

Operation represents the result of a payment operation.

func Confirm

func Confirm(ctx context.Context, secret string, signed Signed) (Operation, error)

Confirm reads the response from the bank and parses the response to determine the status of the transaction in a more easy to use way. If an error is returned the input data is compromised and should not be used, the returned operation will also be empty.

type Params

type Params struct {
	// Response code of the bank.
	Response int64 `json:"-"`

	// Order code of the transaction.
	Order string `json:"Ds_Order"`

	// Original order code as a string that sometimes comes back empty.
	RawResponse string `json:"Ds_Response"`

	// Date of the transaction in the format "02/01/2006".
	Date string `json:"Ds_Date"`

	// Hour of the transaction in the format "15:04".
	Time string `json:"Ds_Hour"`

	// Country code of the card.
	Country string `json:"Ds_Card_Country"`

	// Authorization code of the card. Should be stored to have a reference to the transaction.
	AuthCode string `json:"Ds_AuthorisationCode"`

	// Card type: MasterCard, Visa, etc.
	CardType string `json:"Ds_Card_Type"`

	// Custom data previously sent that comes back in the confirmation.
	Data string `json:"Ds_MerchantData"`
}

Parsed parameters of the transaction.

func ParseParams

func ParseParams(signed Signed) (Params, error)

ParseParams reads the response from the bank and returns the parsed parameters if the signature is valid. If an error is returned the input data is compromised and should not be used, the returned params will also be empty.

type PaymentMethod added in v0.6.0

type PaymentMethod string

type Session

type Session struct {
	// Code of the session. It should have 4 digits and 8 characters. It should be unique for each retry of the payment.
	Order string

	// Language code. Use English if unknown.
	Lang Lang

	// Name of the client to show in the receipt. Use any appropiate info available.
	Client string

	// Amount in cents to pay.
	Amount int32

	// Product name to show in the receipt.
	Product string

	// URL to return the user to when the transaction is approved.
	URLOK string

	// URL to return the user to when the transaction is cancelled.
	URLKO string

	// Raw custom data that will be sent back in the confirmation when the transaction finishes. You can use it to store
	// identifiers or any other data that facilitates the verification afterwards.
	Data string

	// Payment method to use. By default it will be credit card if empty.
	PaymentMethod PaymentMethod
}

Session data that changes for each payment the merchant wants to make.

type Signed

type Signed struct {
	// Signature of the parameters. Assign to Ds_Signature.
	Signature string

	// Version of the signature. Assign to Ds_SignatureVersion.
	SignatureVersion string

	// Params to send. Assign to Ds_MerchantParameters.
	Params string

	// Output only. It will return the endpoint of the call where the info should be sent.
	Endpoint string
}

Signed TPV transaction to send to the bank.

func Sign

func Sign(ctx context.Context, merchant Merchant, session Session) (Signed, error)

Sign takes all the input data and returns the parameters to be sent to the bank.

type Status

type Status string

Status of a finished transaction.

type TransactionType

type TransactionType int64

Jump to

Keyboard shortcuts

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