diff --git a/api_keys.go b/api_keys.go index be9d679..58ed51d 100755 --- a/api_keys.go +++ b/api_keys.go @@ -51,8 +51,8 @@ const ( Oauth2ScopePayments Oauth2Scope = "payments" Oauth2ScopeProducts Oauth2Scope = "products" Oauth2ScopeProfile Oauth2Scope = "profile" - Oauth2ScopeTerminalsRead Oauth2Scope = "terminals.read" - Oauth2ScopeTerminalsWrite Oauth2Scope = "terminals.write" + Oauth2ScopeReadersRead Oauth2Scope = "readers.read" + Oauth2ScopeReadersWrite Oauth2Scope = "readers.write" Oauth2ScopeTransactionsHistory Oauth2Scope = "transactions.history" Oauth2ScopeUserAppSettings Oauth2Scope = "user.app-settings" Oauth2ScopeUserPayoutSettings Oauth2Scope = "user.payout-settings" @@ -116,7 +116,7 @@ func (s *ApiKeysService) ListApikeys(ctx context.Context, merchantCode string, p } var v ApikeysList - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + if err := dec.Decode(&v); err != nil { return nil, fmt.Errorf("decode response: %s", err.Error()) } @@ -159,7 +159,7 @@ func (s *ApiKeysService) CreateApikey(ctx context.Context, merchantCode string, } var v Apikey - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + if err := dec.Decode(&v); err != nil { return nil, fmt.Errorf("decode response: %s", err.Error()) } @@ -230,7 +230,7 @@ func (s *ApiKeysService) GetApikey(ctx context.Context, merchantCode string, key } var v Apikey - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + if err := dec.Decode(&v); err != nil { return nil, fmt.Errorf("decode response: %s", err.Error()) } diff --git a/authorization.go b/authorization.go index dee28b2..a3b1527 100755 --- a/authorization.go +++ b/authorization.go @@ -31,19 +31,6 @@ const ( AuthTokenGrantTypeRefreshToken AuthTokenGrantType = "refresh_token" ) -// AuthorizeParams are query parameters for Authorize -type AuthorizeParams struct { - ClientId *string `json:"client_id,omitempty"` - RedirectUri *string `json:"redirect_uri,omitempty"` - ResponseType *string `json:"response_type,omitempty"` - Scope *string `json:"scope,omitempty"` - State *string `json:"state,omitempty"` -} - -// AuthorizeResponse is the type definition for a AuthorizeResponse. -type AuthorizeResponse struct { -} - // CreateToken request body. type CreateTokenBody struct { // The client ID of your application that was generated when you [registered it](https://developer.sumup.com/docs/register-app). @@ -80,14 +67,32 @@ type CreateTokenResponse struct { TokenType *string `json:"token_type,omitempty"` } +// AuthorizeParams are query parameters for Authorize +type AuthorizeParams struct { + ClientId *string `json:"client_id,omitempty"` + RedirectUri *string `json:"redirect_uri,omitempty"` + ResponseType *string `json:"response_type,omitempty"` + Scope *string `json:"scope,omitempty"` + State *string `json:"state,omitempty"` +} + +// AuthorizeResponse is the type definition for a AuthorizeResponse. +type AuthorizeResponse struct { +} + type AuthorizationService service -// Authorize: Request authorization from users -// Request authorization from users and grant your application access to resources associated with the user's profile. -func (s *AuthorizationService) Authorize(ctx context.Context, params AuthorizeParams) (*AuthorizeResponse, error) { - path := fmt.Sprintf("/authorize") +// CreateToken: Generate a token +// Generate a token or a refresh token +func (s *AuthorizationService) CreateToken(ctx context.Context, body CreateTokenBody) (*CreateTokenResponse, error) { + buf := new(bytes.Buffer) + if err := json.NewEncoder(buf).Encode(body); err != nil { + return nil, fmt.Errorf("encoding json body request failed: %v", err) + } - req, err := s.client.NewRequest(ctx, http.MethodGet, path, http.NoBody) + path := fmt.Sprintf("/token") + + req, err := s.client.NewRequest(ctx, http.MethodPost, path, buf) if err != nil { return nil, fmt.Errorf("error building request: %v", err) } @@ -112,25 +117,20 @@ func (s *AuthorizationService) Authorize(ctx context.Context, params AuthorizePa return nil, &apiErr } - var v AuthorizeResponse - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + var v CreateTokenResponse + if err := dec.Decode(&v); err != nil { return nil, fmt.Errorf("decode response: %s", err.Error()) } return &v, nil } -// CreateToken: Generate a token -// Generate a token or a refresh token -func (s *AuthorizationService) CreateToken(ctx context.Context, body CreateTokenBody) (*CreateTokenResponse, error) { - buf := new(bytes.Buffer) - if err := json.NewEncoder(buf).Encode(body); err != nil { - return nil, fmt.Errorf("encoding json body request failed: %v", err) - } - - path := fmt.Sprintf("/token") +// Authorize: Request authorization from users +// Request authorization from users and grant your application access to resources associated with the user's profile. +func (s *AuthorizationService) Authorize(ctx context.Context, params AuthorizeParams) (*AuthorizeResponse, error) { + path := fmt.Sprintf("/authorize") - req, err := s.client.NewRequest(ctx, http.MethodPost, path, buf) + req, err := s.client.NewRequest(ctx, http.MethodGet, path, http.NoBody) if err != nil { return nil, fmt.Errorf("error building request: %v", err) } @@ -155,8 +155,8 @@ func (s *AuthorizationService) CreateToken(ctx context.Context, body CreateToken return nil, &apiErr } - var v CreateTokenResponse - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + var v AuthorizeResponse + if err := dec.Decode(&v); err != nil { return nil, fmt.Errorf("decode response: %s", err.Error()) } diff --git a/checkouts.go b/checkouts.go index 04c0bae..35ff77c 100755 --- a/checkouts.go +++ b/checkouts.go @@ -136,7 +136,7 @@ type CheckoutCreateRequest struct { PersonalDetails *CheckoutCreateRequestPersonalDetails `json:"personal_details,omitempty"` // Purpose of the checkout. Purpose *CheckoutCreateRequestPurpose `json:"purpose,omitempty"` - // __Required for 3DS checkouts.__ Refers to a URL where the end user is redirected once the payment processing completes. + // __Required__ for [APMs](https://developer.sumup.com/online-payments/apm/introduction) and __recommended__ for card payments. Refers to a url where the end user is redirected once the payment processing completes. If not specified, the [Payment Widget](https://developer.sumup.com/online-payments/tools/card-widget) renders [3DS challenge](https://developer.sumup.com/online-payments/features/3ds) within an iframe instead of performing a full-page redirect. RedirectUrl *string `json:"redirect_url,omitempty"` // URL to which the SumUp platform sends the processing status of the payment checkout. ReturnUrl *string `json:"return_url,omitempty"` @@ -304,10 +304,10 @@ type CheckoutProcessMixinPaymentType string const ( CheckoutProcessMixinPaymentTypeBancontact CheckoutProcessMixinPaymentType = "bancontact" + CheckoutProcessMixinPaymentTypeBlik CheckoutProcessMixinPaymentType = "blik" CheckoutProcessMixinPaymentTypeBoleto CheckoutProcessMixinPaymentType = "boleto" CheckoutProcessMixinPaymentTypeCard CheckoutProcessMixinPaymentType = "card" CheckoutProcessMixinPaymentTypeIdeal CheckoutProcessMixinPaymentType = "ideal" - CheckoutProcessMixinPaymentTypeSofort CheckoutProcessMixinPaymentType = "sofort" ) // Current status of the checkout. @@ -494,7 +494,7 @@ type CreateCheckoutBody struct { PersonalDetails *CreateCheckoutBodyPersonalDetails `json:"personal_details,omitempty"` // Purpose of the checkout. Purpose *CreateCheckoutBodyPurpose `json:"purpose,omitempty"` - // __Required for 3DS checkouts.__ Refers to a URL where the end user is redirected once the payment processing completes. + // __Required__ for [APMs](https://developer.sumup.com/online-payments/apm/introduction) and __recommended__ for card payments. Refers to a url where the end user is redirected once the payment processing completes. If not specified, the [Payment Widget](https://developer.sumup.com/online-payments/tools/card-widget) renders [3DS challenge](https://developer.sumup.com/online-payments/features/3ds) within an iframe instead of performing a full-page redirect. RedirectUrl *string `json:"redirect_url,omitempty"` // URL to which the SumUp platform sends the processing status of the payment checkout. ReturnUrl *string `json:"return_url,omitempty"` @@ -643,6 +643,23 @@ type CreateCheckoutBodyTransaction struct { VatAmount *float64 `json:"vat_amount,omitempty"` } +// GetPaymentMethodsParams are query parameters for GetPaymentMethods +type GetPaymentMethodsParams struct { + Amount *float64 `json:"amount,omitempty"` + Currency *string `json:"currency,omitempty"` +} + +// GetPaymentMethodsResponse is the type definition for a GetPaymentMethodsResponse. +type GetPaymentMethodsResponse struct { + AvailablePaymentMethods *[]GetPaymentMethodsResponseAvailablePaymentMethod `json:"available_payment_methods,omitempty"` +} + +// GetPaymentMethodsResponseAvailablePaymentMethod is the type definition for a GetPaymentMethodsResponseAvailablePaymentMethod. +type GetPaymentMethodsResponseAvailablePaymentMethod struct { + // The ID of the payment method. + Id string `json:"id"` +} + // DeactivateCheckoutResponse is Details of the deleted checkout. type DeactivateCheckoutResponse struct { // Amount of the payment. @@ -768,29 +785,12 @@ type ProcessCheckoutBodyPaymentType string const ( ProcessCheckoutBodyPaymentTypeBancontact ProcessCheckoutBodyPaymentType = "bancontact" + ProcessCheckoutBodyPaymentTypeBlik ProcessCheckoutBodyPaymentType = "blik" ProcessCheckoutBodyPaymentTypeBoleto ProcessCheckoutBodyPaymentType = "boleto" ProcessCheckoutBodyPaymentTypeCard ProcessCheckoutBodyPaymentType = "card" ProcessCheckoutBodyPaymentTypeIdeal ProcessCheckoutBodyPaymentType = "ideal" - ProcessCheckoutBodyPaymentTypeSofort ProcessCheckoutBodyPaymentType = "sofort" ) -// GetPaymentMethodsParams are query parameters for GetPaymentMethods -type GetPaymentMethodsParams struct { - Amount *float64 `json:"amount,omitempty"` - Currency *string `json:"currency,omitempty"` -} - -// GetPaymentMethodsResponse is the type definition for a GetPaymentMethodsResponse. -type GetPaymentMethodsResponse struct { - AvailablePaymentMethods *[]GetPaymentMethodsResponseAvailablePaymentMethod `json:"available_payment_methods,omitempty"` -} - -// GetPaymentMethodsResponseAvailablePaymentMethod is the type definition for a GetPaymentMethodsResponseAvailablePaymentMethod. -type GetPaymentMethodsResponseAvailablePaymentMethod struct { - // The ID of the payment method. - Id string `json:"id"` -} - type CheckoutsService service // List: List checkouts @@ -824,7 +824,7 @@ func (s *CheckoutsService) List(ctx context.Context, params ListCheckoutsParams) } var v ListCheckoutsResponse - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + if err := dec.Decode(&v); err != nil { return nil, fmt.Errorf("decode response: %s", err.Error()) } @@ -871,19 +871,19 @@ func (s *CheckoutsService) Create(ctx context.Context, body CreateCheckoutBody) } var v Checkout - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + if err := dec.Decode(&v); err != nil { return nil, fmt.Errorf("decode response: %s", err.Error()) } return &v, nil } -// Deactivate: Deactivate a checkout -// Deactivates an identified checkout resource. If the checkout has already been processed it can not be deactivated. -func (s *CheckoutsService) Deactivate(ctx context.Context, id string) (*DeactivateCheckoutResponse, error) { - path := fmt.Sprintf("/v0.1/checkouts/%v", id) +// ListAvailablePaymentMethods: Get available payment methods +// Get payment methods available for the given merchant to use with a checkout. +func (s *CheckoutsService) ListAvailablePaymentMethods(ctx context.Context, merchantCode string, params GetPaymentMethodsParams) (*GetPaymentMethodsResponse, error) { + path := fmt.Sprintf("/v0.1/merchants/%v/payment-methods", merchantCode) - req, err := s.client.NewRequest(ctx, http.MethodDelete, path, http.NoBody) + req, err := s.client.NewRequest(ctx, http.MethodGet, path, http.NoBody) if err != nil { return nil, fmt.Errorf("error building request: %v", err) } @@ -908,20 +908,20 @@ func (s *CheckoutsService) Deactivate(ctx context.Context, id string) (*Deactiva return nil, &apiErr } - var v DeactivateCheckoutResponse - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + var v GetPaymentMethodsResponse + if err := dec.Decode(&v); err != nil { return nil, fmt.Errorf("decode response: %s", err.Error()) } return &v, nil } -// Get: Retrieve a checkout -// Retrieves an identified checkout resource. Use this request after processing a checkout to confirm its status and inform the end user respectively. -func (s *CheckoutsService) Get(ctx context.Context, id string) (*CheckoutSuccess, error) { +// Deactivate: Deactivate a checkout +// Deactivates an identified checkout resource. If the checkout has already been processed it can not be deactivated. +func (s *CheckoutsService) Deactivate(ctx context.Context, id string) (*DeactivateCheckoutResponse, error) { path := fmt.Sprintf("/v0.1/checkouts/%v", id) - req, err := s.client.NewRequest(ctx, http.MethodGet, path, http.NoBody) + req, err := s.client.NewRequest(ctx, http.MethodDelete, path, http.NoBody) if err != nil { return nil, fmt.Errorf("error building request: %v", err) } @@ -946,27 +946,20 @@ func (s *CheckoutsService) Get(ctx context.Context, id string) (*CheckoutSuccess return nil, &apiErr } - var v CheckoutSuccess - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + var v DeactivateCheckoutResponse + if err := dec.Decode(&v); err != nil { return nil, fmt.Errorf("decode response: %s", err.Error()) } return &v, nil } -// Process: Process a checkout -// Processing a checkout will attempt to charge the provided payment instrument for the amount of the specified checkout resource initiated in the `Create a checkout` endpoint. -// -// Follow this request with `Retrieve a checkout` to confirm its status. -func (s *CheckoutsService) Process(ctx context.Context, id string, body ProcessCheckoutBody) (*CheckoutSuccess, error) { - buf := new(bytes.Buffer) - if err := json.NewEncoder(buf).Encode(body); err != nil { - return nil, fmt.Errorf("encoding json body request failed: %v", err) - } - +// Get: Retrieve a checkout +// Retrieves an identified checkout resource. Use this request after processing a checkout to confirm its status and inform the end user respectively. +func (s *CheckoutsService) Get(ctx context.Context, id string) (*CheckoutSuccess, error) { path := fmt.Sprintf("/v0.1/checkouts/%v", id) - req, err := s.client.NewRequest(ctx, http.MethodPut, path, buf) + req, err := s.client.NewRequest(ctx, http.MethodGet, path, http.NoBody) if err != nil { return nil, fmt.Errorf("error building request: %v", err) } @@ -992,19 +985,26 @@ func (s *CheckoutsService) Process(ctx context.Context, id string, body ProcessC } var v CheckoutSuccess - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + if err := dec.Decode(&v); err != nil { return nil, fmt.Errorf("decode response: %s", err.Error()) } return &v, nil } -// ListAvailablePaymentMethods: Get available payment methods -// Get payment methods available for the given merchant to use with a checkout. -func (s *CheckoutsService) ListAvailablePaymentMethods(ctx context.Context, merchantCode string, params GetPaymentMethodsParams) (*GetPaymentMethodsResponse, error) { - path := fmt.Sprintf("/v0.1/merchants/%v/payment-methods", merchantCode) +// Process: Process a checkout +// Processing a checkout will attempt to charge the provided payment instrument for the amount of the specified checkout resource initiated in the `Create a checkout` endpoint. +// +// Follow this request with `Retrieve a checkout` to confirm its status. +func (s *CheckoutsService) Process(ctx context.Context, id string, body ProcessCheckoutBody) (*CheckoutSuccess, error) { + buf := new(bytes.Buffer) + if err := json.NewEncoder(buf).Encode(body); err != nil { + return nil, fmt.Errorf("encoding json body request failed: %v", err) + } - req, err := s.client.NewRequest(ctx, http.MethodGet, path, http.NoBody) + path := fmt.Sprintf("/v0.1/checkouts/%v", id) + + req, err := s.client.NewRequest(ctx, http.MethodPut, path, buf) if err != nil { return nil, fmt.Errorf("error building request: %v", err) } @@ -1029,8 +1029,8 @@ func (s *CheckoutsService) ListAvailablePaymentMethods(ctx context.Context, merc return nil, &apiErr } - var v GetPaymentMethodsResponse - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + var v CheckoutSuccess + if err := dec.Decode(&v); err != nil { return nil, fmt.Errorf("decode response: %s", err.Error()) } diff --git a/client.go b/client.go index e0bb7fb..f51e5fc 100755 --- a/client.go +++ b/client.go @@ -123,9 +123,9 @@ func (c *Client) NewRequest( } req, err := http.NewRequestWithContext( ctx, - http.MethodGet, + method, c.url+path, - http.NoBody, + body, ) if err != nil { return nil, fmt.Errorf("build request: %s", err.Error()) diff --git a/customers.go b/customers.go index 42c7422..3f65e9d 100755 --- a/customers.go +++ b/customers.go @@ -128,12 +128,6 @@ type CreateCustomerBody struct { PersonalDetails *PersonalDetails `json:"personal_details,omitempty"` } -// UpdateCustomer request body. -type UpdateCustomerBody struct { - // Personal details for the customer. - PersonalDetails *PersonalDetails `json:"personal_details,omitempty"` -} - // ListPaymentInstrumentsResponse is the type definition for a ListPaymentInstrumentsResponse. type ListPaymentInstrumentsResponse []PaymentInstrumentResponse @@ -156,6 +150,12 @@ const ( CreatePaymentInstrumentBodyTypeCard CreatePaymentInstrumentBodyType = "card" ) +// UpdateCustomer request body. +type UpdateCustomerBody struct { + // Personal details for the customer. + PersonalDetails *PersonalDetails `json:"personal_details,omitempty"` +} + // DeactivatePaymentInstrumentResponse is the type definition for a DeactivatePaymentInstrumentResponse. type DeactivatePaymentInstrumentResponse struct { } @@ -198,17 +198,17 @@ func (s *CustomersService) Create(ctx context.Context, body CreateCustomerBody) } var v Customer - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + if err := dec.Decode(&v); err != nil { return nil, fmt.Errorf("decode response: %s", err.Error()) } return &v, nil } -// Get: Retrieve a customer -// Retrieves an identified saved customer resource through the unique `customer_id` parameter, generated upon customer creation. -func (s *CustomersService) Get(ctx context.Context, customerId string) (*Customer, error) { - path := fmt.Sprintf("/v0.1/customers/%v", customerId) +// ListPaymentInstruments: List payment instruments +// Lists all payment instrument resources that are saved for an identified customer. +func (s *CustomersService) ListPaymentInstruments(ctx context.Context, customerId string) (*ListPaymentInstrumentsResponse, error) { + path := fmt.Sprintf("/v0.1/customers/%v/payment-instruments", customerId) req, err := s.client.NewRequest(ctx, http.MethodGet, path, http.NoBody) if err != nil { @@ -235,27 +235,27 @@ func (s *CustomersService) Get(ctx context.Context, customerId string) (*Custome return nil, &apiErr } - var v Customer - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + var v ListPaymentInstrumentsResponse + if err := dec.Decode(&v); err != nil { return nil, fmt.Errorf("decode response: %s", err.Error()) } return &v, nil } -// Update: Update a customer -// Updates an identified saved customer resource's personal details. +// CreatePaymentInstrument: Create a payment instrument +// Creates and activates a new payment instrument resource by saving a payment card for an identified customer. Implement to improve customer experience by skipping the step of entering payment instrument details. // -// The request only overwrites the parameters included in the request, all other parameters will remain with their initially assigned values. -func (s *CustomersService) Update(ctx context.Context, customerId string, body UpdateCustomerBody) (*Customer, error) { +// The token created via this endpoint **can not** be used for recurring payments by merchants operating within the EU. For more information visit our [recurring payments guide](https://developer.sumup.com/docs/recurring-payments/). +func (s *CustomersService) CreatePaymentInstrument(ctx context.Context, customerId string, body CreatePaymentInstrumentBody) (*PaymentInstrumentResponse, error) { buf := new(bytes.Buffer) if err := json.NewEncoder(buf).Encode(body); err != nil { return nil, fmt.Errorf("encoding json body request failed: %v", err) } - path := fmt.Sprintf("/v0.1/customers/%v", customerId) + path := fmt.Sprintf("/v0.1/customers/%v/payment-instruments", customerId) - req, err := s.client.NewRequest(ctx, http.MethodPut, path, buf) + req, err := s.client.NewRequest(ctx, http.MethodPost, path, buf) if err != nil { return nil, fmt.Errorf("error building request: %v", err) } @@ -280,18 +280,18 @@ func (s *CustomersService) Update(ctx context.Context, customerId string, body U return nil, &apiErr } - var v Customer - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + var v PaymentInstrumentResponse + if err := dec.Decode(&v); err != nil { return nil, fmt.Errorf("decode response: %s", err.Error()) } return &v, nil } -// ListPaymentInstruments: List payment instruments -// Lists all payment instrument resources that are saved for an identified customer. -func (s *CustomersService) ListPaymentInstruments(ctx context.Context, customerId string) (*ListPaymentInstrumentsResponse, error) { - path := fmt.Sprintf("/v0.1/customers/%v/payment-instruments", customerId) +// Get: Retrieve a customer +// Retrieves an identified saved customer resource through the unique `customer_id` parameter, generated upon customer creation. +func (s *CustomersService) Get(ctx context.Context, customerId string) (*Customer, error) { + path := fmt.Sprintf("/v0.1/customers/%v", customerId) req, err := s.client.NewRequest(ctx, http.MethodGet, path, http.NoBody) if err != nil { @@ -318,27 +318,27 @@ func (s *CustomersService) ListPaymentInstruments(ctx context.Context, customerI return nil, &apiErr } - var v ListPaymentInstrumentsResponse - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + var v Customer + if err := dec.Decode(&v); err != nil { return nil, fmt.Errorf("decode response: %s", err.Error()) } return &v, nil } -// CreatePaymentInstrument: Create a payment instrument -// Creates and activates a new payment instrument resource by saving a payment card for an identified customer. Implement to improve customer experience by skipping the step of entering payment instrument details. +// Update: Update a customer +// Updates an identified saved customer resource's personal details. // -// The token created via this endpoint **can not** be used for recurring payments by merchants operating within the EU. For more information visit our [recurring payments guide](https://developer.sumup.com/docs/recurring-payments/). -func (s *CustomersService) CreatePaymentInstrument(ctx context.Context, customerId string, body CreatePaymentInstrumentBody) (*PaymentInstrumentResponse, error) { +// The request only overwrites the parameters included in the request, all other parameters will remain with their initially assigned values. +func (s *CustomersService) Update(ctx context.Context, customerId string, body UpdateCustomerBody) (*Customer, error) { buf := new(bytes.Buffer) if err := json.NewEncoder(buf).Encode(body); err != nil { return nil, fmt.Errorf("encoding json body request failed: %v", err) } - path := fmt.Sprintf("/v0.1/customers/%v/payment-instruments", customerId) + path := fmt.Sprintf("/v0.1/customers/%v", customerId) - req, err := s.client.NewRequest(ctx, http.MethodPost, path, buf) + req, err := s.client.NewRequest(ctx, http.MethodPut, path, buf) if err != nil { return nil, fmt.Errorf("error building request: %v", err) } @@ -363,8 +363,8 @@ func (s *CustomersService) CreatePaymentInstrument(ctx context.Context, customer return nil, &apiErr } - var v PaymentInstrumentResponse - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + var v Customer + if err := dec.Decode(&v); err != nil { return nil, fmt.Errorf("decode response: %s", err.Error()) } @@ -402,7 +402,7 @@ func (s *CustomersService) DeactivatePaymentInstrument(ctx context.Context, cust } var v DeactivatePaymentInstrumentResponse - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + if err := dec.Decode(&v); err != nil { return nil, fmt.Errorf("decode response: %s", err.Error()) } diff --git a/members.go b/members.go new file mode 100755 index 0000000..65d6791 --- /dev/null +++ b/members.go @@ -0,0 +1,274 @@ +// Code generated by `gogenitor`. DO NOT EDIT. +package sumup + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http" + "time" +) + +// Invite is Pending invitation for membership. +type Invite struct { + // Email address of the invited user. + Email string `json:"email"` + ExpiresAt time.Time `json:"expires_at"` +} + +// Member is A member is user within speicfic resource identified by resource id, resource type, and associated roles. +type Member struct { + CreatedAt time.Time `json:"created_at"` + // ID of the member. + Id string `json:"id"` + // Pending invitation for membership. + Invite *Invite `json:"invite,omitempty"` + // User's permissions. + Permissions []string `json:"permissions"` + // User's roles. + Roles []string `json:"roles"` + Status MemberStatus `json:"status"` + UpdatedAt time.Time `json:"updated_at"` + // User information. + User *MemberUser `json:"user,omitempty"` +} + +type MemberStatus string + +const ( + MemberStatusAccepted MemberStatus = "accepted" + MemberStatusPending MemberStatus = "pending" +) + +// MemberUser is User information. +type MemberUser struct { + // Time when the user has been disabled. Applies only to virtual users (`virtual_user: true`). + DisabledAt *time.Time `json:"disabled_at,omitempty"` + // End-User's preferred e-mail address. Its value MUST conform to the RFC 5322 [RFC5322] addr-spec syntax. The RP MUST NOT rely upon this value being unique, for unique identification use ID instead. + Email string `json:"email"` + // Identifier for the End-User (also called Subject). + Id string `json:"id"` + // True if the user has enabled MFA on login. + MfaOnLoginEnabled bool `json:"mfa_on_login_enabled"` + // True if the user is a virtual user (operator). + VirtualUser bool `json:"virtual_user"` +} + +// ListMerchantMembersParams are query parameters for ListMerchantMembers +type ListMerchantMembersParams struct { + Email *string `json:"email,omitempty"` + Limit *int `json:"limit,omitempty"` + Offset *int `json:"offset,omitempty"` +} + +// ListMerchantMembersResponse is the type definition for a ListMerchantMembersResponse. +type ListMerchantMembersResponse struct { + Items []Member `json:"items"` + TotalCount int `json:"total_count"` +} + +// AddMerchantMember request body. +type AddMerchantMemberBody struct { + // Email address of the member to add. + Email string `json:"email"` + // List of roles to assign to the new member. + Roles []string `json:"roles"` +} + +// UpdateMerchantMember request body. +type UpdateMerchantMemberBody struct { + Roles []string `json:"roles"` +} + +type MembersService service + +// ListMerchantMembers: List members +// Lists merchant members with their roles and permissions. +func (s *MembersService) ListMerchantMembers(ctx context.Context, merchantCode string, params ListMerchantMembersParams) (*ListMerchantMembersResponse, error) { + path := fmt.Sprintf("/v0.1/merchants/%v/members", merchantCode) + + req, err := s.client.NewRequest(ctx, http.MethodGet, path, http.NoBody) + if err != nil { + return nil, fmt.Errorf("error building request: %v", err) + } + + resp, err := s.client.Do(req) + if err != nil { + return nil, fmt.Errorf("error sending request: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode >= 500 { + return nil, fmt.Errorf("invalid response: %d - %s", resp.StatusCode, http.StatusText(resp.StatusCode)) + } + + dec := json.NewDecoder(resp.Body) + if resp.StatusCode >= 400 { + var apiErr APIError + if err := dec.Decode(&apiErr); err != nil { + return nil, fmt.Errorf("read error response: %s", err.Error()) + } + + return nil, &apiErr + } + + var v ListMerchantMembersResponse + if err := dec.Decode(&v); err != nil { + return nil, fmt.Errorf("decode response: %s", err.Error()) + } + + return &v, nil +} + +// AddMerchantMember: Add member to merchant. + +func (s *MembersService) AddMerchantMember(ctx context.Context, merchantCode string, body AddMerchantMemberBody) (*Member, error) { + buf := new(bytes.Buffer) + if err := json.NewEncoder(buf).Encode(body); err != nil { + return nil, fmt.Errorf("encoding json body request failed: %v", err) + } + + path := fmt.Sprintf("/v0.1/merchants/%v/members", merchantCode) + + req, err := s.client.NewRequest(ctx, http.MethodPost, path, buf) + if err != nil { + return nil, fmt.Errorf("error building request: %v", err) + } + + resp, err := s.client.Do(req) + if err != nil { + return nil, fmt.Errorf("error sending request: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode >= 500 { + return nil, fmt.Errorf("invalid response: %d - %s", resp.StatusCode, http.StatusText(resp.StatusCode)) + } + + dec := json.NewDecoder(resp.Body) + if resp.StatusCode >= 400 { + var apiErr APIError + if err := dec.Decode(&apiErr); err != nil { + return nil, fmt.Errorf("read error response: %s", err.Error()) + } + + return nil, &apiErr + } + + var v Member + if err := dec.Decode(&v); err != nil { + return nil, fmt.Errorf("decode response: %s", err.Error()) + } + + return &v, nil +} + +// DeleteMerchantMember: Delete member +// Deletes member by ID. +func (s *MembersService) DeleteMerchantMember(ctx context.Context, merchantCode string, memberId string) error { + path := fmt.Sprintf("/v0.1/merchants/%v/members/%v", merchantCode, memberId) + + req, err := s.client.NewRequest(ctx, http.MethodDelete, path, http.NoBody) + if err != nil { + return fmt.Errorf("error building request: %v", err) + } + + resp, err := s.client.Do(req) + if err != nil { + return fmt.Errorf("error sending request: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode >= 500 { + return fmt.Errorf("invalid response: %d - %s", resp.StatusCode, http.StatusText(resp.StatusCode)) + } + + dec := json.NewDecoder(resp.Body) + if resp.StatusCode >= 400 { + var apiErr APIError + if err := dec.Decode(&apiErr); err != nil { + return fmt.Errorf("read error response: %s", err.Error()) + } + + return &apiErr + } + + return nil +} + +// GetMerchantMember: Get merchant member +// Returns merchant member details. +func (s *MembersService) GetMerchantMember(ctx context.Context, merchantCode string, memberId string) (*Member, error) { + path := fmt.Sprintf("/v0.1/merchants/%v/members/%v", merchantCode, memberId) + + req, err := s.client.NewRequest(ctx, http.MethodGet, path, http.NoBody) + if err != nil { + return nil, fmt.Errorf("error building request: %v", err) + } + + resp, err := s.client.Do(req) + if err != nil { + return nil, fmt.Errorf("error sending request: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode >= 500 { + return nil, fmt.Errorf("invalid response: %d - %s", resp.StatusCode, http.StatusText(resp.StatusCode)) + } + + dec := json.NewDecoder(resp.Body) + if resp.StatusCode >= 400 { + var apiErr APIError + if err := dec.Decode(&apiErr); err != nil { + return nil, fmt.Errorf("read error response: %s", err.Error()) + } + + return nil, &apiErr + } + + var v Member + if err := dec.Decode(&v); err != nil { + return nil, fmt.Errorf("decode response: %s", err.Error()) + } + + return &v, nil +} + +// UpdateMerchantMember: Update merchant member +// Update assigned roles of the member. +func (s *MembersService) UpdateMerchantMember(ctx context.Context, merchantCode string, memberId string, body UpdateMerchantMemberBody) error { + buf := new(bytes.Buffer) + if err := json.NewEncoder(buf).Encode(body); err != nil { + return fmt.Errorf("encoding json body request failed: %v", err) + } + + path := fmt.Sprintf("/v0.1/merchants/%v/members/%v", merchantCode, memberId) + + req, err := s.client.NewRequest(ctx, http.MethodPut, path, buf) + if err != nil { + return fmt.Errorf("error building request: %v", err) + } + + resp, err := s.client.Do(req) + if err != nil { + return fmt.Errorf("error sending request: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode >= 500 { + return fmt.Errorf("invalid response: %d - %s", resp.StatusCode, http.StatusText(resp.StatusCode)) + } + + dec := json.NewDecoder(resp.Body) + if resp.StatusCode >= 400 { + var apiErr APIError + if err := dec.Decode(&apiErr); err != nil { + return fmt.Errorf("read error response: %s", err.Error()) + } + + return &apiErr + } + + return nil +} diff --git a/memberships.go b/memberships.go new file mode 100755 index 0000000..4455628 --- /dev/null +++ b/memberships.go @@ -0,0 +1,4 @@ +// Code generated by `gogenitor`. DO NOT EDIT. +package sumup + +type MembershipsService service diff --git a/merchant.go b/merchant.go index dfb3ba1..6abce71 100755 --- a/merchant.go +++ b/merchant.go @@ -259,14 +259,6 @@ type MerchantProfile struct { // MerchantSettings is Merchant settings (like \"payout_type\", \"payout_period\") type MerchantSettings struct { - // Adyen company - AdyenCompany *string `json:"adyen_company,omitempty"` - // Adyen merchant code - AdyenMerchantCode *string `json:"adyen_merchant_code,omitempty"` - // Adyen password - AdyenPassword *string `json:"adyen_password,omitempty"` - // Adyen username - AdyenUser *string `json:"adyen_user,omitempty"` // Whether merchant will receive daily payout emails DailyPayoutEmail *bool `json:"daily_payout_email,omitempty"` // Whether merchant has gross settlement enabled @@ -351,11 +343,6 @@ type VatRates struct { Rate *float64 `json:"rate,omitempty"` } -// GetAccountParams are query parameters for GetAccount -type GetAccountParams struct { - Include *[]string `json:"include[],omitempty"` -} - // ListBankAccountsParams are query parameters for ListBankAccounts type ListBankAccountsParams struct { Primary *bool `json:"primary,omitempty"` @@ -364,12 +351,17 @@ type ListBankAccountsParams struct { // ListBankAccountsResponse is the type definition for a ListBankAccountsResponse. type ListBankAccountsResponse []BankAccount +// GetAccountParams are query parameters for GetAccount +type GetAccountParams struct { + Include *[]string `json:"include[],omitempty"` +} + type MerchantService service -// Get: Retrieve a profile -// Returns user profile information. -func (s *MerchantService) Get(ctx context.Context, params GetAccountParams) (*MerchantAccount, error) { - path := fmt.Sprintf("/v0.1/me") +// GetPersonalProfile: Retrieve a personal profile +// Retrieves personal profile data. +func (s *MerchantService) GetPersonalProfile(ctx context.Context) (*PersonalProfile, error) { + path := fmt.Sprintf("/v0.1/me/personal-profile") req, err := s.client.NewRequest(ctx, http.MethodGet, path, http.NoBody) if err != nil { @@ -396,18 +388,18 @@ func (s *MerchantService) Get(ctx context.Context, params GetAccountParams) (*Me return nil, &apiErr } - var v MerchantAccount - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + var v PersonalProfile + if err := dec.Decode(&v); err != nil { return nil, fmt.Errorf("decode response: %s", err.Error()) } return &v, nil } -// GetMerchantProfile: Retrieve a merchant profile -// Retrieves merchant profile data. -func (s *MerchantService) GetMerchantProfile(ctx context.Context) (*MerchantProfile, error) { - path := fmt.Sprintf("/v0.1/me/merchant-profile") +// GetSettings: Get settings +// Retrieves merchant settings. +func (s *MerchantService) GetSettings(ctx context.Context) (*MerchantSettings, error) { + path := fmt.Sprintf("/v0.1/me/merchant-profile/settings") req, err := s.client.NewRequest(ctx, http.MethodGet, path, http.NoBody) if err != nil { @@ -434,18 +426,18 @@ func (s *MerchantService) GetMerchantProfile(ctx context.Context) (*MerchantProf return nil, &apiErr } - var v MerchantProfile - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + var v MerchantSettings + if err := dec.Decode(&v); err != nil { return nil, fmt.Errorf("decode response: %s", err.Error()) } return &v, nil } -// ListBankAccounts: List bank accounts -// Retrives bank accounts of the merchant. -func (s *MerchantService) ListBankAccounts(ctx context.Context, params ListBankAccountsParams) (*ListBankAccountsResponse, error) { - path := fmt.Sprintf("/v0.1/me/merchant-profile/bank-accounts") +// GetDoingBusinessAs: Retrieve DBA +// Retrieves Doing Business As profile. +func (s *MerchantService) GetDoingBusinessAs(ctx context.Context) (*DoingBusinessAs, error) { + path := fmt.Sprintf("/v0.1/me/merchant-profile/doing-business-as") req, err := s.client.NewRequest(ctx, http.MethodGet, path, http.NoBody) if err != nil { @@ -472,18 +464,18 @@ func (s *MerchantService) ListBankAccounts(ctx context.Context, params ListBankA return nil, &apiErr } - var v ListBankAccountsResponse - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + var v DoingBusinessAs + if err := dec.Decode(&v); err != nil { return nil, fmt.Errorf("decode response: %s", err.Error()) } return &v, nil } -// GetDoingBusinessAs: Retrieve DBA -// Retrieves Doing Business As profile. -func (s *MerchantService) GetDoingBusinessAs(ctx context.Context) (*DoingBusinessAs, error) { - path := fmt.Sprintf("/v0.1/me/merchant-profile/doing-business-as") +// ListBankAccounts: List bank accounts +// Retrives bank accounts of the merchant. +func (s *MerchantService) ListBankAccounts(ctx context.Context, params ListBankAccountsParams) (*ListBankAccountsResponse, error) { + path := fmt.Sprintf("/v0.1/me/merchant-profile/bank-accounts") req, err := s.client.NewRequest(ctx, http.MethodGet, path, http.NoBody) if err != nil { @@ -510,18 +502,18 @@ func (s *MerchantService) GetDoingBusinessAs(ctx context.Context) (*DoingBusines return nil, &apiErr } - var v DoingBusinessAs - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + var v ListBankAccountsResponse + if err := dec.Decode(&v); err != nil { return nil, fmt.Errorf("decode response: %s", err.Error()) } return &v, nil } -// GetSettings: Get settings -// Retrieves merchant settings. -func (s *MerchantService) GetSettings(ctx context.Context) (*MerchantSettings, error) { - path := fmt.Sprintf("/v0.1/me/merchant-profile/settings") +// GetMerchantProfile: Retrieve a merchant profile +// Retrieves merchant profile data. +func (s *MerchantService) GetMerchantProfile(ctx context.Context) (*MerchantProfile, error) { + path := fmt.Sprintf("/v0.1/me/merchant-profile") req, err := s.client.NewRequest(ctx, http.MethodGet, path, http.NoBody) if err != nil { @@ -548,18 +540,18 @@ func (s *MerchantService) GetSettings(ctx context.Context) (*MerchantSettings, e return nil, &apiErr } - var v MerchantSettings - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + var v MerchantProfile + if err := dec.Decode(&v); err != nil { return nil, fmt.Errorf("decode response: %s", err.Error()) } return &v, nil } -// GetPersonalProfile: Retrieve a personal profile -// Retrieves personal profile data. -func (s *MerchantService) GetPersonalProfile(ctx context.Context) (*PersonalProfile, error) { - path := fmt.Sprintf("/v0.1/me/personal-profile") +// Get: Retrieve a profile +// Returns user profile information. +func (s *MerchantService) Get(ctx context.Context, params GetAccountParams) (*MerchantAccount, error) { + path := fmt.Sprintf("/v0.1/me") req, err := s.client.NewRequest(ctx, http.MethodGet, path, http.NoBody) if err != nil { @@ -586,8 +578,8 @@ func (s *MerchantService) GetPersonalProfile(ctx context.Context) (*PersonalProf return nil, &apiErr } - var v PersonalProfile - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + var v MerchantAccount + if err := dec.Decode(&v); err != nil { return nil, fmt.Errorf("decode response: %s", err.Error()) } diff --git a/readers.go b/readers.go new file mode 100755 index 0000000..ae4eb85 --- /dev/null +++ b/readers.go @@ -0,0 +1,308 @@ +// Code generated by `gogenitor`. DO NOT EDIT. +package sumup + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http" + "time" +) + +// Meta is Set of user-defined key-value pairs attached to the object. +type Meta struct { +} + +// Reader is A physical card reader device that can accept in-person payments. +type Reader struct { + // Reader creation timestamp. + CreatedAt time.Time `json:"created_at"` + // Information about the underlying physical device. + Device ReaderDevice `json:"device"` + // Unique identifier of the object. + // + // Note that this identifies the instance of the physical devices pairing with your SumUp account. + // + // If you DELETE a reader, and pair the device again, the ID will be different. Do not use this ID to refer to a physical device. + Id ReaderId `json:"id"` + // Set of user-defined key-value pairs attached to the object. + Meta *Meta `json:"meta,omitempty"` + // Custom human-readable, user-defined name for easier identification of the reader. + Name ReaderName `json:"name"` + // The status of the reader object gives information about the current state of the reader. + // Possible values: + // * `unknown` - The reader status is unknown. + // * `processing` - The reader is created and waits for the physical device to confirm the pairing. + // * `paired` - The reader is paired with a merchant account and can be used with SumUp APIs. + // * `expired` - The pairing is expired and no longer usable with the account. The ressource needs to get recreated + Status ReaderStatus `json:"status"` + // Reader last-modification timestamp. + UpdatedAt time.Time `json:"updated_at"` +} + +// ReaderDevice is Information about the underlying physical device. +type ReaderDevice struct { + // A unique identifier of the physical device (e.g. serial number). + Identifier string `json:"identifier"` + // Identifier of the model of the device. + Model ReaderDeviceModel `json:"model"` +} + +// Identifier of the model of the device. +type ReaderDeviceModel string + +const ( + ReaderDeviceModelSolo ReaderDeviceModel = "solo" + ReaderDeviceModelVirtualSolo ReaderDeviceModel = "virtual-solo" +) + +// ReaderId is Unique identifier of the object. +// +// Note that this identifies the instance of the physical devices pairing with your SumUp account. +// +// If you DELETE a reader, and pair the device again, the ID will be different. Do not use this ID to refer to a physical device. +type ReaderId string + +// ReaderName is Custom human-readable, user-defined name for easier identification of the reader. +type ReaderName string + +// ReaderPairingCode is The pairing code is a 8 or 9 character alphanumeric string that is displayed on a SumUp Device after initiating the pairing. +// It is used to link the physical device to the created pairing. +type ReaderPairingCode string + +// The status of the reader object gives information about the current state of the reader. +// Possible values: +// * `unknown` - The reader status is unknown. +// * `processing` - The reader is created and waits for the physical device to confirm the pairing. +// * `paired` - The reader is paired with a merchant account and can be used with SumUp APIs. +// * `expired` - The pairing is expired and no longer usable with the account. The ressource needs to get recreated +type ReaderStatus string + +const ( + ReaderStatusExpired ReaderStatus = "expired" + ReaderStatusPaired ReaderStatus = "paired" + ReaderStatusProcessing ReaderStatus = "processing" + ReaderStatusUnknown ReaderStatus = "unknown" +) + +// ListReadersResponse is the type definition for a ListReadersResponse. +type ListReadersResponse struct { + Items []Reader `json:"items"` +} + +// CreateReader request body. +type CreateReaderBody struct { + // Set of user-defined key-value pairs attached to the object. + Meta *Meta `json:"meta,omitempty"` + // Custom human-readable, user-defined name for easier identification of the reader. + Name *ReaderName `json:"name,omitempty"` + // The pairing code is a 8 or 9 character alphanumeric string that is displayed on a SumUp Device after initiating the pairing. + // It is used to link the physical device to the created pairing. + PairingCode ReaderPairingCode `json:"pairing_code"` +} + +// GetReaderParams are query parameters for GetReader +type GetReaderParams struct { + IfModifiedSince *string `json:"If-Modified-Since,omitempty"` +} + +// UpdateReader request body. +type UpdateReaderBody struct { + // Set of user-defined key-value pairs attached to the object. + Meta *Meta `json:"meta,omitempty"` + // Custom human-readable, user-defined name for easier identification of the reader. + Name *ReaderName `json:"name,omitempty"` +} + +type ReadersService service + +// ListReaders: List Readers +// Returns list of all readers of the merchant. +func (s *ReadersService) ListReaders(ctx context.Context, merchantCode string) (*ListReadersResponse, error) { + path := fmt.Sprintf("/v0.1/merchants/%v/readers", merchantCode) + + req, err := s.client.NewRequest(ctx, http.MethodGet, path, http.NoBody) + if err != nil { + return nil, fmt.Errorf("error building request: %v", err) + } + + resp, err := s.client.Do(req) + if err != nil { + return nil, fmt.Errorf("error sending request: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode >= 500 { + return nil, fmt.Errorf("invalid response: %d - %s", resp.StatusCode, http.StatusText(resp.StatusCode)) + } + + dec := json.NewDecoder(resp.Body) + if resp.StatusCode >= 400 { + var apiErr APIError + if err := dec.Decode(&apiErr); err != nil { + return nil, fmt.Errorf("read error response: %s", err.Error()) + } + + return nil, &apiErr + } + + var v ListReadersResponse + if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + return nil, fmt.Errorf("decode response: %s", err.Error()) + } + + return &v, nil +} + +// CreateReader: Create a Reader +// Create a new reader linked to the merchant account. +func (s *ReadersService) CreateReader(ctx context.Context, merchantCode string, body CreateReaderBody) (*Reader, error) { + buf := new(bytes.Buffer) + if err := json.NewEncoder(buf).Encode(body); err != nil { + return nil, fmt.Errorf("encoding json body request failed: %v", err) + } + + path := fmt.Sprintf("/v0.1/merchants/%v/readers", merchantCode) + + req, err := s.client.NewRequest(ctx, http.MethodPost, path, buf) + if err != nil { + return nil, fmt.Errorf("error building request: %v", err) + } + + resp, err := s.client.Do(req) + if err != nil { + return nil, fmt.Errorf("error sending request: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode >= 500 { + return nil, fmt.Errorf("invalid response: %d - %s", resp.StatusCode, http.StatusText(resp.StatusCode)) + } + + dec := json.NewDecoder(resp.Body) + if resp.StatusCode >= 400 { + var apiErr APIError + if err := dec.Decode(&apiErr); err != nil { + return nil, fmt.Errorf("read error response: %s", err.Error()) + } + + return nil, &apiErr + } + + var v Reader + if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + return nil, fmt.Errorf("decode response: %s", err.Error()) + } + + return &v, nil +} + +// DeleteReader: Delete a reader +// Deletes a Reader. +func (s *ReadersService) DeleteReader(ctx context.Context, merchantCode string, id ReaderId) error { + path := fmt.Sprintf("/v0.1/merchants/%v/readers/%v", merchantCode, id) + + req, err := s.client.NewRequest(ctx, http.MethodDelete, path, http.NoBody) + if err != nil { + return fmt.Errorf("error building request: %v", err) + } + + resp, err := s.client.Do(req) + if err != nil { + return fmt.Errorf("error sending request: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode >= 500 { + return fmt.Errorf("invalid response: %d - %s", resp.StatusCode, http.StatusText(resp.StatusCode)) + } + + dec := json.NewDecoder(resp.Body) + if resp.StatusCode >= 400 { + var apiErr APIError + if err := dec.Decode(&apiErr); err != nil { + return fmt.Errorf("read error response: %s", err.Error()) + } + + return &apiErr + } + + return nil +} + +// GetReader: Retrieve a Reader +// Gets a Reader. +func (s *ReadersService) GetReader(ctx context.Context, merchantCode string, id ReaderId, params GetReaderParams) (*Reader, error) { + path := fmt.Sprintf("/v0.1/merchants/%v/readers/%v", merchantCode, id) + + req, err := s.client.NewRequest(ctx, http.MethodGet, path, http.NoBody) + if err != nil { + return nil, fmt.Errorf("error building request: %v", err) + } + + resp, err := s.client.Do(req) + if err != nil { + return nil, fmt.Errorf("error sending request: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode >= 500 { + return nil, fmt.Errorf("invalid response: %d - %s", resp.StatusCode, http.StatusText(resp.StatusCode)) + } + + dec := json.NewDecoder(resp.Body) + if resp.StatusCode >= 400 { + var apiErr APIError + if err := dec.Decode(&apiErr); err != nil { + return nil, fmt.Errorf("read error response: %s", err.Error()) + } + + return nil, &apiErr + } + + var v Reader + if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + return nil, fmt.Errorf("decode response: %s", err.Error()) + } + + return &v, nil +} + +// UpdateReader: Update a Reader +// Updates a Reader. +func (s *ReadersService) UpdateReader(ctx context.Context, merchantCode string, id ReaderId, body UpdateReaderBody) error { + buf := new(bytes.Buffer) + if err := json.NewEncoder(buf).Encode(body); err != nil { + return fmt.Errorf("encoding json body request failed: %v", err) + } + + path := fmt.Sprintf("/v0.1/merchants/%v/readers/%v", merchantCode, id) + + req, err := s.client.NewRequest(ctx, http.MethodPatch, path, buf) + if err != nil { + return fmt.Errorf("error building request: %v", err) + } + + resp, err := s.client.Do(req) + if err != nil { + return fmt.Errorf("error sending request: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode >= 500 { + return fmt.Errorf("invalid response: %d - %s", resp.StatusCode, http.StatusText(resp.StatusCode)) + } + + dec := json.NewDecoder(resp.Body) + if resp.StatusCode >= 400 { + var apiErr APIError + if err := dec.Decode(&apiErr); err != nil { + return fmt.Errorf("read error response: %s", err.Error()) + } + + return &apiErr + } + + return nil +} diff --git a/receipts.go b/receipts.go index 0e6eaed..cdc1a0c 100755 --- a/receipts.go +++ b/receipts.go @@ -181,7 +181,7 @@ func (s *ReceiptsService) Get(ctx context.Context, id string, params GetReceiptP } var v Receipt - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + if err := dec.Decode(&v); err != nil { return nil, fmt.Errorf("decode response: %s", err.Error()) } diff --git a/subaccounts.go b/subaccounts.go index 867eb00..f4c6cf1 100755 --- a/subaccounts.go +++ b/subaccounts.go @@ -77,7 +77,7 @@ func (s *SubaccountsService) List(ctx context.Context) (*ListSubAccountsResponse } var v ListSubAccountsResponse - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + if err := dec.Decode(&v); err != nil { return nil, fmt.Errorf("decode response: %s", err.Error()) } @@ -120,7 +120,7 @@ func (s *SubaccountsService) CreateSubAccount(ctx context.Context, body CreateSu } var v Subaccount - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + if err := dec.Decode(&v); err != nil { return nil, fmt.Errorf("decode response: %s", err.Error()) } @@ -158,7 +158,7 @@ func (s *SubaccountsService) Deactivate(ctx context.Context, operatorCode string } var v Subaccount - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + if err := dec.Decode(&v); err != nil { return nil, fmt.Errorf("decode response: %s", err.Error()) } @@ -201,7 +201,7 @@ func (s *SubaccountsService) Update(ctx context.Context, operatorCode string, bo } var v Subaccount - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + if err := dec.Decode(&v); err != nil { return nil, fmt.Errorf("decode response: %s", err.Error()) } diff --git a/transactions.go b/transactions.go index 398c7d8..0839f09 100755 --- a/transactions.go +++ b/transactions.go @@ -92,30 +92,6 @@ type Event struct { Type *EventType `json:"type,omitempty"` } -// FinancialTransaction is the type definition for a FinancialTransaction. -type FinancialTransaction struct { - Amount *float64 `json:"amount,omitempty"` - Currency *string `json:"currency,omitempty"` - ExternalReference *string `json:"external_reference,omitempty"` - Id *string `json:"id,omitempty"` - Timestamp *string `json:"timestamp,omitempty"` - TransactionCode *string `json:"transaction_code,omitempty"` - Type *FinancialTransactionType `json:"type,omitempty"` -} - -type FinancialTransactionType string - -const ( - FinancialTransactionTypeChargeBack FinancialTransactionType = "CHARGE_BACK" - FinancialTransactionTypeDdReturn FinancialTransactionType = "DD_RETURN" - FinancialTransactionTypeDdReturnReversal FinancialTransactionType = "DD_RETURN_REVERSAL" - FinancialTransactionTypeRefund FinancialTransactionType = "REFUND" - FinancialTransactionTypeSale FinancialTransactionType = "SALE" -) - -// FinancialTransactions is the type definition for a FinancialTransactions. -type FinancialTransactions []FinancialTransaction - // HorizontalAccuracy is Indication of the precision of the geographical position received from the payment terminal. type HorizontalAccuracy float64 @@ -474,32 +450,6 @@ const ( TransactionMixinHistoryPayoutPlanTrueInstallment TransactionMixinHistoryPayoutPlan = "TRUE_INSTALLMENT" ) -// ListFinancialTransactionsParams are query parameters for ListFinancialTransactions -type ListFinancialTransactionsParams struct { - EndDate time.Time `json:"end_date"` - Format *string `json:"format,omitempty"` - Limit *int `json:"limit,omitempty"` - Order *string `json:"order,omitempty"` - StartDate time.Time `json:"start_date"` -} - -// RefundTransaction request body. -type RefundTransactionBody struct { - // Amount to be refunded. Eligible amount can't exceed the amount of the transaction and varies based on country and currency. If you do not specify a value, the system performs a full refund of the transaction. - Amount *float64 `json:"amount,omitempty"` -} - -// RefundTransactionResponse is the type definition for a RefundTransactionResponse. -type RefundTransactionResponse struct { -} - -// GetTransactionParams are query parameters for GetTransaction -type GetTransactionParams struct { - Id *string `json:"id,omitempty"` - InternalId *string `json:"internal_id,omitempty"` - TransactionCode *string `json:"transaction_code,omitempty"` -} - // ListTransactionsParams are query parameters for ListTransactions type ListTransactionsParams struct { ChangesSince *time.Time `json:"changes_since,omitempty"` @@ -522,57 +472,31 @@ type ListTransactionsResponse struct { Links *[]Link `json:"links,omitempty"` } -type TransactionsService service - -// List: List financial transactions -// Lists a less detailed history of all transactions associated with the merchant profile. -func (s *TransactionsService) List(ctx context.Context, params ListFinancialTransactionsParams) (*FinancialTransactions, error) { - path := fmt.Sprintf("/v0.1/me/financials/transactions") - - req, err := s.client.NewRequest(ctx, http.MethodGet, path, http.NoBody) - if err != nil { - return nil, fmt.Errorf("error building request: %v", err) - } - - resp, err := s.client.Do(req) - if err != nil { - return nil, fmt.Errorf("error sending request: %v", err) - } - defer resp.Body.Close() - - if resp.StatusCode >= 500 { - return nil, fmt.Errorf("invalid response: %d - %s", resp.StatusCode, http.StatusText(resp.StatusCode)) - } - - dec := json.NewDecoder(resp.Body) - if resp.StatusCode >= 400 { - var apiErr APIError - if err := dec.Decode(&apiErr); err != nil { - return nil, fmt.Errorf("read error response: %s", err.Error()) - } - - return nil, &apiErr - } +// GetTransactionParams are query parameters for GetTransaction +type GetTransactionParams struct { + Id *string `json:"id,omitempty"` + InternalId *string `json:"internal_id,omitempty"` + TransactionCode *string `json:"transaction_code,omitempty"` +} - var v FinancialTransactions - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { - return nil, fmt.Errorf("decode response: %s", err.Error()) - } +// RefundTransaction request body. +type RefundTransactionBody struct { + // Amount to be refunded. Eligible amount can't exceed the amount of the transaction and varies based on country and currency. If you do not specify a value, the system performs a full refund of the transaction. + Amount *float64 `json:"amount,omitempty"` +} - return &v, nil +// RefundTransactionResponse is the type definition for a RefundTransactionResponse. +type RefundTransactionResponse struct { } -// Refund: Refund a transaction -// Refunds an identified transaction either in full or partially. -func (s *TransactionsService) Refund(ctx context.Context, txnId string, body RefundTransactionBody) (*RefundTransactionResponse, error) { - buf := new(bytes.Buffer) - if err := json.NewEncoder(buf).Encode(body); err != nil { - return nil, fmt.Errorf("encoding json body request failed: %v", err) - } +type TransactionsService service - path := fmt.Sprintf("/v0.1/me/refund/%v", txnId) +// ListDetailed: List transactions +// Lists detailed history of all transactions associated with the merchant profile. +func (s *TransactionsService) ListDetailed(ctx context.Context, params ListTransactionsParams) (*ListTransactionsResponse, error) { + path := fmt.Sprintf("/v0.1/me/transactions/history") - req, err := s.client.NewRequest(ctx, http.MethodPost, path, buf) + req, err := s.client.NewRequest(ctx, http.MethodGet, path, http.NoBody) if err != nil { return nil, fmt.Errorf("error building request: %v", err) } @@ -597,8 +521,8 @@ func (s *TransactionsService) Refund(ctx context.Context, txnId string, body Ref return nil, &apiErr } - var v RefundTransactionResponse - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + var v ListTransactionsResponse + if err := dec.Decode(&v); err != nil { return nil, fmt.Errorf("decode response: %s", err.Error()) } @@ -641,19 +565,24 @@ func (s *TransactionsService) Get(ctx context.Context, params GetTransactionPara } var v TransactionFull - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + if err := dec.Decode(&v); err != nil { return nil, fmt.Errorf("decode response: %s", err.Error()) } return &v, nil } -// ListDetailed: List transactions -// Lists detailed history of all transactions associated with the merchant profile. -func (s *TransactionsService) ListDetailed(ctx context.Context, params ListTransactionsParams) (*ListTransactionsResponse, error) { - path := fmt.Sprintf("/v0.1/me/transactions/history") +// Refund: Refund a transaction +// Refunds an identified transaction either in full or partially. +func (s *TransactionsService) Refund(ctx context.Context, txnId string, body RefundTransactionBody) (*RefundTransactionResponse, error) { + buf := new(bytes.Buffer) + if err := json.NewEncoder(buf).Encode(body); err != nil { + return nil, fmt.Errorf("encoding json body request failed: %v", err) + } - req, err := s.client.NewRequest(ctx, http.MethodGet, path, http.NoBody) + path := fmt.Sprintf("/v0.1/me/refund/%v", txnId) + + req, err := s.client.NewRequest(ctx, http.MethodPost, path, buf) if err != nil { return nil, fmt.Errorf("error building request: %v", err) } @@ -678,8 +607,8 @@ func (s *TransactionsService) ListDetailed(ctx context.Context, params ListTrans return nil, &apiErr } - var v ListTransactionsResponse - if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + var v RefundTransactionResponse + if err := dec.Decode(&v); err != nil { return nil, fmt.Errorf("decode response: %s", err.Error()) }