### Manage PayPal Authorizations in Go Source: https://github.com/plutov/paypal/blob/master/README.md Provides Go code examples for managing PayPal authorizations. This includes getting, capturing, voiding, and reauthorizing existing authorizations using the PayPal client. ```go // Get authorization auth, err := c.GetAuthorization("2DC87612EK520411B") // Capture authorization capture, err := c.CaptureAuthorization(authID, &paypal.Amount{Total: "7.00", Currency: "USD"}, true) // Void authorization auth, err := c.VoidAuthorization(authID) // Reauthorize authorization auth, err := c.ReauthorizeAuthorization(authID, &paypal.Amount{Total: "7.00", Currency: "USD"}) ``` -------------------------------- ### Create PayPal Subscription in Go Source: https://context7.com/plutov/paypal/llms.txt Creates a customer subscription using a previously defined subscription plan. This function sets up the customer's details, start time, and application context for the subscription. It requires a PayPal client and the plan ID. ```go import ( "context" "fmt" "time" "github.com/paypal/paypal-checkout-sdk-go/v2/paypal" ) func createSubscription(client *paypal.Client, planID string) (*paypal.SubscriptionDetailResp, error) { ctx := context.Background() startTime := paypal.JSONTime(time.Now().Add(24 * time.Hour)) subscription := paypal.SubscriptionBase{ PlanID: planID, StartTime: &startTime, Subscriber: &paypal.Subscriber{ Name: paypal.CreateOrderPayerName{ GivenName: "John", Surname: "Doe", }, EmailAddress: "john.doe@example.com", }, ApplicationContext: &paypal.ApplicationContext{ BrandName: "My SaaS App", Locale: "en-US", ShippingPreference: "NO_SHIPPING", UserAction: "SUBSCRIBE_NOW", ReturnURL: "https://example.com/subscription/return", CancelURL: "https://example.com/subscription/cancel", }, } response, err := client.CreateSubscription(ctx, subscription) if err != nil { return nil, fmt.Errorf("failed to create subscription: %w", err) } fmt.Printf("Subscription created: ID=%s, Status=%s\n", response.ID, response.SubscriptionStatus) // Find approval URL for _, link := range response.Links { if link.Rel == "approve" { fmt.Printf("Approval URL: %s\n", link.Href) } } return response, nil } ``` -------------------------------- ### Generate and Get PayPal Invoice Source: https://context7.com/plutov/paypal/llms.txt Generates the next sequential invoice number and retrieves invoice details using the provided client. It demonstrates calls to GenerateInvoiceNumber and GetInvoiceDetails. ```go func generateInvoice(client *paypal.Client) (*paypal.Invoice, error) { ctx := context.Background() // Generate next invoice number invoiceNum, err := client.GenerateInvoiceNumber(ctx) if err != nil { return nil, fmt.Errorf("failed to generate invoice number: %w", err) } fmt.Printf("Next invoice number: %s\n", invoiceNum.InvoiceNumberValue) // Get invoice details by ID invoice, err := client.GetInvoiceDetails(ctx, "INV2-XXXX-XXXX-XXXX-XXXX") if err != nil { return nil, fmt.Errorf("failed to get invoice: %w", err) } fmt.Printf("Invoice: ID=%s, Status=%s, Amount=%s %s\n", invoice.ID, invoice.Status, invoice.AmountSummary.Value, invoice.AmountSummary.Currency) return invoice, nil } ``` -------------------------------- ### List PayPal Disputes Source: https://context7.com/plutov/paypal/llms.txt Retrieves a list of customer disputes from the last month using the provided client. It sets a start time and page size for the request and iterates through the results, printing key details. ```go func listDisputes(client *paypal.Client) error { ctx := context.Background() startTime := time.Now().AddDate(0, -1, 0) // Last month pageSize := 10 request := &paypal.ListDisputesRequest{ StartTime: &startTime, PageSize: &pageSize, } response, err := client.ListDisputes(ctx, request) if err != nil { return fmt.Errorf("failed to list disputes: %w", err) } fmt.Printf("Found %d disputes\n", len(response.Items)) for _, dispute := range response.Items { fmt.Printf("Dispute: ID=%s, Reason=%s, Status=%s, Amount=%s %s\n", dispute.DisputeID, dispute.Reason, dispute.Status, dispute.DisputeAmount.Value, dispute.DisputeAmount.Currency) // Get detailed dispute information details, err := client.GetDisputeDetail(ctx, dispute.DisputeID) if err != nil { fmt.Printf("Error getting details: %v\n", err) continue } fmt.Printf(" Created: %s, Messages: %d\n", details.CreateTime, len(details.Messages)) } return nil } ``` -------------------------------- ### Manage PayPal Orders in Go Source: https://github.com/plutov/paypal/blob/master/README.md Illustrates how to perform various operations on PayPal orders using the Go client. This includes getting, creating, updating, authorizing, and capturing orders. ```go // Get Order order, err := c.GetOrder("O-4J082351X3132253H") // Create Order units := []paypal.PurchaseUnitRequest{} source := &paypal.PaymentSource{} appCtx := &paypal.ApplicationContext{} order, err := c.CreateOrder(context.TODO(), paypal.OrderIntentCapture, units, source, appCtx) // Update Order order, err := c.UpdateOrder("O-4J082351X3132253H", []paypal.PurchaseUnitRequest{}) // Authorize Order auth, err := c.AuthorizeOrder(orderID, paypal.AuthorizeOrderRequest{}) // Capture Order capture, err := c.CaptureOrder(orderID, paypal.CaptureOrderRequest{}) ``` -------------------------------- ### Get PayPal Order Details Source: https://context7.com/plutov/paypal/llms.txt Retrieves details of an existing PayPal order using its ID. Requires a PayPal client and the order ID. Returns the Order object or an error. ```go func getOrderDetails(client *paypal.Client, orderID string) (*paypal.Order, error) { ctx := context.Background() order, err := client.GetOrder(ctx, orderID) if err != nil { return nil, fmt.Errorf("failed to get order: %w", err) } fmt.Printf("Order: ID=%s, Intent=%s, Status=%s\n", order.ID, order.Intent, order.Status) if order.Payer != nil { fmt.Printf("Payer: %s %s (%s)\n", order.Payer.Name.GivenName, order.Payer.Name.Surname, order.Payer.EmailAddress) } for _, pu := range order.PurchaseUnits { fmt.Printf("Purchase Unit: %s %s\n", pu.Amount.Value, pu.Amount.Currency) } return order, nil } ``` -------------------------------- ### Get PayPal User Info Source: https://context7.com/plutov/paypal/llms.txt Retrieves user profile information using OpenID Connect. This function requires a PayPal client and returns user information or an error. It prints the user's name, email, and address details. ```Go func getUserInfo(client *paypal.Client) (*paypal.UserInfo, error) { ctx := context.Background() userInfo, err := client.GetUserInfo(ctx, "openid") if err != nil { return nil, fmt.Errorf("failed to get user info: %w", err) } fmt.Printf("User: %s %s\n", userInfo.GivenName, userInfo.FamilyName) fmt.Printf("Email: %s (verified: %v)\n", userInfo.Email, userInfo.Verified) fmt.Printf("PayerID: %s\n", userInfo.PayerID) if userInfo.Address != nil { fmt.Printf("Address: %s, %s, %s %s\n", userInfo.Address.Line1, userInfo.Address.City, userInfo.Address.State, userInfo.Address.PostalCode) } return userInfo, nil } ``` -------------------------------- ### Get Invoice Details Source: https://github.com/plutov/paypal/blob/master/README.md This Go code retrieves the details for a specific invoice using its ID. It returns the invoice object and an error if the retrieval fails. The invoice ID format is exemplified as 'INV2-XFXV-YW42-ZANU-4F33'. ```go invoice, err := c.GetInvoiceDetails(ctx, "INV2-XFXV-YW42-ZANU-4F33") ``` -------------------------------- ### Get Payout Status (Go) Source: https://context7.com/plutov/paypal/llms.txt Retrieves the status of a specific PayPal payout batch and its individual items. This Go function requires a PayPal client and the payout batch ID. It returns the payout details or an error, printing batch and item statuses. ```Go func getPayoutStatus(client *paypal.Client, payoutBatchID string) (*paypal.PayoutResponse, error) { ctx := context.Background() payout, err := client.GetPayout(ctx, payoutBatchID) if err != nil { return nil, fmt.Errorf("failed to get payout: %w", err) } fmt.Printf("Payout Batch: %s, Status: %s\n", payout.BatchHeader.PayoutBatchID, payout.BatchHeader.BatchStatus) if payout.BatchHeader.Amount != nil { fmt.Printf("Total Amount: %s %s\n", payout.BatchHeader.Amount.Value, payout.BatchHeader.Amount.Currency) } for _, item := range payout.Items { fmt.Printf("Item %s: Status=%s, Amount=%s\n", item.PayoutItemID, item.TransactionStatus, item.PayoutItem.Amount.Value) } return payout, nil } ``` -------------------------------- ### Initialize PayPal Client in Go Source: https://github.com/plutov/paypal/blob/master/README.md Demonstrates how to initialize the PayPal REST API client in Go. It shows setting up the client with credentials and choosing between sandbox and live API environments. Optionally, it configures logging for the client. ```go import ( "os" "github.com/plutov/paypal/v4" ) c, err := paypal.NewClient("clientID", "secretID", paypal.APIBaseSandBox) // or paypal.APIBaseLive c.SetLog(os.Stdout) ``` -------------------------------- ### Run Tests Source: https://github.com/plutov/paypal/blob/master/README.md This command executes the test suite for the project. It relies on a mock server generated from PayPal's OpenAPI specifications for testing purposes. ```bash make test ``` -------------------------------- ### Create PayPal Order in Go Source: https://context7.com/plutov/paypal/llms.txt Shows how to create a new PayPal order with specified purchase units, including currency, value, breakdown, items, and description. It also configures application context for branding, return URLs, and user actions. ```go func createOrder(client *paypal.Client) (*paypal.Order, error) { ctx := context.Background() purchaseUnits := []paypal.PurchaseUnitRequest{ { Amount: &paypal.PurchaseUnitAmount{ Currency: "USD", Value: "100.00", Breakdown: &paypal.PurchaseUnitAmountBreakdown{ ItemTotal: &paypal.Money{Currency: "USD", Value: "90.00"}, Shipping: &paypal.Money{Currency: "USD", Value: "10.00"}, }, }, Description: "Premium Subscription", Items: []paypal.Item{ { Name: "Premium Plan", Description: "Annual subscription", Quantity: "1", UnitAmount: &paypal.Money{Currency: "USD", Value: "90.00"}, Category: paypal.ItemCategoryDigitalGood, }, }, }, } appContext := &paypal.ApplicationContext{ BrandName: "My Store", LandingPage: "LOGIN", UserAction: "PAY_NOW", ShippingPreference: "SET_PROVIDED_ADDRESS", ReturnURL: "https://example.com/return", CancelURL: "https://example.com/cancel", } order, err := client.CreateOrder(ctx, paypal.OrderIntentCapture, purchaseUnits, nil, appContext) if err != nil { return nil, fmt.Errorf("failed to create order: %w", err) } fmt.Printf("Order created: ID=%s, Status=%s\n", order.ID, order.Status) // Find approval URL for customer redirect for _, link := range order.Links { if link.Rel == "approve" { fmt.Printf("Approval URL: %s\n", link.Href) } } return order, nil } ``` -------------------------------- ### Create PayPal Product Source: https://context7.com/plutov/paypal/llms.txt Creates a product in PayPal's catalog for use with subscription plans. This function requires a PayPal client and returns the created product details or an error. It also lists all products in the catalog. ```Go func createProduct(client *paypal.Client) (*paypal.CreateProductResponse, error) { ctx := context.Background() product := paypal.Product{ Name: "Premium SaaS Application", Description: "Cloud-based productivity software", Type: paypal.ProductTypeService, Category: paypal.ProductCategorySoftware, ImageUrl: "https://example.com/product-image.png", HomeUrl: "https://example.com", } response, err := client.CreateProduct(ctx, product) if err != nil { return nil, fmt.Errorf("failed to create product: %w", err) } fmt.Printf("Product created: ID=%s, Name=%s\n", response.ID, response.Name) // List all products listResponse, err := client.ListProducts(ctx, &paypal.ProductListParameters{ ListParams: paypal.ListParams{ PageSize: "10", }, }) if err != nil { return nil, fmt.Errorf("failed to list products: %w", err) } fmt.Printf("Total products: %d\n", len(listResponse.Products)) return response, nil } ``` -------------------------------- ### Update Mock Server Source: https://github.com/plutov/paypal/blob/master/README.md This command updates the mock server used for testing. It involves fetching the latest OpenAPI specification files and regenerating the mock server code. Missing implementations should be added in `mockserver/impl.go`. ```bash make oapi ``` -------------------------------- ### Create PayPal Web Profile Source: https://context7.com/plutov/paypal/llms.txt Creates a web experience profile to customize the payment experience. It takes a PayPal client and returns the created web profile or an error. The function also lists all existing profiles. ```Go func createWebProfile(client *paypal.Client) (*paypal.WebProfile, error) { ctx := context.Background() profile := paypal.WebProfile{ Name: "My Store Checkout", Presentation: paypal.Presentation{ BrandName: "My Store", LogoImage: "https://example.com/logo.png", LocaleCode: "US", }, InputFields: paypal.InputFields{ AllowNote: true, NoShipping: paypal.NoShippingDisplay, // 0 = display shipping AddressOverride: paypal.AddrOverrideFromCall, }, FlowConfig: paypal.FlowConfig{ LandingPageType: paypal.LandingPageTypeBilling, BankTXNPendingURL: "https://example.com/pending", UserAction: "commit", }, } created, err := client.CreateWebProfile(ctx, profile) if err != nil { return nil, fmt.Errorf("failed to create profile: %w", err) } fmt.Printf("Web profile created: ID=%s, Name=%s\n", created.ID, created.Name) // List all profiles profiles, err := client.GetWebProfiles(ctx) if err != nil { return nil, fmt.Errorf("failed to list profiles: %w", err) } fmt.Printf("Total profiles: %d\n", len(profiles)) return created, nil } ``` -------------------------------- ### Create PayPal Subscription Plan in Go Source: https://context7.com/plutov/paypal/llms.txt Creates a new subscription plan for recurring billing with PayPal. This function defines the plan's pricing, billing cycles, and payment preferences. It requires a PayPal client and a product ID. ```go import ( "context" "fmt" "github.com/paypal/paypal-checkout-sdk-go/v2/paypal" ) func createSubscriptionPlan(client *paypal.Client, productID string) (*paypal.CreateSubscriptionPlanResponse, error) { ctx := context.Background() plan := paypal.SubscriptionPlan{ ProductId: productID, Name: "Premium Monthly", Description: "Premium subscription billed monthly", Status: paypal.SubscriptionPlanStatusActive, BillingCycles: []paypal.BillingCycle{ { Frequency: paypal.Frequency{ IntervalUnit: paypal.IntervalUnitMonth, IntervalCount: 1, }, TenureType: paypal.TenureTypeRegular, Sequence: 1, TotalCycles: 0, // 0 = infinite PricingScheme: paypal.PricingScheme{ FixedPrice: paypal.Money{ Currency: "USD", Value: "9.99", }, }, }, }, PaymentPreferences: &paypal.PaymentPreferences{ AutoBillOutstanding: true, SetupFeeFailureAction: paypal.SetupFeeFailureActionContinue, PaymentFailureThreshold: 3, SetupFee: &paypal.Money{ Currency: "USD", Value: "0.00", }, }, Taxes: &paypal.Taxes{ Percentage: "10", Inclusive: false, }, } response, err := client.CreateSubscriptionPlan(ctx, plan) if err != nil { return nil, fmt.Errorf("failed to create plan: %w", err) } fmt.Printf("Plan created: ID=%s, Status=%s\n", response.ID, response.Status) return response, nil } ``` -------------------------------- ### Run Linter Source: https://github.com/plutov/paypal/blob/master/README.md This command runs the linter to ensure code quality before submitting a pull request. It helps maintain consistent code style and identify potential issues. ```bash make lint ``` -------------------------------- ### Create Webhook Subscription (Go) Source: https://context7.com/plutov/paypal/llms.txt Subscribes to specific PayPal events by creating a webhook. This Go function utilizes the PayPal SDK to register a webhook URL and a list of event types to listen for, such as order approvals and payment captures. It returns the created webhook details or an error. ```Go func createWebhook(client *paypal.Client) (*paypal.Webhook, error) { ctx := context.Background() webhookRequest := &paypal.CreateWebhookRequest{ URL: "https://example.com/webhooks/paypal", EventTypes: []paypal.WebhookEventType{ {Name: paypal.EventCheckoutOrderApproved}, {Name: paypal.EventPaymentCaptureCompleted}, {Name: paypal.EventPaymentCaptureDenied}, {Name: paypal.EventPaymentCaptureRefunded}, }, } webhook, err := client.CreateWebhook(ctx, webhookRequest) if err != nil { return nil, fmt.Errorf("failed to create webhook: %w", err) } fmt.Printf("Webhook created: ID=%s, URL=%s\n", webhook.ID, webhook.URL) for _, eventType := range webhook.EventTypes { fmt.Printf("Subscribed to: %s\n", eventType.Name) } return webhook, nil } ``` -------------------------------- ### Manage PayPal Webhooks Source: https://github.com/plutov/paypal/blob/master/README.md This Go code demonstrates how to interact with PayPal webhooks. It covers creating, updating, retrieving, deleting, and listing webhooks. Ensure the PayPal client is properly initialized and authenticated before use. ```go c.CreateWebhook(paypal.CreateWebhookRequest{ URL: "webhook URL", EventTypes: []paypal.WebhookEventType{ paypal.WebhookEventType{ Name: "PAYMENT.AUTHORIZATION.CREATED", }, }, }) c.UpdateWebhook("WebhookID", []paypal.WebhookField{ paypal.WebhookField{ Operation: "replace", Path: "/event_types", Value: []interface{}{ map[string]interface{}{ "name": "PAYMENT.SALE.REFUNDED", }, }, }, }) c.GetWebhook("WebhookID") c.DeleteWebhook("WebhookID") c.ListWebhooks(paypal.AncorTypeApplication) ``` -------------------------------- ### Create Payout Batch (Go) Source: https://context7.com/plutov/paypal/llms.txt Initiates a PayPal payout to one or more recipients. This function uses the PayPal Go SDK to send money with details like sender batch ID, email subject, and individual item recipient information. It returns a payout response or an error. ```Go func createPayout(client *paypal.Client) (*paypal.PayoutResponse, error) { ctx := context.Background() payout := paypal.Payout{ SenderBatchHeader: &paypal.SenderBatchHeader{ SenderBatchID: "Payouts_2024_001", EmailSubject: "You have received a payment", EmailMessage: "You have received a payment from My Company", }, Items: []paypal.PayoutItem{ { RecipientType: paypal.EmailRecipientType, RecipientWallet: paypal.PaypalRecipientWallet, Receiver: "recipient1@example.com", Amount: &paypal.AmountPayout{ Currency: "USD", Value: "100.00", }, Note: "Payment for services rendered", SenderItemID: "item-001", }, { RecipientType: paypal.EmailRecipientType, RecipientWallet: paypal.PaypalRecipientWallet, Receiver: "recipient2@example.com", Amount: &paypal.AmountPayout{ Currency: "USD", Value: "50.00", }, Note: "Bonus payment", SenderItemID: "item-002", }, }, } response, err := client.CreatePayout(ctx, payout) if err != nil { return nil, fmt.Errorf("failed to create payout: %w", err) } fmt.Printf("Payout created: BatchID=%s, Status=%s\n", response.BatchHeader.PayoutBatchID, response.BatchHeader.BatchStatus) return response, nil } ``` -------------------------------- ### Handle PayPal Identity and Tokens in Go Source: https://github.com/plutov/paypal/blob/master/README.md Demonstrates how to obtain and manage access tokens for PayPal API interactions in Go. It covers granting new access tokens using authorization codes or refresh tokens, and retrieving user information. ```go // Grant new access token from auth code token, err := c.GrantNewAccessTokenFromAuthCode("", "http://example.com/myapp/return.php") // Grant new access token from refresh token token, err := c.GrantNewAccessTokenFromRefreshToken("") // Get user info userInfo, err := c.GetUserInfo("openid") ``` -------------------------------- ### Manage PayPal Web Experience Profiles in Go Source: https://github.com/plutov/paypal/blob/master/README.md Demonstrates the creation, retrieval, update, and deletion of PayPal web experience profiles using the Go client. This allows customization of the PayPal checkout experience. ```go // Create web experience profile webprofile := WebProfile{ Name: "YeowZa! T-Shirt Shop", Presentation: Presentation{ BrandName: "YeowZa! Paypal", LogoImage: "http://www.yeowza.com", LocaleCode: "US", }, InputFields: InputFields{ AllowNote: true, NoShipping: NoShippingDisplay, AddressOverride: AddrOverrideFromCall, }, FlowConfig: FlowConfig{ LandingPageType: LandingPageTypeBilling, BankTXNPendingURL: "http://www.yeowza.com", }, } result, err := c.CreateWebProfile(webprofile) // Get web experience profile webprofile, err := c.GetWebProfile("XP-CP6S-W9DY-96H8-MVN2") // List web experience profiles webprofiles, err := c.GetWebProfiles() // Update web experience profile webprofile := WebProfile{ ID: "XP-CP6S-W9DY-96H8-MVN2", Name: "Shop YeowZa! YeowZa! ", } err := c.SetWebProfile(webprofile) // Delete web experience profile err := c.DeleteWebProfile("XP-CP6S-W9DY-96H8-MVN2") ``` -------------------------------- ### Manage PayPal Subscription Source: https://context7.com/plutov/paypal/llms.txt Activates, suspends, or cancels a PayPal subscription using the provided client and subscription ID. It first retrieves subscription details, then performs suspend, activate, and cancel operations. ```go func manageSubscription(client *paypal.Client, subscriptionID string) error { ctx := context.Background() // Get subscription details details, err := client.GetSubscriptionDetails(ctx, subscriptionID) if err != nil { return fmt.Errorf("failed to get subscription: %w", err) } fmt.Printf("Subscription: ID=%s, Status=%s\n", details.ID, details.SubscriptionStatus) // Suspend subscription err = client.SuspendSubscription(ctx, subscriptionID, "Customer requested pause") if err != nil { return fmt.Errorf("failed to suspend: %w", err) } fmt.Println("Subscription suspended") // Activate subscription err = client.ActivateSubscription(ctx, subscriptionID, "Customer resumed subscription") if err != nil { return fmt.Errorf("failed to activate: %w", err) } fmt.Println("Subscription activated") // Cancel subscription err = client.CancelSubscription(ctx, subscriptionID, "Customer requested cancellation") if err != nil { return fmt.Errorf("failed to cancel: %w", err) } fmt.Println("Subscription cancelled") return nil } ``` -------------------------------- ### Create and Manage PayPal Payouts in Go Source: https://github.com/plutov/paypal/blob/master/README.md Provides Go code for creating single payouts to an email address and retrieving payout details. It includes setting up payout items with recipient information and amounts. ```go // Create single payout to email payout := paypal.Payout{ SenderBatchHeader: &paypal.SenderBatchHeader{ EmailSubject: "Subject will be displayed on PayPal", }, Items: []paypal.PayoutItem{ paypal.PayoutItem{ RecipientType: "EMAIL", Receiver: "single-email-payout@mail.com", Amount: &paypal.AmountPayout{ Value: "15.11", Currency: "USD", }, Note: "Optional note", SenderItemID: "Optional Item ID", }, }, } payoutResp, err := c.CreatePayout(payout) // Get payout payout, err := c.GetPayout("PayoutBatchID") // Get payout item payoutItem, err := c.GetPayoutItem("PayoutItemID") // Cancel unclaimed payout item payoutItem, err := c.CancelPayoutItem("PayoutItemID") ``` -------------------------------- ### Refund Captured Payment (Go) Source: https://context7.com/plutov/paypal/llms.txt Issues a partial or full refund for a previously captured payment using the PayPal Go SDK. Requires a PayPal client instance and the capture ID. Returns a refund response or an error. ```Go func refundCapture(client *paypal.Client, captureID string) (*paypal.RefundResponse, error) { ctx := context.Background() refundRequest := paypal.RefundCaptureRequest{ Amount: &paypal.Money{ Currency: "USD", Value: "25.00", // Partial refund }, InvoiceID: "INV-12345-REFUND", NoteToPayer: "Refund for returned item", } refund, err := client.RefundCapture(ctx, captureID, refundRequest) if err != nil { return nil, fmt.Errorf("failed to refund capture: %w", err) } fmt.Printf("Refund issued: ID=%s, Status=%s, Amount=%s %s\n", refund.ID, refund.Status, refund.Amount.Value, refund.Amount.Currency) return refund, nil } ``` -------------------------------- ### Manage PayPal Refunds in Go Source: https://github.com/plutov/paypal/blob/master/README.md Shows how to retrieve refund information for a given PayPal transaction using the Go client library. It requires the refund ID as input. ```go refund, err := c.GetRefund("O-4J082351X3132253H") ``` -------------------------------- ### Vault PayPal Credit Card Information in Go Source: https://github.com/plutov/paypal/blob/master/README.md Shows how to securely store, retrieve, update, and delete credit card information using PayPal's vaulting feature with the Go client. This includes storing new cards, patching existing ones, and listing all stored cards. ```go // Store credit card c.StoreCreditCard(paypal.CreditCard{ Number: "4417119669820331", Type: "visa", ExpireMonth: "11", ExpireYear: "2020", CVV2: "874", FirstName: "Foo", LastName: "Bar", }) // Delete credit card c.DeleteCreditCard("CARD-ID-123") // Patch credit card c.PatchCreditCard("CARD-ID-123", []paypal.CreditCardField{ paypal.CreditCardField{ Operation: "replace", Path: "/billing_address/line1", Value: "New value", }, }) // Get credit card c.GetCreditCard("CARD-ID-123") // Get all credit cards c.GetCreditCards(nil) ``` -------------------------------- ### Capture PayPal Order Source: https://context7.com/plutov/paypal/llms.txt Captures payment for an approved PayPal order to complete the transaction. Requires a PayPal client and the order ID. Returns a CaptureOrderResponse or an error. ```go func captureOrder(client *paypal.Client, orderID string) (*paypal.CaptureOrderResponse, error) { ctx := context.Background() captureRequest := paypal.CaptureOrderRequest{ PaymentSource: &paypal.PaymentSource{ Paypal: &paypal.PaymentSourcePaypal{ ExperienceContext: paypal.PaymentSourcePaypalExperienceContext{ PaymentMethodPreference: "IMMEDIATE_PAYMENT_REQUIRED", BrandName: "My Store", Locale: "en-US", LandingPage: "LOGIN", UserAction: "PAY_NOW", ReturnURL: "https://example.com/return", CancelURL: "https://example.com/cancel", }, }, }, } capture, err := client.CaptureOrder(ctx, orderID, captureRequest) if err != nil { return nil, fmt.Errorf("failed to capture order: %w", err) } fmt.Printf("Order captured: ID=%s, Status=%s\n", capture.ID, capture.Status) // Access captured payment details for _, pu := range capture.PurchaseUnits { if pu.Payments != nil { for _, c := range pu.Payments.Captures { fmt.Printf("Capture ID: %s, Amount: %s %s\n", c.ID, c.Amount.Value, c.Amount.Currency) } } } return capture, nil } ``` -------------------------------- ### Capture Previously Authorized PayPal Payment Source: https://context7.com/plutov/paypal/llms.txt Captures a previously authorized PayPal payment. Allows for partial captures. Requires a PayPal client and the authorization ID. Returns a PaymentCaptureResponse or an error. ```go func captureAuthorization(client *paypal.Client, authorizationID string) (*paypal.PaymentCaptureResponse, error) { ctx := context.Background() captureRequest := &paypal.PaymentCaptureRequest{ Amount: &paypal.Money{ Currency: "USD", Value: "50.00", // Can capture partial amount }, FinalCapture: false, // Set true if this is the final capture InvoiceID: "INV-12345", NoteToPayer: "Thank you for your purchase!", SoftDescriptor: "MYSTORE", } capture, err := client.CaptureAuthorization(ctx, authorizationID, captureRequest) if err != nil { return nil, fmt.Errorf("failed to capture authorization: %w", err) } fmt.Printf("Captured: ID=%s, Status=%s, Amount=%s %s\n", capture.ID, capture.Status, capture.Amount.Value, capture.Amount.Currency) return capture, nil } ``` -------------------------------- ### Authorize PayPal Order Source: https://context7.com/plutov/paypal/llms.txt Authorizes a PayPal order, placing a hold on funds without immediate capture. Requires a PayPal client and the order ID. Returns an AuthorizeOrderResponse or an error. ```go func authorizeOrder(client *paypal.Client, orderID string) (*paypal.AuthorizeOrderResponse, error) { ctx := context.Background() authRequest := paypal.AuthorizeOrderRequest{ ApplicationContext: paypal.ApplicationContext{ ReturnURL: "https://example.com/return", CancelURL: "https://example.com/cancel", }, } auth, err := client.AuthorizeOrder(ctx, orderID, authRequest) if err != nil { return nil, fmt.Errorf("failed to authorize order: %w", err) } fmt.Printf("Order authorized: ID=%s, Status=%s\n", auth.ID, auth.Status) // Get authorization ID for later capture for _, pu := range auth.PurchaseUnits { if pu.Payments != nil { for _, a := range pu.Payments.Authorizations { fmt.Printf("Authorization ID: %s, Status: %s\n", a.ID, a.Status) } } } return auth, nil } ``` -------------------------------- ### List PayPal Transactions Source: https://context7.com/plutov/paypal/llms.txt Searches for PayPal transactions within a specified date range. It requires a PayPal client and returns a transaction search response or an error. The function prints found transactions to the console. ```Go func listTransactions(client *paypal.Client) (*paypal.TransactionSearchResponse, error) { ctx := context.Background() endDate := time.Now() startDate := endDate.AddDate(0, 0, -30) // Last 30 days pageSize := 100 request := &paypal.TransactionSearchRequest{ StartDate: startDate, EndDate: endDate, PageSize: &pageSize, Fields: strPtr("all"), } response, err := client.ListTransactions(ctx, request) if err != nil { return nil, fmt.Errorf("failed to list transactions: %w", err) } fmt.Printf("Found %d transactions\n", len(response.TransactionDetails)) for _, tx := range response.TransactionDetails { fmt.Printf("Transaction: ID=%s, Status=%s, Amount=%s %s\n", tx.TransactionInfo.TransactionID, tx.TransactionInfo.TransactionStatus, tx.TransactionInfo.TransactionAmount.Value, tx.TransactionInfo.TransactionAmount.Currency) } return response, nil } func strPtr(s string) *string { return &s } ``` -------------------------------- ### Generate Next Invoice Number Source: https://github.com/plutov/paypal/blob/master/README.md This Go code snippet shows how to generate the next sequential invoice number using the PayPal client. The generated number might be formatted with leading zeros, such as '0001' or '0010'. ```go c.GenerateInvoiceNumber(ctx) // might return something like "0001" or "0010". ``` -------------------------------- ### Verify PayPal Webhook Signature in Go Source: https://context7.com/plutov/paypal/llms.txt Verifies the authenticity of incoming webhook requests from PayPal. It uses the PayPal client and the HTTP request object to check the signature. This is crucial for security to ensure requests originate from PayPal. ```go import ( "context" "fmt" "net/http" "github.com/paypal/paypal-checkout-sdk-go/v2/paypal" ) func verifyWebhook(client *paypal.Client, webhookID string, r *http.Request) (bool, error) { ctx := context.Background() response, err := client.VerifyWebhookSignature(ctx, r, webhookID) if err != nil { return false, fmt.Errorf("failed to verify webhook: %w", err) } isValid := response.VerificationStatus == "SUCCESS" fmt.Printf("Webhook verification: %s\n", response.VerificationStatus) return isValid, nil } // Example HTTP handler for webhook endpoint func webhookHandler(client *paypal.Client, webhookID string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { isValid, err := verifyWebhook(client, webhookID, r) if err != nil || !isValid { http.Error(w, "Invalid webhook", http.StatusUnauthorized) return } // Process the webhook event w.WriteHeader(http.StatusOK) } } ``` -------------------------------- ### Store Credit Card in PayPal Vault Source: https://context7.com/plutov/paypal/llms.txt Securely stores credit card information in PayPal's vault using the provided client. It creates a CreditCard object with details and calls the StoreCreditCard method. ```go func storeCreditCard(client *paypal.Client) (*paypal.CreditCard, error) { ctx := context.Background() card := paypal.CreditCard{ Number: "4417119669820331", Type: "visa", ExpireMonth: "12", ExpireYear: "2030", CVV2: "123", FirstName: "John", LastName: "Doe", ExternalCustomerID: "customer-12345", BillingAddress: &paypal.Address{ Line1: "123 Main St", City: "San Jose", State: "CA", PostalCode: "95131", CountryCode: "US", }, } storedCard, err := client.StoreCreditCard(ctx, card) if err != nil { return nil, fmt.Errorf("failed to store card: %w", err) } fmt.Printf("Card stored: ID=%s, State=%s, ValidUntil=%s\n", storedCard.ID, storedCard.State, storedCard.ValidUntil) return storedCard, nil } ``` -------------------------------- ### Void PayPal Authorization Source: https://context7.com/plutov/paypal/llms.txt Voids a previously authorized PayPal payment that has not yet been captured. Requires a PayPal client and the authorization ID. Returns an error if the operation fails. ```go func voidAuthorization(client *paypal.Client, authorizationID string) error { ctx := context.Background() auth, err := client.VoidAuthorization(ctx, authorizationID) if err != nil { return fmt.Errorf("failed to void authorization: %w", err) } fmt.Printf("Authorization voided: ID=%s, Status=%s\n", auth.ID, auth.Status) return nil } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.