-
Notifications
You must be signed in to change notification settings - Fork 17
/
referral_customer.go
270 lines (224 loc) · 11.6 KB
/
referral_customer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
package easypost
import (
"context"
"encoding/json"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
// A BetaPaymentRefund that has the refund details for the refund request.
type BetaPaymentRefund struct {
RefundedAmount int `json:"refunded_amount,omitempty" url:"refunded_amount,omitempty"`
RefundedPaymentLogs []string `json:"refunded_payment_log,omitempty" url:"refunded_payment_log,omitempty"`
PaymentLogId string `json:"payment_log_id,omitempty" url:"payment_log_id,omitempty"`
Errors []APIError `json:"errors,omitempty" url:"errors,omitempty"`
}
// A ReferralCustomer contains data about an EasyPost referral customer.
type ReferralCustomer struct {
User
}
// ListReferralCustomersResult holds the results from the list referral customers API call.
type ListReferralCustomersResult struct {
ReferralCustomers []*ReferralCustomer `json:"referral_customers,omitempty" url:"referral_customers,omitempty"`
PaginatedCollection
}
// CreditCardOptions specifies options for creating or updating a credit card.
type CreditCardOptions struct {
Number string `json:"number,omitempty" url:"number,omitempty"`
ExpMonth string `json:"expiration_month,omitempty" url:"expiration_month,omitempty"`
ExpYear string `json:"expiration_year,omitempty" url:"expiration_year,omitempty"`
Cvc string `json:"cvc,omitempty" url:"cvc,omitempty"`
}
type stripeApiKeyResponse struct {
PublicKey string `json:"public_key,omitempty" url:"public_key,omitempty"`
}
type stripeTokenResponse struct {
Id string `json:"id,omitempty" url:"id,omitempty"`
}
type referralCustomerRequest struct {
UserOptions *UserOptions `json:"user,omitempty" url:"user,omitempty"`
}
type creditCardCreateRequest struct {
CreditCard *easypostCreditCardCreateOptions `json:"credit_card,omitempty" url:"credit_card,omitempty"`
}
type easypostCreditCardCreateOptions struct {
StripeToken string `json:"stripe_object_id,omitempty" url:"stripe_object_id,omitempty"`
Priority string `json:"priority,omitempty" url:"priority,omitempty"`
}
// CreateReferralCustomer creates a new referral customer.
func (c *Client) CreateReferralCustomer(in *UserOptions) (out *ReferralCustomer, err error) {
return c.CreateReferralCustomerWithContext(context.Background(), in)
}
// CreateReferralCustomerWithContext performs the same operation as CreateReferralCustomer, but allows
// specifying a context that can interrupt the request.
func (c *Client) CreateReferralCustomerWithContext(ctx context.Context, in *UserOptions) (out *ReferralCustomer, err error) {
err = c.do(ctx, http.MethodPost, "referral_customers", &referralCustomerRequest{UserOptions: in}, &out)
return
}
// ListReferralCustomers provides a paginated result of ReferralCustomer objects.
func (c *Client) ListReferralCustomers(opts *ListOptions) (out *ListReferralCustomersResult, err error) {
return c.ListReferralCustomersWithContext(context.Background(), opts)
}
// ListReferralCustomersWithContext performs the same operation as ListReferralCustomers, but
// allows specifying a context that can interrupt the request.
func (c *Client) ListReferralCustomersWithContext(ctx context.Context, opts *ListOptions) (out *ListReferralCustomersResult, err error) {
err = c.do(ctx, http.MethodGet, "referral_customers", opts, &out)
return
}
// GetNextReferralCustomerPage returns the next page of referral customers
func (c *Client) GetNextReferralCustomerPage(collection *ListReferralCustomersResult) (out *ListReferralCustomersResult, err error) {
return c.GetNextReferralCustomerPageWithContext(context.Background(), collection)
}
// GetNextReferralCustomerPageWithPageSize returns the next page of referral customers with a specific page size
func (c *Client) GetNextReferralCustomerPageWithPageSize(collection *ListReferralCustomersResult, pageSize int) (out *ListReferralCustomersResult, err error) {
return c.GetNextReferralCustomerPageWithPageSizeWithContext(context.Background(), collection, pageSize)
}
// GetNextReferralCustomerPageWithContext performs the same operation as GetNextReferralCustomerPage, but
// allows specifying a context that can interrupt the request.
func (c *Client) GetNextReferralCustomerPageWithContext(ctx context.Context, collection *ListReferralCustomersResult) (out *ListReferralCustomersResult, err error) {
return c.GetNextReferralCustomerPageWithPageSizeWithContext(ctx, collection, 0)
}
// GetNextReferralCustomerPageWithPageSizeWithContext performs the same operation as GetNextReferralCustomerPageWithPageSize, but
// allows specifying a context that can interrupt the request.
func (c *Client) GetNextReferralCustomerPageWithPageSizeWithContext(ctx context.Context, collection *ListReferralCustomersResult, pageSize int) (out *ListReferralCustomersResult, err error) {
if len(collection.ReferralCustomers) == 0 {
err = EndOfPaginationError
return
}
lastID := collection.ReferralCustomers[len(collection.ReferralCustomers)-1].ID
params, err := nextPageParameters(collection.HasMore, lastID, pageSize)
if err != nil {
return
}
return c.ListReferralCustomersWithContext(ctx, params)
}
// UpdateReferralCustomerEmail updates a ReferralCustomer's email address
func (c *Client) UpdateReferralCustomerEmail(userId string, email string) (out *ReferralCustomer, err error) {
return c.UpdateReferralCustomerEmailWithContext(context.Background(), userId, email)
}
// UpdateReferralCustomerEmailWithContext performs the same operation as UpdateReferralCustomerEmail, but allows
// specifying a context that can interrupt the request.
func (c *Client) UpdateReferralCustomerEmailWithContext(ctx context.Context, userId string, email string) (out *ReferralCustomer, err error) {
req := referralCustomerRequest{
UserOptions: &UserOptions{
Email: &email,
},
}
err = c.do(ctx, http.MethodPut, "referral_customers/"+userId, req, &out)
return
}
// AddReferralCustomerCreditCard adds a credit card to a referral customer's account.
func (c *Client) AddReferralCustomerCreditCard(referralCustomerApiKey string, creditCardOptions *CreditCardOptions, priority PaymentMethodPriority) (out *PaymentMethodObject, err error) {
return c.AddReferralCustomerCreditCardWithContext(context.Background(), referralCustomerApiKey, creditCardOptions, priority)
}
// AddReferralCustomerCreditCardWithContext performs the same operation as AddReferralCustomerCreditCard, but allows
// specifying a context that can interrupt the request.
func (c *Client) AddReferralCustomerCreditCardWithContext(ctx context.Context, referralCustomerApiKey string, creditCardOptions *CreditCardOptions, priority PaymentMethodPriority) (out *PaymentMethodObject, err error) {
stripeApiKeyResponse, err := c.retrieveEasypostStripeApiKey(ctx)
if err != nil || stripeApiKeyResponse == nil || stripeApiKeyResponse.PublicKey == "" {
return nil, &InternalServerError{
APIError: APIError{
Code: "Could not create Stripe token, please try again later",
StatusCode: 500,
},
}
}
stripeTokenResponse, err := c.createStripeToken(ctx, stripeApiKeyResponse.PublicKey, creditCardOptions)
if err != nil || stripeTokenResponse == nil || stripeTokenResponse.Id == "" {
return nil, newExternalApiError("Could not create Stripe token, please try again later")
}
return c.createEasypostCreditCard(ctx, referralCustomerApiKey, stripeTokenResponse.Id, priority)
}
func (c *Client) retrieveEasypostStripeApiKey(ctx context.Context) (out *stripeApiKeyResponse, err error) {
err = c.do(ctx, http.MethodGet, "partners/stripe_public_key", nil, &out)
return
}
func (c *Client) createStripeToken(ctx context.Context, stripeApiKey string, creditCardOptions *CreditCardOptions) (out *stripeTokenResponse, err error) {
data := url.Values{}
data.Set("card[number]", creditCardOptions.Number)
data.Set("card[exp_month]", creditCardOptions.ExpMonth)
data.Set("card[exp_year]", creditCardOptions.ExpYear)
data.Set("card[cvc]", creditCardOptions.Cvc)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://api.stripe.com/v1/tokens", strings.NewReader(data.Encode()))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Authorization", "Bearer "+stripeApiKey)
resp, err := c.client().Do(req) // use the current client's inner http.Client (configured to record) for the one-off request
if err != nil {
return nil, err
}
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(resp.Body)
body, err := ioutil.ReadAll(resp.Body) // deprecated, but we have to keep it for legacy compatibility
if err != nil {
return nil, err
}
err = json.Unmarshal(body, &out)
if err != nil {
return nil, err
}
return
}
func (c *Client) createEasypostCreditCard(ctx context.Context, referralCustomerApiKey string, stripeToken string, priority PaymentMethodPriority) (out *PaymentMethodObject, err error) {
client := &Client{
APIKey: referralCustomerApiKey,
Client: c.client(), // pass the current client's inner http.Client (configured to record) to the new client
}
creditCardOptions := &easypostCreditCardCreateOptions{
StripeToken: stripeToken,
Priority: c.GetPaymentEndpointByPrimaryOrSecondary(priority),
}
creditCardRequest := &creditCardCreateRequest{
CreditCard: creditCardOptions,
}
err = client.do(ctx, http.MethodPost, "credit_cards", creditCardRequest, &out)
return
}
// BetaAddPaymentMethod adds Stripe payment method to referral customer.
func (c *Client) BetaAddPaymentMethod(stripeCustomerId string, paymentMethodReference string, priority PaymentMethodPriority) (out *PaymentMethodObject, err error) {
return c.BetaAddPaymentMethodWithContext(context.Background(), stripeCustomerId, paymentMethodReference, priority)
}
// BetaAddPaymentMethodWithContext performs the same operation as BetaAddPaymentMethod, but allows
// specifying a context that can interrupt the request.
func (c *Client) BetaAddPaymentMethodWithContext(ctx context.Context, stripeCustomerId string, paymentMethodReference string, priority PaymentMethodPriority) (out *PaymentMethodObject, err error) {
wrappedParams := map[string]interface{}{
"payment_method": map[string]interface{}{
"stripe_customer_id": stripeCustomerId,
"payment_method_reference": paymentMethodReference,
"priority": c.GetPaymentEndpointByPrimaryOrSecondary(priority),
},
}
err = c.do(ctx, http.MethodPost, "/beta/referral_customers/payment_method", wrappedParams, out)
return
}
// BetaRefundByAmount refunds a recent payment by amount in cents.
func (c *Client) BetaRefundByAmount(refundAmount int) (out *BetaPaymentRefund, err error) {
return c.BetaRefundByAmountWithContext(context.Background(), refundAmount)
}
// BetaRefundByAmountWithContext performs the same operation as BetaRefundByAmount, but allows
// specifying a context that can interrupt the request.
func (c *Client) BetaRefundByAmountWithContext(ctx context.Context, refundAmount int) (out *BetaPaymentRefund, err error) {
params := map[string]interface{}{
"refund_amount": refundAmount,
}
err = c.do(ctx, http.MethodPost, "/beta/referral_customers/refunds", params, out)
return
}
// BetaRefundByPaymentLog refunds a payment by payment log ID.
func (c *Client) BetaRefundByPaymentLog(paymentLogId string) (out *BetaPaymentRefund, err error) {
return c.BetaRefundByPaymentLogWithContext(context.Background(), paymentLogId)
}
// BetaRefundByPaymentLogWithContext performs the same operation as BetaRefundByPaymentLog, but allows
// specifying a context that can interrupt the request.
func (c *Client) BetaRefundByPaymentLogWithContext(ctx context.Context, paymentLogId string) (out *BetaPaymentRefund, err error) {
params := map[string]interface{}{
"payment_log_id": paymentLogId,
}
err = c.do(ctx, http.MethodPost, "/beta/referral_customers/refunds", params, out)
return
}