plutov/paypal Go Client

repository·master·Indexed 21 days ago

https://github.com/plutov/paypal

A Go client for the PayPal REST API providing structured access to services including Orders, Payouts, Vault, Webhooks, and Authorizations. It features automatic OAuth2 lifecycle management via SendWithAuth, support for custom requests, and comprehensive constants for subscription plans, billing tenure, and product categories.

Tokens
26.3K
Snippets
102
Records
116
Agent score
73%

What's inside plutov/paypal

  1. Handle missing endpoints with custom requests

    master
    If a specific PayPal endpoint is not implemented in the client, you can perform manual requests by chaining the built-in functions: NewClient -> NewRequest -> SendWithAuth.
  2. Initialize the PayPal client

    master

    To use the PayPal client, create a new client using paypal.NewClient with your clientID and secretID. You must specify the environment using either paypal.APIBaseSandBox or paypal.APIBaseLive. You can also optionally set a logger using c.SetLog.

    import "github.com/plutov/paypal/v4"
    import "os"
    
    c, err := paypal.NewClient("clientID", "secretID", paypal.APIBaseSandBox) // or paypal.APIBaseLive
    c.SetLog(os.Stdout)
  3. How the Send method works

    master

    The Send method is the low-level execution engine for all requests. It handles:

    • Setting default headers (Accept: application/json, Accept-Language: en_US).
    • Applying the Prefer: return=representation header if configured.
    • Logging request/response dumps if a logger is set.
    • Unmarshalling JSON responses into the provided interface v.
    • Special Case: If v implements io.Writer, the raw response body is copied directly to that writer instead of being decoded.
  4. Manage Authorizations

    master

    The client provides methods to manage the lifecycle of a PayPal authorization:

    • Get authorization: Retrieve an existing authorization using c.GetAuthorization(authID).
    • Capture authorization: Capture a specific amount from an authorization using c.CaptureAuthorization(authID, amount, captureAll).
    • Void authorization: Void an existing authorization using c.VoidAuthorization(authID).
    • Reauthorize authorization: Reauthorize an authorization with a new amount using c.ReauthorizeAuthorization(authID, amount).
    // Get
    auth, err := c.GetAuthorization("2DC87612EK520411B")
    
    // Capture
    capture, err := c.CaptureAuthorization(authID, &paypal.Amount{Total: "7.00", Currency: "USD"}, true)
    
    // Void
    auth, err := c.VoidAuthorization(authID)
    
    // Reauthorize
    auth, err := c.ReauthorizeAuthorization(authID, &paypal.Amount{Total: "7.00", Currency: "USD"})
  5. Manage Payouts

    master

    The client supports creating and managing payouts:

    • Create single payout to email: Use c.CreatePayout(payout) with a paypal.Payout object containing SenderBatchHeader and Items.
    • Get payout: Retrieve payout details via c.GetPayout(payoutBatchID).
    • Get payout item: Retrieve a specific item via c.GetPayoutItem(payoutItemID).
    • Cancel unclaimed payout item: Use c.CancelPayoutItem(payoutItemID) to cancel an item that hasn't been claimed.
    // Create single payout to email
    payout := paypal.Payout{
        SenderBatchHeader: &paypal.SenderBatchHeader{
            EmailSubject: "Subject will be displayed on PayPal",
        },
        Items: []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 Payout Item
    payoutItem, err := c.CancelPayoutItem("PayoutItemID")
  6. Manage Identity and User Info

    master

    The client supports identity-related operations:

    • Grant Access Token from Auth Code: c.GrantNewAccessTokenFromAuthCode(authCode, redirectURI).
    • Grant Access Token from Refresh Token: c.GrantNewAccessTokenFromRefreshToken(refreshToken).
    • Get User Info: c.GetUserInfo(scope) (e.g., using openid).
    // From Auth Code
    token, err := c.GrantNewAccessTokenFromAuthCode("<Authorization-Code>", "http://example.com/myapp/return.php")
    
    // From Refresh Token
    token, err := c.GrantNewAccessTokenFromRefreshToken("<Refresh-Token>")
    
    // Get User Info
    userInfo, err := c.GetUserInfo("openid")
  7. Manage Vault (Credit Cards)

    master

    The Vault API allows you to store, retrieve, and update credit card information:

    • Store Credit Card: c.StoreCreditCard(creditCard).
    • Delete Credit Card: c.DeleteCreditCard(cardID).
    • Patch Credit Card: c.PatchCreditCard(cardID, fields) to update specific fields using JSON Patch operations.
    • Get Credit Card: c.GetCreditCard(cardID).
    • List Credit Cards: c.GetCreditCards(params).
    // Store
    c.StoreCreditCard(paypal.CreditCard{
        Number:      "4417119669820331",
        Type:        "visa",
        ExpireMonth: "11",
        ExpireYear:  "2020",
        CVV2:        "874",
        FirstName:   "Foo",
        LastName:    "Bar",
    })
    
    // Delete
    c.DeleteCreditCard("CARD-ID-123")
    
    // Patch
    c.PatchCreditCard("CARD-ID-123", []paypal.CreditCardField{
        {
            Operation: "replace",
            Path:      "/billing_address/line1",
            Value:     "New value",
        },
    })
    
    // Get
    c.GetCreditCard("CARD-ID-123")
    
    // List
    c.GetCreditCards(nil)
  8. Manage Invoices

    master

    Use these methods for invoice management:

    • Generate Next Invoice Number: c.GenerateInvoiceNumber(ctx) returns a string like 0001.
    • Get Invoice Details: c.GetInvoiceDetails(ctx, invoiceID).
    // Generate Number
    c.GenerateInvoiceNumber(ctx)
    
    // Get Details
    invoice, err := c.GetInvoiceDetails(ctx, "INV2-XFXV-YW42-ZANU-4F33")
  9. Manage Webhooks

    master

    Use the following methods to manage PayPal webhooks:

    • Create Webhook: c.CreateWebhook(request).
    • Update Webhook: c.UpdateWebhook(webhookID, fields).
    • Get Webhook: c.GetWebhook(webhookID).
    • Delete Webhook: c.DeleteWebhook(webhookID).
    • List Webhooks: c.ListWebhooks(anchorType).
    // Create
    c.CreateWebhook(paypal.CreateWebhookRequest{
        URL: "webhook URL",
        EventTypes: []paypal.WebhookEventType{
            {Name: "PAYMENT.AUTHORIZATION.CREATED"},
        },
    })
    
    // Update
    c.UpdateWebhook("WebhookID", []paypal.WebhookField{
        {
            Operation: "replace",
            Path:      "/event_types",
            Value: []interface{}{
                map[string]interface{}{"name": "PAYMENT.SALE.REFUNDED"},
            },
        },
    })
    
    // Get
    c.GetWebhook("WebhookID")
    
    // Delete
    c.DeleteWebhook("WebhookID")
    
    // List
    c.ListWebhooks(paypal.AncorTypeApplication)
  10. Manage Orders

    master

    Use the following methods to interact with PayPal Orders:

    • Create Order: c.CreateOrder(ctx, intent, units, source, appCtx).
    • Get Order: c.GetOrder(orderID).
    • Update Order: c.UpdateOrder(orderID, purchaseUnitRequests).
    • Authorize Order: c.AuthorizeOrder(orderID, authorizeOrderRequest).
    • Capture Order: c.CaptureOrder(orderID, captureOrderRequest).
    // Create Order
    units := []paypal.PurchaseUnitRequest{}
    source := &paypal.PaymentSource{}
    appCtx := &paypal.ApplicationContext{}
    order, err := c.CreateOrder(context.TODO(), paypal.OrderIntentCapture, units, source, appCtx)
    
    // Get Order
    order, err := c.GetOrder("O-4J082351X3132253H")
    
    // 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{})
  11. Manage Web Experience Profiles

    master

    Web experience profiles can be managed using the following methods:

    • Create: c.CreateWebProfile(webprofile).
    • Get: c.GetWebProfile(id).
    • List: c.GetWebProfiles().
    • Update: c.SetWebProfile(webprofile).
    • Delete: c.DeleteWebProfile(id).
    // Create
    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
    webprofile, err := c.GetWebProfile("XP-CP6S-W9DY-96H8-MVN2")
    
    // List
    webprofiles, err := c.GetWebProfiles()
    
    // Update
    webprofile := WebProfile{
        ID: "XP-CP6S-W9DY-96H8-MVN2",
        Name: "Shop YeowZa! YeowZa! ",
    }
    err := c.SetWebProfile(webprofile)
    
    // Delete
    err := c.DeleteWebProfile("XP-CP6S-W9DY-96H8-MVN2")
  12. Update a dispute

    master

    Use UpdateDispute to partially update an existing dispute's information via a PATCH request. This requires the disputeId and an UpdateDisputeParams object.

    err := client.UpdateDispute(ctx, "DISPUTE_ID", &paypal.UpdateDisputeParams{
    	// ... parameters
    })