Handle missing endpoints with custom requests
masterNewClient -> NewRequest -> SendWithAuth.repository·master·Indexed 21 days ago
https://github.com/plutov/paypalA 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.
NewClient -> NewRequest -> SendWithAuth.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)The Send method is the low-level execution engine for all requests. It handles:
Accept: application/json, Accept-Language: en_US).Prefer: return=representation header if configured.v.v implements io.Writer, the raw response body is copied directly to that writer instead of being decoded.The client provides methods to manage the lifecycle of a PayPal authorization:
c.GetAuthorization(authID).c.CaptureAuthorization(authID, amount, captureAll).c.VoidAuthorization(authID).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"})The client supports creating and managing payouts:
c.CreatePayout(payout) with a paypal.Payout object containing SenderBatchHeader and Items.c.GetPayout(payoutBatchID).c.GetPayoutItem(payoutItemID).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")The client supports identity-related operations:
c.GrantNewAccessTokenFromAuthCode(authCode, redirectURI).c.GrantNewAccessTokenFromRefreshToken(refreshToken).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")The Vault API allows you to store, retrieve, and update credit card information:
c.StoreCreditCard(creditCard).c.DeleteCreditCard(cardID).c.PatchCreditCard(cardID, fields) to update specific fields using JSON Patch operations.c.GetCreditCard(cardID).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)Use these methods for invoice management:
c.GenerateInvoiceNumber(ctx) returns a string like 0001.c.GetInvoiceDetails(ctx, invoiceID).// Generate Number
c.GenerateInvoiceNumber(ctx)
// Get Details
invoice, err := c.GetInvoiceDetails(ctx, "INV2-XFXV-YW42-ZANU-4F33")Use the following methods to manage PayPal webhooks:
c.CreateWebhook(request).c.UpdateWebhook(webhookID, fields).c.GetWebhook(webhookID).c.DeleteWebhook(webhookID).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)Use the following methods to interact with PayPal Orders:
c.CreateOrder(ctx, intent, units, source, appCtx).c.GetOrder(orderID).c.UpdateOrder(orderID, purchaseUnitRequests).c.AuthorizeOrder(orderID, authorizeOrderRequest).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{})Web experience profiles can be managed using the following methods:
c.CreateWebProfile(webprofile).c.GetWebProfile(id).c.GetWebProfiles().c.SetWebProfile(webprofile).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")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
})