diff --git a/Makefile b/Makefile index 7f5384a..5587572 100644 --- a/Makefile +++ b/Makefile @@ -4,4 +4,4 @@ test: .PHONY: integration integration: - go test -count=1 -v -run "Auction" ./test/integration -integration=true -timeout=999999s \ No newline at end of file + go test -count=1 -v -run "Auction" ./test/integration -integration=true \ No newline at end of file diff --git a/browse_test.go b/browse_test.go index feedf1a..911786c 100644 --- a/browse_test.go +++ b/browse_test.go @@ -28,6 +28,9 @@ func TestGetLegacyItem(t *testing.T) { defer teardown() mux.HandleFunc("/buy/browse/v1/item/get_item_by_legacy_id", func(w http.ResponseWriter, r *http.Request) { + if r.Method != "GET" { + t.Fatalf("expected GET method, got: %s", r.Method) + } fmt.Fprintf(w, `{"itemId": "v1|%s|0"}`, r.URL.Query().Get("legacy_item_id")) }) @@ -41,6 +44,9 @@ func TestGetCompactItem(t *testing.T) { defer teardown() mux.HandleFunc("/buy/browse/v1/item/v1|202117468662|0", func(w http.ResponseWriter, r *http.Request) { + if r.Method != "GET" { + t.Fatalf("expected GET method, got: %s", r.Method) + } fmt.Fprintf(w, `{"itemId": "%s"}`, r.URL.Query().Get("fieldgroups")) }) @@ -54,6 +60,9 @@ func TestGettItem(t *testing.T) { defer teardown() mux.HandleFunc("/buy/browse/v1/item/v1|202117468662|0", func(w http.ResponseWriter, r *http.Request) { + if r.Method != "GET" { + t.Fatalf("expected GET method, got: %s", r.Method) + } fmt.Fprintf(w, `{"itemId": "%s"}`, r.URL.Query().Get("fieldgroups")) }) diff --git a/clientcredentials/clientcredentials.go b/clientcredentials/clientcredentials.go deleted file mode 100644 index 076a4bf..0000000 --- a/clientcredentials/clientcredentials.go +++ /dev/null @@ -1,121 +0,0 @@ -// Package clientcredentials implements the eBay client credentials grant flow -// to generate "Application access" tokens. -// eBay doc: https://developer.ebay.com/api-docs/static/oauth-client-credentials-grant.html -// -// The only difference from the original golang.org/x/oauth2/clientcredentials is the token type -// being forced to "Bearer". The eBay api /identity/v1/oauth2/token endpoint returns -// "Application Access Token" as token type which is then reused: -// https://github.com/golang/oauth2/blob/aaccbc9213b0974828f81aaac109d194880e3014/token.go#L68-L70 -package clientcredentials - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "strings" - "time" - - "golang.org/x/oauth2" -) - -type Config struct { - // ClientID is the application's ID. - ClientID string - - // ClientSecret is the application's secret. - ClientSecret string - - // TokenURL is the resource server's token endpoint - // URL. This is a constant specific to each server. - TokenURL string - - // Scope specifies optional requested permissions. - Scopes []string - - // HTTPClient used to make requests. - HTTPClient *http.Client -} - -// Token uses client credentials to retrieve a token. -func (c *Config) Token(ctx context.Context) (*oauth2.Token, error) { - return c.TokenSource(ctx).Token() -} - -// Client returns an HTTP client using the provided token. -// The token will auto-refresh as necessary. -// The returned client and its Transport should not be modified. -func (c *Config) Client(ctx context.Context) *http.Client { - return oauth2.NewClient(ctx, c.TokenSource(ctx)) -} - -// TokenSource returns a TokenSource that returns t until t expires, -// automatically refreshing it as necessary using the provided context and the -// client ID and client secret. -// -// Most users will use Config.Client instead. -func (c *Config) TokenSource(ctx context.Context) oauth2.TokenSource { - source := &tokenSource{ - ctx: ctx, - conf: c, - } - return oauth2.ReuseTokenSource(nil, source) -} - -type tokenSource struct { - ctx context.Context - conf *Config -} - -// Token refreshes the token by using a new client credentials request. -// tokens received this way do not include a refresh token -func (c *tokenSource) Token() (*oauth2.Token, error) { - v := url.Values{ - "grant_type": {"client_credentials"}, - } - if len(c.conf.Scopes) > 0 { - v.Set("scope", strings.Join(c.conf.Scopes, " ")) - } - req, err := http.NewRequest("POST", c.conf.TokenURL, strings.NewReader(v.Encode())) - if err != nil { - return nil, err - } - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - req.SetBasicAuth(url.QueryEscape(c.conf.ClientID), url.QueryEscape(c.conf.ClientSecret)) - client := c.conf.HTTPClient - if client == nil { - client = http.DefaultClient - } - r, err := client.Do(req) - if err != nil { - return nil, err - } - defer r.Body.Close() - body, err := ioutil.ReadAll(r.Body) - if err != nil { - return nil, fmt.Errorf("cannot fetch token: %v", err) - } - if code := r.StatusCode; code < 200 || code > 299 { - return nil, fmt.Errorf("%s (%d)", req.URL, r.StatusCode) - } - token := struct { - AccessToken string `json:"access_token"` - ExpiresIn int `json:"expires_in"` - }{} - if err = json.NewDecoder(bytes.NewReader(body)).Decode(&token); err != nil { - return nil, err - } - var expiry time.Time - if secs := token.ExpiresIn; secs > 0 { - expiry = time.Now().Add(time.Duration(secs) * time.Second) - } - t := oauth2.Token{ - AccessToken: token.AccessToken, - Expiry: expiry, - TokenType: "Bearer", - } - return &t, nil -} diff --git a/ebay.go b/ebay.go index 3a540d2..440cc2e 100644 --- a/ebay.go +++ b/ebay.go @@ -88,16 +88,20 @@ func (c *Client) NewRequest(method, url string, body interface{}, opts ...Opt) ( if err != nil { return nil, errors.WithStack(err) } - var buf io.ReadWriter + var bodyR io.Reader if body != nil { - buf = new(bytes.Buffer) + buf := new(bytes.Buffer) enc := json.NewEncoder(buf) enc.SetEscapeHTML(false) if err := enc.Encode(body); err != nil { return nil, err } + b := buf.Bytes() + print("body:" + string(b)) // TODO + bodyR = bytes.NewReader(b) } - req, err := http.NewRequest(method, u.String(), buf) + + req, err := http.NewRequest(method, u.String(), bodyR) if err != nil { return nil, errors.WithStack(err) } @@ -152,7 +156,7 @@ type ErrorData struct { } func (e *ErrorData) Error() string { - return fmt.Sprintf("%d %s: %+v", e.response.StatusCode, e.requestDump, e.Errors) + return fmt.Sprintf("%d\n%s\n%+v", e.response.StatusCode, e.requestDump, e.Errors) } // CheckResponse checks the API response for errors, and returns them if present. @@ -166,7 +170,7 @@ func CheckResponse(req *http.Request, resp *http.Response) error { return errorData } -// IsError allows to check if err is a specific error codes returned by the eBay API. +// IsError allows to check if err contains specific error codes returned by the eBay API. // // eBay API docs: https://developer.ebay.com/devzone/xml/docs/Reference/ebay/Errors/errormessages.htm func IsError(err error, codes ...int) bool { diff --git a/oauth2.go b/oauth2.go new file mode 100644 index 0000000..0ee357a --- /dev/null +++ b/oauth2.go @@ -0,0 +1,24 @@ +package ebay + +import "golang.org/x/oauth2" + +// BearerTokenSource forces the type of the token returned by the 'base' TokenSource to 'Bearer'. +// The eBay API will return "Application Access Token" or "User Access Token" as token_type but +// it must be set to 'Bearer' for subsequent requests. +type BearerTokenSource struct { + base oauth2.TokenSource +} + +// TokenSource returns a new BearerTokenSource. +func TokenSource(base oauth2.TokenSource) *BearerTokenSource { + return &BearerTokenSource{base: base} +} + +// Token allows BearerTokenSource to implement oauth2.TokenSource. +func (ts *BearerTokenSource) Token() (*oauth2.Token, error) { + t, err := ts.base.Token() + if t != nil { + t.TokenType = "Bearer" + } + return t, err +} diff --git a/offer.go b/offer.go index fe920c9..8d6d570 100644 --- a/offer.go +++ b/offer.go @@ -76,15 +76,15 @@ const ( // GetBidding retrieves the buyer's bidding details on a specific auction item. // // eBay API docs: https://developer.ebay.com/api-docs/buy/offer/resources/bidding/methods/getBidding -func (s *OfferService) GetBidding(ctx context.Context, itemID, marketplaceID string, opts ...Opt) (Item, error) { +func (s *OfferService) GetBidding(ctx context.Context, itemID, marketplaceID string, opts ...Opt) (Bidding, error) { u := fmt.Sprintf("buy/offer/v1_beta/bidding/%s", itemID) opts = append(opts, OptBuyMarketplace(marketplaceID)) req, err := s.client.NewRequest(http.MethodGet, u, nil, opts...) if err != nil { - return Item{}, err + return Bidding{}, err } - var it Item - return it, s.client.Do(ctx, req, &it) + var bid Bidding + return bid, s.client.Do(ctx, req, &bid) } // ProxyBid represents an eBay proxy bid. @@ -94,7 +94,7 @@ type ProxyBid struct { // Some valid eBay error codes for the PlaceProxyBid method. // -// eBay API docs: https://developer.ebay.com/api-docs/buy/offer/resources/bidding/methods/getBidding#h2-error-codes +// eBay API docs: https://developer.ebay.com/api-docs/buy/offer/resources/bidding/methods/placeProxyBid#h2-error-codes const ( ErrPlaceProxyBidAuctionEndedBecauseOfBuyItNow = 120002 ErrPlaceProxyBidBidCannotBeGreaterThanBuyItNowPrice = 120005 @@ -111,34 +111,38 @@ const ( // PlaceProxyBid places a proxy bid for the buyer on a specific auction item. // +// Curency is the three-letter ISO 4217 code representing the currency. +// For one hundred US dollars, MaxAmout is "100.00" and currency is "USD". +// // You must ensure the user agrees to the "Terms of use for Adult Only category" // (https://signin.ebay.com/ws/eBayISAPI.dll?AdultSignIn2) if he wishes to bid on on a adult-only item. +// An item is adult-only if the AdultOnly field returned by the Browse API is set to true. // -// eBay API docs: https://developer.ebay.com/api-docs/buy/offer/resources/bidding/methods/getBidding +// eBay API docs: https://developer.ebay.com/api-docs/buy/offer/resources/bidding/methods/placeProxyBid func (s *OfferService) PlaceProxyBid(ctx context.Context, itemID, marketplaceID, maxAmount, currency string, userConsentAdultOnlyItem bool, opts ...Opt) (ProxyBid, error) { u := fmt.Sprintf("buy/offer/v1_beta/bidding/%s/place_proxy_bid", itemID) opts = append(opts, OptBuyMarketplace(marketplaceID)) - pl := struct { - MaxAmount struct { - Currency string `json:"currency"` - Value string `json:"value"` - } `json:"maxAmount"` - UserConsent struct { - AdultOnlyItem bool `json:"adultOnlyItem"` - } `json:"userConsent"` - }{ - MaxAmount: struct { - Currency string `json:"currency"` - Value string `json:"value"` - }{currency, maxAmount}, - UserConsent: struct { - AdultOnlyItem bool `json:"adultOnlyItem"` - }{userConsentAdultOnlyItem}, + type userConsent struct { + AdultOnlyItem bool `json:"adultOnlyItem,omitempty"` + } + type amount struct { + Currency string `json:"currency"` + Value string `json:"value"` + } + type payload struct { + MaxAmount amount `json:"maxAmount"` + UserConsent *userConsent `json:"userConsent,omitempty"` + } + pl := payload{ + MaxAmount: amount{Currency: currency, Value: maxAmount}, + } + if userConsentAdultOnlyItem { + pl.UserConsent = &userConsent{userConsentAdultOnlyItem} } req, err := s.client.NewRequest(http.MethodPost, u, &pl, opts...) if err != nil { return ProxyBid{}, err } - var p ProxyBid - return p, s.client.Do(ctx, req, &p) + var bid ProxyBid + return bid, s.client.Do(ctx, req, &bid) } diff --git a/offer_test.go b/offer_test.go index c57c305..5895bbf 100644 --- a/offer_test.go +++ b/offer_test.go @@ -3,7 +3,9 @@ package ebay_test import ( "context" "fmt" + "io/ioutil" "net/http" + "strconv" "testing" "github.com/jybp/ebay" @@ -21,6 +23,9 @@ func TestGetBidding(t *testing.T) { defer teardown() mux.HandleFunc("/buy/offer/v1_beta/bidding/v1|202117468662|0", func(w http.ResponseWriter, r *http.Request) { + if r.Method != "GET" { + t.Fatalf("expected GET method, got: %s", r.Method) + } marketplaceID := r.Header.Get("X-EBAY-C-MARKETPLACE-ID") fmt.Fprintf(w, `{"itemId": "%s"}`, marketplaceID) }) @@ -29,3 +34,32 @@ func TestGetBidding(t *testing.T) { assert.Nil(t, err) assert.Equal(t, ebay.BuyMarketplaceUSA, bidding.ItemID) } + +func TestPlaceProxyBid(t *testing.T) { + client, mux, teardown := setup(t) + defer teardown() + + mux.HandleFunc("/buy/offer/v1_beta/bidding/v1|202117468662|0/place_proxy_bid", func(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" { + t.Fatalf("expected POST method, got: %s", r.Method) + } + marketplaceID := r.Header.Get("X-EBAY-C-MARKETPLACE-ID") + body, err := ioutil.ReadAll(r.Body) + if err != nil { + t.Fatalf("%+v", err) + http.Error(w, err.Error(), 500) + return + } + escapedBody := strconv.Quote(string(body)) + escapedBody = escapedBody[1 : len(escapedBody)-1] + fmt.Fprintf(w, `{"proxyBidId": "%s_%s"}`, escapedBody, marketplaceID) + }) + + bid, err := client.Buy.Offer.PlaceProxyBid(context.Background(), "v1|202117468662|0", ebay.BuyMarketplaceUSA, "1.23", "USD", false) + assert.Nil(t, err) + assert.Equal(t, "{\"maxAmount\":{\"currency\":\"USD\",\"value\":\"1.23\"}}\n_EBAY_US", bid.ProxyBidID) + + bid, err = client.Buy.Offer.PlaceProxyBid(context.Background(), "v1|202117468662|0", ebay.BuyMarketplaceUSA, "1.23", "USD", true) + assert.Nil(t, err) + assert.Equal(t, "{\"maxAmount\":{\"currency\":\"USD\",\"value\":\"1.23\"},\"userConsent\":{\"adultOnlyItem\":true}}\n_EBAY_US", bid.ProxyBidID) +} diff --git a/test/integration/auction_test.go b/test/integration/auction_test.go index fe7f6ae..48a754c 100644 --- a/test/integration/auction_test.go +++ b/test/integration/auction_test.go @@ -9,21 +9,22 @@ import ( "net/http" "net/url" "os" + "strconv" "strings" "testing" "time" _ "github.com/joho/godotenv/autoload" "github.com/jybp/ebay" - "github.com/jybp/ebay/tokensource" "golang.org/x/oauth2" - oclientcredentials "golang.org/x/oauth2/clientcredentials" + "golang.org/x/oauth2/clientcredentials" ) var ( integration bool clientID string clientSecret string + auctionURL string ) func init() { @@ -34,8 +35,10 @@ func init() { } clientID = os.Getenv("SANDBOX_CLIENT_ID") clientSecret = os.Getenv("SANDBOX_CLIENT_SECRET") - if clientID == "" || clientSecret == "" { - panic("No SANDBOX_CLIENT_ID or SANDBOX_CLIENT_SECRET. Tests won't run.") + // You have to manually create an auction in the sandbox. Auctions can't be created using the rest api (yet?). + auctionURL = os.Getenv("SANDOX_AUCTION_URL") + if clientID == "" || clientSecret == "" || auctionURL == "" { + panic("Please set SANDBOX_CLIENT_ID, SANDBOX_CLIENT_SECRET and SANDOX_AUCTION_URL.") } } @@ -44,20 +47,16 @@ func TestAuction(t *testing.T) { t.SkipNow() } - // Manually create an auction in the sandbox and copy/paste the url. - // Auctions can't be created using the rest api (yet?). - const auctionURL = "https://www.sandbox.ebay.com/itm/110440008951" - ctx := context.Background() - conf := oclientcredentials.Config{ + conf := clientcredentials.Config{ ClientID: clientID, ClientSecret: clientSecret, TokenURL: "https://api.sandbox.ebay.com/identity/v1/oauth2/token", Scopes: []string{"https://api.ebay.com/oauth/api_scope"}, } - client := ebay.NewSandboxClient(oauth2.NewClient(ctx, tokensource.New(conf.TokenSource(ctx)))) + client := ebay.NewSandboxClient(oauth2.NewClient(ctx, ebay.TokenSource(conf.TokenSource(ctx)))) lit, err := client.Buy.Browse.GetItemByLegacyID(ctx, auctionURL[strings.LastIndex(auctionURL, "/")+1:]) if err != nil { @@ -84,8 +83,6 @@ func TestAuction(t *testing.T) { } t.Logf("item %s UniqueBidderCount:%d minimumBidPrice: %+v currentPriceToBid: %+v\n", it.ItemID, it.UniqueBidderCount, it.MinimumPriceToBid, it.CurrentBidPrice) - // Setup oauth server. - b := make([]byte, 16) if _, err := io.ReadFull(rand.Reader, b); err != nil { t.Fatalf("%+v", err) @@ -139,13 +136,32 @@ func TestAuction(t *testing.T) { t.Fatal(err) } - client = ebay.NewSandboxClient(oauth2.NewClient(ctx, tokensource.New(oauthConf.TokenSource(ctx, tok)))) + client = ebay.NewSandboxClient(oauth2.NewClient(ctx, ebay.TokenSource(oauthConf.TokenSource(ctx, tok)))) - _, err = client.Buy.Offer.GetBidding(ctx, it.ItemID, ebay.BuyMarketplaceUSA) - if !ebay.IsError(err, ebay.ErrGetBiddingNoBiddingActivity) { - t.Logf("Expected ErrNoBiddingActivity, got %+v.", err) + bid, err := client.Buy.Offer.GetBidding(ctx, it.ItemID, ebay.BuyMarketplaceUSA) + if err != nil && !ebay.IsError(err, ebay.ErrGetBiddingNoBiddingActivity) { + t.Fatalf("Expected error code %d, got %+v.", ebay.ErrGetBiddingNoBiddingActivity, err) } - // err := client.Buy.Offer.PlaceProxyBid(ctx) + var bidValue, bidCurrency string + if len(bid.SuggestedBidAmounts) > 0 { + bidValue = bid.SuggestedBidAmounts[0].Value + bidCurrency = bid.SuggestedBidAmounts[0].Currency + } else { + bidValue = it.CurrentBidPrice.Value + v, err := strconv.ParseFloat(bidValue, 64) + if err != nil { + t.Fatal(err) + } + v += 2 + bidValue = fmt.Sprintf("%.2f", v) + bidCurrency = it.CurrentBidPrice.Currency + } + _, err = client.Buy.Offer.PlaceProxyBid(ctx, it.ItemID, ebay.BuyMarketplaceUSA, bidValue, bidCurrency, false) + if err != nil { + t.Fatal(err) + } + + t.Logf("Successfully bid %+v.", bid.SuggestedBidAmounts[0]) } diff --git a/tokensource/tokensource.go b/tokensource/tokensource.go deleted file mode 100644 index 8bc0291..0000000 --- a/tokensource/tokensource.go +++ /dev/null @@ -1,26 +0,0 @@ -package tokensource - -import "golang.org/x/oauth2" - -// type TokenSource interface { -// // Token returns a token or an error. -// // Token must be safe for concurrent use by multiple goroutines. -// // The returned Token must not be modified. -// Token() (*Token, error) -// } - -type TokenSource struct { - base oauth2.TokenSource -} - -func New(base oauth2.TokenSource) *TokenSource { - return &TokenSource{base: base} -} - -func (ts *TokenSource) Token() (*oauth2.Token, error) { - t, err := ts.base.Token() - if t != nil { - t.TokenType = "Bearer" - } - return t, err -}