plutov / paypal Goto Github PK
View Code? Open in Web Editor NEWGolang client for PayPal REST API
License: MIT License
Golang client for PayPal REST API
License: MIT License
Nvm
Hi there,
PayPal subscription API will be deprecated as of March 31, 2019.
It seems like some endpoints will be changed, and billing plans and agreements are going away.
I assume you plan to upgrade the library sooner or later to adjust to the new api,
but how far up the priorities list is this? 😄
Will the new api replace the old one, or be added alongside it?
Hello, I have a question about the amount shown?
` clientId := "AehUCWtgSv0ZXi-4o8P9jQ8oeyP07NRw0UqVzCwFFStmzq5-OqEXMhJGLr7HBqqbt9UonFHtHln4NVMC"
secretId := "EH2PBwQU5sGxFxaEjYiT8QuO7Ejs74QYkOAmQZRQ1kJMYFOauB7enxGSlxd5l9aUKKFVVO_73aVV1QLs"
c, err := paypalsdk.NewClient(clientId, secretId, paypalsdk.APIBaseSandBox)
if err != nil {
fmt.Println("paypalsdk.NewClient err", err.Error())
}
accessToken, err := c.GetAccessToken()
if err != nil {
fmt.Println("c.GetAccessToken err", err.Error())
}
fmt.Println(accessToken.Token)
amount := paypalsdk.Amount{
Total: "100.00",
Currency: "USD",
}
redirectURI := "http://www.baidu.com"
cancelURI := "http://www.baidu.com"
description := "maimaimai"
paymentResult, err := c.CreateDirectPaypalPayment(amount, redirectURI, cancelURI, description)
fmt.Println(paymentResult.Links)`
I got a link from paymentResult,However, the payment amount of the page is not displayed.
Can you tell me how to solve it?Thanks!
In V2 how do we pay with a vaulted card once it is stored? I cannot for the life of me get it to work! It keeps giving me ORDER_NOT_APPROVED
I am trying to get an access token after an user has logged in with paypal.
client, err := paypalsdk.NewClient(util.Config.PayPal.ClientID, util.Config.PayPal.Secret, paypalsdk.APIBaseSandBox)
if err != nil {
log.Fatal(err)
}
client.SetLog(os.Stdout)
token, err := client.GrantNewAccessTokenFromAuthCode(req.URL.Query().Get("code"), "myURL")
However I am always getting this error:
{"error_description":"client id or secret is null","error":"invalid_client","correlation_id":"88feef2c749e8","information_link":"https://developer.paypal.com/docs/api/#errors"}
My ClientID and Secret are correctly set. I can get an access token without any error using client.GetAccessToken()
What I am missing? Thanks
How can I get authorization -> id from this type of response
{
"intent": "authorize",
"payer": {
"payment_method": "credit_card",
"funding_instruments": [
{
"credit_card": {
"payer_id": "3888888888888888888",
"number": "xxxxxxxxxxxx8888",
"type": "DISCOVER",
"expire_month": "10",
"expire_year": "2028",
"first_name": "ABC"
}
}
]
},
"transactions": [
{
"amount": {
"currency": "USD",
"total": "4.00",
"details": {}
},
"description": "This is the authorize payment transaction description.",
"related_resources": [
{
"authorization": {
"amount": {
"currency": "USD",
"total": "4.00",
"details": {}
},
"create_time": "2018-10-12T11:23:51Z",
"update_time": "2018-10-12T11:23:53Z",
"state": "authorized",
"parent_payment": "PAY-37J37J37J37J37J37J37J37J",
"id": "4FR34FR34FR34FR3A",
"valid_until": "2018-11-10T11:23:51Z",
"links": [
{
"href": "https://api.sandbox.paypal.com/v1/payments/authorization/4FR34FR34FR34FR3A",
"rel": "self",
"method": "GET"
},
{
"href": "https://api.sandbox.paypal.com/v1/payments/authorization/4FR34FR34FR34FR3A/capture",
"rel": "capture",
"method": "POST"
},
{
"href": "https://api.sandbox.paypal.com/v1/payments/authorization/4FR34FR34FR34FR3A/void",
"rel": "void",
"method": "POST"
},
{
"href": "https://api.sandbox.paypal.com/v1/payments/payment/PAY-37J37J37J37J37J37J37J37J",
"rel": "parent_payment",
"method": "GET"
}
]
}
}
]
}
],
"id": "PAY-37J37J37J37J37J37J37J37J",
"create_time": "2018-10-12T11:23:51Z",
"state": "approved",
"update_time": "2018-10-12T11:23:53Z",
"links": [
{
"href": "https://api.sandbox.paypal.com/v1/payments/payment/PAY-37J37J37J37J37J37J37J37J",
"rel": "self",
"method": "GET"
}
]
}
}
}
I need to get this id "4FR34FR34FR34FR3A" to capture payment, how can I can I get this id from this response in golang?
Hello,
According to Paypal docs, the quantity item should be a string https://developer.paypal.com/docs/api/payments/v1/#definition-item and not int https://github.com/logpacker/PayPal-Go-SDK/blob/master/types.go#L291
as shown here.
Please check this ticket for more info:
Not work if payment method = "credit_card". Other methods is works.
payInfo := paypalsdk.Payment{
Intent: intent,
Payer: &paypalsdk.Payer{
PaymentMethod: "credit_card",
FundingInstruments: []paypalsdk.FundingInstrument{paypalsdk.FundingInstrument{
CreditCard: &paypalsdk.CreditCard{
Number: "xxx",
Type: "xxx",
ExpireMonth: "xxx",
ExpireYear: "xxx",
CVV2: "xxx",
FirstName: "xxx",
LastName: "xxx",
},
}},
},
Transactions: []paypalsdk.Transaction{paypalsdk.Transaction{
Amount: &paypalsdk.Amount{
Currency: currency,
Total: price,
},
Description: description,
}},
RedirectURLs: &paypalsdk.RedirectURLs{
ReturnURL: successURI,
CancelURL: cancelURI,
},
}
Error: POST https://api.sandbox.paypal.com/v1/payments/payment: 400
I have error from this code.
client, err := paypalsdk.NewClient(secretKeys.PaypalSandboxClientId, secretKeys.PaypalSandboxSecret, paypalsdk.APIBaseSandBox)
// client, err := paypalsdk.NewClient(secretKeys.PaypalClientId, secretKeys.PaypalSecret, paypalsdk.APIBaseLive)
if err != nil {
panic(err)
}
// this required making paypalsdk.Client.client PUBLIC
client.Client = urlfetch.Client(ctx)
if _, err := client.GetAccessToken(); err != nil {
panic(err)
}
Error Msg:
client.Client undefined (type *paypalsdk.Client has no field or method Client, but does have paypalsdk.client)
amount := &paypalsdk.Amount{
Value: "1.00", Currency: "HKD",
}
fmt.Println(amount)
c.CaptureOrder(order.ID, amount, true, nil)
error msg
{"name":"INVALID_REQUEST","message":"Request is not well-formed, syntactically incorrect, or violates schema.","debug_id":"11d0d004ac59b","details":[{"field":"/amount/currency_code","value":"","location":"body","issue":"MISSING_REQUIRED_PARAMETER","description":"A required field / parameter is missing."},{"field":"/amount/value","value":"","location":"body","issue":"MISSING_REQUIRED_PARAMETER","description":"A required field / parameter is missing."}],"links":[{"href":"https://developer.paypal.com/docs/api/orders/v2/#error-MISSING_REQUIRED_PARAMETER","rel":"information_link","encType":"application/json"}]}
Hello,
is it out of date? Am I missing something?
--- FAIL: Test (4.55s)
panic: json: cannot unmarshal string into Go value of type int [recovered]
panic: json: cannot unmarshal string into Go value of type int
...
package paypal
import (
"log"
"os"
"github.com/logpacker/PayPal-Go-SDK"
)
func run() {
c, err := paypalsdk.NewClient(
"...",
"...",
paypalsdk.APIBaseLive,
)
if err != nil {
panic(err)
}
c.SetLog(os.Stdout)
_, err = c.GetAccessToken()
if err != nil {
panic(err)
}
payments, err := c.GetPayments()
if err != nil {
panic(err) // here
}
log.Println(payments)
}
I'm now getting this message back from the Paypal sandbox when I call the CreateSinglePayout function:
Synchronous mode will soon be deprecated and is no longer available for new integrations. You can use the asynchronous mode by specifying sync_mode= false in the request.
subj
I have two accounts. One is user another is the admin. Now, the user wants to send $10.00 invoice to admin. How could you manage it in this package?
UT tests:
Integration tests:
What's the difference between v1 and v2?
So it seems like passing json as a body for /v1/identity/openidconnect/tokenservice
request doesn't work anymore.
This request doesn't work:
curl -v 'https://api.sandbox.paypal.com/v1/identity/openidconnect/tokenservice' \
-H "Content-Type: application/json" \
-H "Authorization: Bearing <token>" \
-d '{"grant_type":"authorization_code","code":"<code>","redirect_uri":"<redirect_uri>"}'
response:
{"error_description":"Grant type is null","error":"invalid_grant","correlation_id":"a7087aa10fff1","information_link":"https://developer.paypal.com/docs/api/#errors"}
Where this request using formdata works:
curl -v 'https://api.sandbox.paypal.com/v1/identity/openidconnect/tokenservice' \
-H "Content-Type: application/x-www-form-urlencoded" \
-H "Authorization: Basic <base64(clientID:secret)>" \
-d 'grant_type=authorization_code&code=<code>&redirect_uri=<redirect_uri>'
Also making GET request with query params also works.
Did I miss something here and I'm incorrect in my assumption? If not, I can provide a pull request that I started to work on. But one issue is that Paypal returns "expire_in" field as a string, so we would need to do something like here for that field where it is a custom type with UnmarshalJSON method: https://github.com/golang/oauth2/blob/master/internal/token.go#L62.
Edit: Also it looks like using a bearing token for authorization doesn't work, but using a basic clientID:secret auth does work. I fixed the cURL example above.
Hi,
To be able to display our app's info, our client needs to query Paypal with a client token.
Paypal documentation says that:
Your server is responsible for generating a client token, which contains the authorization and configuration details that your client needs to initialize the client SDK.
We tried the following:
paypalClient, _ := paypalsdk.NewClient(clientID, secretID, url)
token, _ := paypalClient.GetAccessToken()
But the generated token does not seem to be destined to be used client side.
How can I use you library to generate a client token? Is it even possible? We did not find the endpoint we need to call in Paypal documentation.
Thanks in advance,
Best regards
https://developer.paypal.com/docs/api/#vault
https://github.com/logpacker/PayPal-Go-SDK
import in Article, link in Article
import in Userspace, redeploy Userspace
import in README
I found that the Send
method of the Client
, after doing a http request, would dump the http request and response before checking the error. Here's the code:
resp, err = c.client.Do(req)
c.log(req, resp)
if err != nil {
return err
}
defer resp.Body.Close()
That will cause a "nil pointer dereference" if there is anything wrong with the http request (eg. an i/o timeout). Because in that case, the resp
would be nil, making it impossible to get the body of resp
in the log
method.
hi im trying to execute payments after being redirected from paypals merchant view. keep getting 500s
is there a proper example demonstrating how to go about doing this?
// Item struct
Item struct {
//Quantity string `json:"quantity"`
//Quantity uint32 `json:"quantity"`
Name string `json:"name"`
Price string `json:"price"`
Currency string `json:"currency"`
SKU string `json:"sku,omitempty"`
Description string `json:"description,omitempty"`
Tax string `json:"tax,omitempty"`
}
//----------------types.go:290---------------------
because paypal service response field type is number not string such as
{"id":"PAY-3AL75111WY384445VLPMDDZI","intent":"sale","state":"created","payer":{"payment_method":"paypal"},"transactions":[{"amount":{"total":"7.00","currency":"USD","details":{}},"description":"My Payment","item_list":{"items":[{"name":"name","description":"Desc","price":"7.00","currency":"USD","quantity":1}]},"related_resources":[]}],"create_time":"2018-10-30T10:26:45Z","links":[{"href":"https://api.sandbox.paypal.com/v1/payments/payment/PAY-3AL75111WY384445VLPMDDZI","rel":"self","method":"GET"},{"href":"https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-2NN28981E4508510W","rel":"approval_url","method":"REDIRECT"},{"href":"https://api.sandbox.paypal.com/v1/payments/payment/PAY-3AL75111WY384445VLPMDDZI/execute","rel":"execute","method":"POST"}]}
Can not found function CreateOrder
in v2.0.0?
We are using below code and getting above Error - the code was taken from Example code mentioned in README.md file
c, err := paypalsdk.NewClient("ClientID", "SecretKey", paypalsdk.APIBaseLive)
check(err)
c.SetLog(os.Stdout) // Set log to terminal stdout
//accessToken, err := c.GetAccessToken()
amount := paypalsdk.Amount{
Total: "7.00",
Currency: "USD",
}
redirectURI := Host + "/paypal/redirect"
cancelURI := Host + "/payment/cancel"
description := "Description for this payment"
paymentResult, err := c.CreateDirectPaypalPayment(amount, redirectURI, cancelURI, description)
check(err)
fmt.Println(paymentResult)
And error is on CreateDirectPaypalPayment
Any help would be appreciated.
When cycles_remaining of an Infinite Billing Agreement too big. Unmarshal into AgreementDetails.cycles_remaining will fail.
Error: cannot unmarshal number 18446744073709551615 into Go struct field AgreementDetails.cycles_remaining of type int64
Now, I try to use this code to payment.Have any problems?
I want to make credit card payments using paypal v2 payments api. But I want to do that without authorization id. How can I achieve this using this sdk ?
In version v1 you could get the country iso code from a payment like this:
payment, err := c.client.GetPayment("PayPalPaymentID")
if err != nil {
return err
}
code := payment.Payer.PayerInfo.CountryCode
How can I get the country code for the payer of a payment in v2?
Hi,
It doesn't look like this library support field override_merchant_preferences in create billing agreement. Is this something that will be available in the future?
https://developer.paypal.com/docs/api/payments.billing-agreements/v1/#billing-agreements_post
Hi,
I'm new here. Trying to write the Cancel Billing Agreement method using SendWithAuth. I keep getting error "500 An internal service error occured". Below is my code:
req, err := PaypalClient.NewRequest("POST", fmt.Sprintf("%s%s", PaypalClient.APIBase, "/v1/payments/billing-agreements/"+user.PaypalBillingId+"/cancel"), nil)
var response interface{}
err = PaypalClient.SendWithAuth(req, response)
Also what should I do with the response 204 no content ? It looks like the interface{} is causing problem as well.
However if I use curl in the terminal, everything is fine
Api order is not working with this path /v2/payments/orders/{order_id}
https://github.com/logpacker/PayPal-Go-SDK/blob/master/order.go#L10
Regarding the docs, the path should be /v2/checkout/orders/{order_id}
https://developer.paypal.com/docs/api/orders/v2/#orders_get
I can't find /v2/payments/orders/{order_id}
in PayPal docs
give me a hand
I'm having issues integrating with PayPal's Checkout API, either I'm looking at the wrong docs or PayPal has made API changes recently.
captureOrder requires a different payload than required by the SDK. A "payment_source" consisting of a token and card object compared to an amount and currency object.
I'm seeing a similar issue with authorizeOrder
There also appears to be a missing method called updateOrder
Any help would be appreciated!
Hi,
While creating billing agreement I'm getting error: Invalid Fields passed in plan. Pass only a valid plan-id.
I am passing BillingPlan
object as mentioned in types.BillingAgreement
// Create a client instance
c, err := paypalsdk.NewClient("clientID", "secretID", paypalsdk.APIBaseSandBox)
c.SetLogFile("/tpm/paypal-debug.log") // Set log file if necessary
is now incorrect after my pull request.
possible solution
// Create a client instance
c, err := paypalsdk.NewClient("clientID", "secretID", paypalsdk.APIBaseSandBox)
c.SetLog(os.Stdout) // Set log to terminal stdout
The field is always empty.
ErrorResponse.Detail
has type string
but API returns string array. client.go:110 does no error checking.
Example response from PayPal:
{"name":"VALIDATION_ERROR","debug_id":"xxx","message":"Invalid request - see details","information_link":"https://developer.paypal.com/webapps/developer/docs/api/","details":[{"field":"name","issue":"A profile with this name already exists"}]}
{"name":"VALIDATION_ERROR","details":[{"field":"payer.funding_instruments[0].credit_card.number","issue":"Value must be numeric."}]
any chance you can bump the version to 1.0.2 after the changes from this pr? A version is easier for me to reference than a particular commit in my dep configs
Works fine in dev mode, shows "Return to merchant" in production mode, it is similar to following issue :
braintree/braintree-android-drop-in#53
c.CreateDirectPaypalPayment
Works and creates a redirect link.
After redirect link is opened it shows "Return to merchant" , sometimes shows "Unsupported payee currency" in production mode.
I wasted like 7 months to get this to work :(
Because I'm a solo developer I thought there must be some error on my end.
So I ended up changing implementation of Paypal SDK more than 3 times in my golang project.
After trying hard enough, I got this to work by using a buy now button with IPN listener by using some hacks such as passing user ID in custom field etc.
I got ill and was ICU for few weeks to get this to work in less time.
I followed suggestions that were given in github.com/logpacker/PayPal-Go-SDK
, It worked fine in dev mode but as soon as I switched to production mode it didn't work.
As a result I had implement one more payment option (Instamojo) which took more time to get the actual product ready.
I had no issues with Instamojo even though they do not provide a package for golang, they even provide option to specify webhook URL for payment notifications.
I feel so bad right now, I don't even know what suggestion to give to make this to work without any issues for Indian merchants, but still here is a list that I have made that may ease the process.
Sometimes paypal returns errors like:
400 Invalid request - see details
And we have to type assert the error to get the details field but currently, in README.md there's no examples of error handling.
I've seen that the description of the function says that it will get a new access token when the current one is about to expire, but I can't see to find this logic anywhere in the code. Is it already implemented?
https://github.com/logpacker/PayPal-Go-SDK/blob/master/client.go#L95
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.