### Install YooKassa Go SDK Source: https://github.com/rvinnie/yookassa-sdk-go/blob/main/README.en.md Installs the YooKassa Go SDK using the Go module system. This command fetches the library and its dependencies, making it available for use in your Go projects. ```Go go get github.com/rvinnie/yookassa-sdk-go ``` -------------------------------- ### Go Yookassa Webhook Processing with IP Filtering Source: https://github.com/rvinnie/yookassa-sdk-go/blob/main/docs/examples/04-webhooks.en.md This Go example demonstrates how to set up an HTTP server to receive and process Yookassa webhook events. It includes a custom middleware for IP address filtering, ensuring that only requests originating from allowed CIDR ranges (e.g., Yookassa's official IP addresses) are processed. The example also illustrates how to parse the incoming JSON webhook data into a `yoowebhook.WebhookEvent` structure and emphasizes the importance of responding with an HTTP 200 OK status to acknowledge receipt and prevent re-delivery attempts. ```go package main import ( "encoding/json" "log" "net" "net/http" "strings" yoowebhook "github.com/rvinnie/yookassa-sdk-go/yookassa/webhook" ) func main() { // Allowed CIDR ranges. allowedCIDRs := []string{ "127.0.0.1/32", // IPv4 localhost "::1/128", // IPv6 localhost } // Create a router. mux := http.NewServeMux() mux.HandleFunc("/webhooks", HandleWebhook) // Add middleware for IP filtering. protectedMux := IPFilterMiddleware(mux, allowedCIDRs) // Start the HTTP server. log.Println("Starting server on :8080") err := http.ListenAndServe(":8080", protectedMux) if err != nil { log.Fatalf("Server failed to start: %v", err) } } // HandleWebhook processes webhook requests. func HandleWebhook(w http.ResponseWriter, r *http.Request) { // Parse JSON data from the request body. var webhookEvent yoowebhook.WebhookEvent err := json.NewDecoder(r.Body).Decode(&webhookEvent) if err != nil { http.Error(w, "Invalid webhook data", http.StatusBadRequest) return } // Log data. log.Printf("Webhook processed: %+v", webhookEvent) log.Printf("Webhook Type: %+v", webhookEvent.Type) log.Printf("Event: %+v", webhookEvent.Event) log.Printf("Payment Data: %+v", webhookEvent.Object) // Return HTTP status 200 OK. w.WriteHeader(http.StatusOK) } // Middleware to check allowed IP addresses. func IPFilterMiddleware(next http.Handler, allowedCIDRs []string) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { remoteIP := r.RemoteAddr log.Printf("Initial remote IP: %s", remoteIP) // Check X-Real-IP header if available. if realIP := r.Header.Get("X-Real-IP"); realIP != "" { log.Printf("Using X-Real-IP header: %s", realIP) remoteIP = realIP } // Split the address into host and port. var host string if strings.Contains(remoteIP, ":") { var err error host, _, err = net.SplitHostPort(remoteIP) if err != nil { http.Error(w, "Invalid remote IP address", http.StatusBadRequest) return } } else { host = remoteIP } // Check if the IP address is allowed. if !IsIPAllowed(host, allowedCIDRs) { http.Error(w, "Forbidden", http.StatusForbidden) return } // Pass control to the next handler. next.ServeHTTP(w, r) }) } // Check if the IP address is within the allowed ranges. func IsIPAllowed(ip string, allowedCIDRs []string) bool { parsedIP := net.ParseIP(ip) if parsedIP == nil { return false } for _, cidr := range allowedCIDRs { _, allowedNet, err := net.ParseCIDR(cidr) if err != nil { continue } if allowedNet.Contains(parsedIP) { return true } } return false } ``` -------------------------------- ### List and Filter YooKassa Payments in Go Source: https://github.com/rvinnie/yookassa-sdk-go/blob/main/docs/examples/02-payments.en.md Shows how to retrieve a paginated list of payments from YooKassa, applying filters such as status and limit. The example demonstrates iterating through payment batches using the `next_cursor` for pagination, ensuring all relevant payments are retrieved. ```go package main import ( "github.com/rvinnie/yookassa-sdk-go/yookassa" "github.com/rvinnie/yookassa-sdk-go/yookassa/payment" ) func main() { // Create a yookassa client by specifying the store ID and secret key yooclient := yookassa.NewClient('', '') // Create a payment handler paymentHandler := yookassa.NewPaymentHandler(yooclient) // Get all 'succeeded' payments of 3 per request var cursor string for { paymentsBatch, _ := paymentHandler.FindPayments(&yoopayment.PaymentListFilter{ Limit: 3, Cursor: cursor, Status: yoopayment.Succeeded, }) cursor = paymentsBatch.NextCursor // If the current piece of payments is the last one, exit the loop if cursor == "" { break } } } ``` -------------------------------- ### Confirm Payment with Yookassa Go SDK Source: https://github.com/rvinnie/yookassa-sdk-go/blob/main/docs/examples/02-payments.md This example illustrates how to confirm a payment that is awaiting capture using the Yookassa Go SDK. Payments must be confirmed within a specific timeframe while in 'waiting_for_capture' status; otherwise, they will be automatically canceled. The snippet first creates a payment, simulates a delay, and then captures the payment, transitioning it to a 'succeeded' status. ```Go import ( "github.com/rvinnie/yookassa-sdk-go/yookassa" "github.com/rvinnie/yookassa-sdk-go/yookassa/payment" ) func main() { // Create a Yookassa client, specifying the shop ID and secret key yooclient := yookassa.NewClient('', '') // Create a payment handler paymentHandler := yookassa.NewPaymentHandler(yooclient) // Create payment payment, _ := paymentHandler.CreatePayment(&yoopayment.Payment{ Amount: &yoopayment.Amount{ Value: "1000.00", Currency: "RUB", }, PaymentMethod: yoopayment.PaymentMethodType("bank_card"), Confirmation: yoopayment.Redirect{ Type: "redirect", ReturnURL: "https://www.example.com", }, Description: "Test payment", }) // Wait for payment completion for 30 seconds time.Sleep(time.Second * 30) // Confirm payment payment, _ = paymentHandler.CapturePayment(payment) } ``` -------------------------------- ### Cancel YooKassa Payment in Go Source: https://github.com/rvinnie/yookassa-sdk-go/blob/main/docs/examples/02-payments.en.md Demonstrates how to cancel a payment with `waiting_for_capture` status using the YooKassa Go SDK. This operation initiates a refund to the payer's account. The example shows creating a payment, simulating a wait, and then canceling it by its ID. ```go import ( "github.com/rvinnie/yookassa-sdk-go/yookassa" "github.com/rvinnie/yookassa-sdk-go/yookassa/payment" ) func main() { // Create a yookassa client by specifying the store ID and secret key yooclient := yookassa.NewClient('', '') // Create a payment handler paymentHandler := yookassa.NewPaymentHandler(yooclient) // Create a payment payment, _ := paymentHandler.CreatePayment(&yoopayment.Payment{ Amount: &yoopayment.Amount{ Value: "1000.00", Currency: "RUB", }, PaymentMethod: yoopayment.PaymentMethodType("bank_card"), Confirmation: yoopayment.Redirect{ Type: "redirect", ReturnURL: "https://www.example.com", }, Description: "Test payment", }) // We are waiting for the payment to be made 30 seconds time.Sleep(time.Second * 30) // Cancel payment payment, _ = paymentHandler.CancelPayment(payment.ID) } ``` -------------------------------- ### Create Payment using Yookassa Go SDK Source: https://github.com/rvinnie/yookassa-sdk-go/blob/main/docs/examples/02-payments.en.md This Go code demonstrates how to initialize the Yookassa client with store credentials and create a new payment. It configures the payment amount, currency, method (bank card), and a redirect URL for user confirmation, along with a description. ```go import ( "github.com/rvinnie/yookassa-sdk-go/yookassa" "github.com/rvinnie/yookassa-sdk-go/yookassa/payment" ) func main() { // Create a yookassa client by specifying the store ID and secret key yooclient := yookassa.NewClient('', '') // Create a payment handler paymentHandler := yookassa.NewPaymentHandler(yooclient) // Create a payment payment, _ := paymentHandler.CreatePayment(&yoopayment.Payment{ Amount: &yoopayment.Amount{ Value: "1000.00", Currency: "RUB", }, PaymentMethod: yoopayment.PaymentMethodType("bank_card"), Confirmation: yoopayment.Redirect{ Type: "redirect", ReturnURL: "https://www.example.com", }, Description: "Test payment", }) } ``` -------------------------------- ### Create Payment with Yookassa Go SDK Source: https://github.com/rvinnie/yookassa-sdk-go/blob/main/docs/examples/02-payments.md This snippet demonstrates how to initiate a new payment using the Yookassa Go SDK. It involves setting up the Yookassa client with your shop credentials, creating a payment handler, and then defining the payment details such as amount, currency, payment method, and confirmation URL. The SDK returns a Payment object with its current status. ```Go import ( "github.com/rvinnie/yookassa-sdk-go/yookassa" "github.com/rvinnie/yookassa-sdk-go/yookassa/payment" ) func main() { // Create a Yookassa client, specifying the shop ID and secret key yooclient := yookassa.NewClient('', '') // Create a payment handler paymentHandler := yookassa.NewPaymentHandler(yooclient) // Create payment payment, _ := paymentHandler.CreatePayment(&yoopayment.Payment{ Amount: &yoopayment.Amount{ Value: "1000.00", Currency: "RUB", }, PaymentMethod: yoopayment.PaymentMethodType("bank_card"), Confirmation: yoopayment.Redirect{ Type: "redirect", ReturnURL: "https://www.example.com", }, Description: "Test payment", }) } ``` -------------------------------- ### Retrieve YooKassa Store Information in Go Source: https://github.com/rvinnie/yookassa-sdk-go/blob/main/docs/examples/01-configuration.en.md This Go code shows how to create a YooKassa client, initialize a settings handler, and then fetch account settings. The retrieved settings object contains details about the store, such as its ID, test status, fiscalization status, and supported payment methods. ```go import "github.com/rvinnie/yookassa-sdk-go/yookassa" func main() { // Create a yookassa client by specifying the store ID and secret key yooclient := yookassa.NewClient('', '') // Create a settings handler settingsHandler := yookassa.NewSettingsHandler(yooclient) // Get information about store or gateway settings settings, _ := settingsHandler.GetAccountSettings(nil) } ``` -------------------------------- ### Authenticate YooKassa Client in Go Source: https://github.com/rvinnie/yookassa-sdk-go/blob/main/docs/examples/01-configuration.en.md This snippet demonstrates how to initialize the YooKassa client in Go by providing the store ID and secret key. This client instance is essential for all subsequent API interactions. ```go import "github.com/rvinnie/yookassa-sdk-go" func main() { client := yookassa.NewClient('', '') } ``` -------------------------------- ### Create Yookassa Payment Refund in Go Source: https://github.com/rvinnie/yookassa-sdk-go/blob/main/docs/examples/03-refunds.en.md This snippet demonstrates how to initiate a refund for a successful payment using the Yookassa Go SDK. It requires the original payment's ID, the amount to refund (value and currency), and an optional description. The SDK handles the API call, returning a `Refund` object in its current status upon success. ```go import ( "github.com/rvinnie/yookassa-sdk-go/yookassa" "github.com/rvinnie/yookassa-sdk-go/yookassa/refund" ) func main() { // Create a yookassa client by specifying the store ID and secret key yooclient := yookassa.NewClient('', '') // Create a refund handler refundHandler := yookassa.NewRefundHandler(client) // Create a refund refund, err := refundHandler.CreateRefund(&yoorefund.Refund{ PaymentId: "2c79414f-000f-5100-9000-1d082dd142ea", Amount: &yoocommon.Amount{ Value: "123", Currency: "RUB", }, Description: "Test refund :)", }) } ``` -------------------------------- ### Configure YooKassa Go Client Source: https://github.com/rvinnie/yookassa-sdk-go/blob/main/README.en.md Initializes a new YooKassa API client instance. This client is configured with your unique Account ID and Secret Key, which are required for authenticating API requests. ```Go import "github.com/rvinnie/yookassa-sdk-go" func main() { client := yookassa.NewClient('', '') } ``` -------------------------------- ### YooKassa API Account Settings Object (me_object) Structure Source: https://github.com/rvinnie/yookassa-sdk-go/blob/main/docs/examples/01-configuration.en.md This API documentation describes the structure of the `me_object` returned by the YooKassa API's account settings endpoint. It provides details about the store's configuration, including its ID, operational status, and enabled features. ```APIDOC me_object: account_id: string (e.g., "XXXXXX") - The unique identifier of the store account. test: boolean (e.g., true) - Indicates if the account is in test mode. fiscalization_enabled: boolean (e.g., true) - Indicates if fiscalization is enabled for the account. payment_methods: array of strings (e.g., ["yoo_money", "bank_card"]) - A list of payment methods enabled for the account. status: string (e.g., "enabled") - The current status of the account (e.g., "enabled", "disabled"). ``` -------------------------------- ### List Yookassa Payment Refunds with Filtering in Go Source: https://github.com/rvinnie/yookassa-sdk-go/blob/main/docs/examples/03-refunds.en.md This snippet shows how to retrieve a list of refunds, applying various filters such as `Status` and `Limit` to narrow down the results. The `FindRefunds` method allows fetching fragments of the list, sorted by creation time in descending order, and provides a `next_cursor` for pagination if more results exist than the specified limit. ```go import ( "github.com/rvinnie/yookassa-sdk-go/yookassa" "github.com/rvinnie/yookassa-sdk-go/yookassa/refund" ) func main() { // Create a yookassa client by specifying the store ID and secret key yooclient := yookassa.NewClient('', '') // Create a refund handler refundHandler := yookassa.NewRefundHandler(client) // We get a list of payment objects (the last 3 with the status succeeded) refunds, err := refundHandler.FindRefunds(&yoorefund.RefundListFilter{ Status: yoorefund.Succeeded, Limit: 3, }) } ``` -------------------------------- ### Capture and Confirm Payment using Yookassa Go SDK Source: https://github.com/rvinnie/yookassa-sdk-go/blob/main/docs/examples/02-payments.en.md This Go code illustrates the process of creating a payment and subsequently capturing it. Payments must be in 'waiting_for_capture' status to be confirmed. After capture, the payment status changes to 'succeeded', allowing the service or product to be provided. ```go import ( "github.com/rvinnie/yookassa-sdk-go/yookassa" "github.com/rvinnie/yookassa-sdk-go/yookassa/payment" ) func main() { // Create a yookassa client by specifying the store ID and secret key yooclient := yookassa.NewClient('', '') // Create a payment handler paymentHandler := yookassa.NewPaymentHandler(yooclient) // Create a payment payment, _ := paymentHandler.CreatePayment(&yoopayment.Payment{ Amount: &yoopayment.Amount{ Value: "1000.00", Currency: "RUB", }, PaymentMethod: yoopayment.PaymentMethodType("bank_card"), Confirmation: yoopayment.Redirect{ Type: "redirect", ReturnURL: "https://www.example.com", }, Description: "Test payment", }) // We are waiting for the payment to be made 30 seconds time.Sleep(time.Second * 30) // We confirm the payment payment, _ = paymentHandler.CapturePayment(payment) } ``` -------------------------------- ### Import YooKassa Go SDK Module Source: https://github.com/rvinnie/yookassa-sdk-go/blob/main/README.en.md Imports the YooKassa Go SDK package into your Go application. This step is necessary to access the client and other functionalities provided by the SDK. ```Go import "github.com/rvinnie/yookassa-sdk-go" ``` -------------------------------- ### List YooKassa Payments with Filtering and Pagination in Go SDK Source: https://github.com/rvinnie/yookassa-sdk-go/blob/main/docs/examples/02-payments.md This Go code snippet demonstrates how to retrieve a list of YooKassa payments, applying filters such as status (e.g., 'succeeded') and handling pagination. Payments created within the last 3 years are returned, sorted by creation time in descending order. The `next_cursor` parameter is used to fetch subsequent fragments of the list. ```go package main import ( "github.com/rvinnie/yookassa-sdk-go/yookassa" "github.com/rvinnie/yookassa-sdk-go/yookassa/payment" ) func main() { // Создаем yookassa клиента, указав идентификатор магазина и секретный ключ yooclient := yookassa.NewClient('<Идентификатор магазина>', '<Секретный ключ>') // Создаем обработчик платежей paymentHandler := yookassa.NewPaymentHandler(yooclient) // Получаем все 'succeeded' платежи по 3 штуки за запрос var cursor string for { paymentsBatch, _ := paymentHandler.FindPayments(&yoopayment.PaymentListFilter{ Limit: 3, Cursor: cursor, Status: yoopayment.Succeeded, }) cursor = paymentsBatch.NextCursor // Если текущий кусок платежей последний, выходим из цикла if cursor == "" { break } } } ``` -------------------------------- ### Retrieve Yookassa Payment Refund Details in Go Source: https://github.com/rvinnie/yookassa-sdk-go/blob/main/docs/examples/03-refunds.en.md This snippet illustrates how to fetch detailed information about a specific refund using its unique identifier. It utilizes the `FindRefund` method of the `RefundHandler` to query the Yookassa API, returning a `Refund` object with its current status. This allows checking the state and details of a previously initiated refund. ```go import ( "github.com/rvinnie/yookassa-sdk-go/yookassa" "github.com/rvinnie/yookassa-sdk-go/yookassa/refund" ) func main() { // Create a yookassa client by specifying the store ID and secret key yooclient := yookassa.NewClient('', '') // Create a refund handler refundHandler := yookassa.NewRefundHandler(client) // Get the refund object refund, _ := refundHandler.FindRefund("2c87b72c-0015-5000-9000-172b6038152a") } ``` -------------------------------- ### Retrieve Single YooKassa Payment Information in Go Source: https://github.com/rvinnie/yookassa-sdk-go/blob/main/docs/examples/02-payments.en.md Illustrates how to fetch details of a specific payment by its unique ID using the YooKassa Go SDK. The response provides the `Payment` object with its current status, allowing you to check the payment's state. ```go package main import "github.com/rvinnie/yookassa-sdk-go/yookassa" func main() { // Create a yookassa client by specifying the store ID and secret key yooclient := yookassa.NewClient('', '') // Create a payment handler paymentHandler := yookassa.NewPaymentHandler(yooclient) // Getting payment information p, _ := paymentHandler.FindPayment("21b23b5b-000f-5061-a000-0674e49a8c10") } ``` -------------------------------- ### Retrieve YooKassa Payment Information using Go SDK Source: https://github.com/rvinnie/yookassa-sdk-go/blob/main/docs/examples/02-payments.md This Go code snippet illustrates how to retrieve the current status and details of a specific YooKassa payment using its unique identifier. The `FindPayment` method returns the complete payment object. ```go package main import "github.com/rvinnie/yookassa-sdk-go/yookassa" func main() { // Создаем yookassa клиента, указав идентификатор магазина и секретный ключ yooclient := yookassa.NewClient('<Идентификатор магазина>', '<Секретный ключ>') // Создаем обработчик платежей paymentHandler := yookassa.NewPaymentHandler(yooclient) // Получаем информацию о платеже p, _ := paymentHandler.FindPayment("21b23b5b-000f-5061-a000-0674e49a8c10") } ``` -------------------------------- ### Simulate YooKassa Payment Waiting for Capture Webhook (Bash) Source: https://github.com/rvinnie/yookassa-sdk-go/blob/main/docs/examples/04-webhooks.en.md This `curl` command demonstrates how to send a `payment.waiting_for_capture` webhook notification to a local endpoint (e.g., `http://localhost:8080/webhooks`). This is useful for testing the handling of payment status updates in a development environment without relying on actual YooKassa events. The command includes a comprehensive JSON payload representing a payment in the 'waiting_for_capture' status. ```bash curl -i --location 'http://localhost:8080/webhooks' \ --header 'Content-Type: application/json' \ --data '{ "type": "notification", "event": "payment.waiting_for_capture", "object": { "id": "22d6d597-000f-5000-9000-145f6df21d6f", "status": "waiting_for_capture", "paid": true, "amount": { "value": "2.00", "currency": "RUB" }, "authorization_details": { "rrn": "10000000000", "auth_code": "000000", "three_d_secure": { "applied": true } }, "created_at": "2018-07-10T14:27:54.691Z", "description": "Order #72", "expires_at": "2018-07-17T14:28:32.484Z", "metadata": {}, "payment_method": { "type": "bank_card", "id": "22d6d597-000f-5000-9000-145f6df21d6f", "saved": false, "card": { "first6": "555555", "last4": "4444", "expiry_month": "07", "expiry_year": "2021", "card_type": "MasterCard", "issuer_country": "RU", "issuer_name": "Sberbank" }, "title": "Bank card *4444" }, "refundable": false, "test": false } } ' ``` -------------------------------- ### Simulate Yookassa 'payment.waiting_for_capture' Webhook with cURL Source: https://github.com/rvinnie/yookassa-sdk-go/blob/main/docs/examples/04-webhooks.md This cURL command sends a POST request to a local webhook endpoint (`http://localhost:8080/webhooks`) with a JSON payload representing a `payment.waiting_for_capture` notification from Yookassa. It's used for local development and testing of webhook handlers, allowing developers to verify their application's response to specific payment events. ```bash curl -i --location 'http://localhost:8080/webhooks' \ --header 'Content-Type: application/json' \ --data '{ "type": "notification", "event": "payment.waiting_for_capture", "object": { "id": "22d6d597-000f-5000-9000-145f6df21d6f", "status": "waiting_for_capture", "paid": true, "amount": { "value": "2.00", "currency": "RUB" }, "authorization_details": { "rrn": "10000000000", "auth_code": "000000", "three_d_secure": { "applied": true } }, "created_at": "2018-07-10T14:27:54.691Z", "description": "Заказ №72", "expires_at": "2018-07-17T14:28:32.484Z", "metadata": {}, "payment_method": { "type": "bank_card", "id": "22d6d597-000f-5000-9000-145f6df21d6f", "saved": false, "card": { "first6": "555555", "last4": "4444", "expiry_month": "07", "expiry_year": "2021", "card_type": "MasterCard", "issuer_country": "RU", "issuer_name": "Sberbank" }, "title": "Bank card *4444" }, "refundable": false, "test": false } } ' ``` -------------------------------- ### Cancel YooKassa Payment using Go SDK Source: https://github.com/rvinnie/yookassa-sdk-go/blob/main/docs/examples/02-payments.md This Go code snippet demonstrates how to cancel a YooKassa payment that is in `waiting_for_capture` status. The cancellation initiates a refund to the payer. For bank cards and YuMoney wallets, cancellation is instant, while other methods may take several days. The response will contain the payment object with its updated status. ```go import ( "github.com/rvinnie/yookassa-sdk-go/yookassa" "github.com/rvinnie/yookassa-sdk-go/yookassa/payment" ) func main() { // Создаем yookassa клиента, указав идентификатор магазина и секретный ключ yooclient := yookassa.NewClient('<Идентификатор магазина>', '<Секретный ключ>') // Создаем обработчик платежей paymentHandler := yookassa.NewPaymentHandler(yooclient) // Создаем платеж payment, _ := paymentHandler.CreatePayment(&yoopayment.Payment{ Amount: &yoopayment.Amount{ Value: "1000.00", Currency: "RUB", }, PaymentMethod: yoopayment.PaymentMethodType("bank_card"), Confirmation: yoopayment.Redirect{ Type: "redirect", ReturnURL: "https://www.example.com", }, Description: "Test payment", }) // Ожидаем совершение платежа 30 секунд time.Sleep(time.Second * 30) // Отменяем платеж payment, _ = paymentHandler.CancelPayment(payment.ID) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.