-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpaypal.go
95 lines (85 loc) · 2.09 KB
/
paypal.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
package main
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"github.com/plutov/paypal/v4"
)
func NewPaypalClient() *paypal.Client {
auth, ok := providerAuth["paypal"]
if !ok {
return nil
}
client, err := paypal.NewClient(auth.ClientID, auth.Secret, auth.APIBase)
FatalIf(err)
_, err = client.GetAccessToken(context.Background())
FatalIf(err)
log.Println("Using PayPal auth", auth)
return client
}
type eInvalidAmount struct {
amount paypal.PurchaseUnitAmount
}
func (e eInvalidAmount) Error() string {
return fmt.Sprintf("invalid purchase unit amount: %v", e.amount)
}
func parseAmount(amount paypal.PurchaseUnitAmount) (cents int, err error) {
var euros int
if amount.Currency != "EUR" {
return 0, eInvalidAmount{amount}
}
n, err := fmt.Sscanf(amount.Value, "%d.%d", &euros, ¢s)
if n != 2 {
return 0, eInvalidAmount{amount}
} else if err != nil {
return 0, err
}
return euros*100 + cents, nil
}
// Pulling the amount from PayPal only seems to work for regular orders, not
// subscriptions…
func processOrder(in *Incoming, order *paypal.Order) error {
in.Cents = 0 // Don't rely on or duplicate any value sent by the frontend.
in.Time = order.UpdateTime
for _, pu := range order.PurchaseUnits {
cents, err := parseAmount(*pu.Amount)
if err != nil {
return err
}
in.Cents += cents
}
return nil
}
func processSubscription(in *Incoming, order *paypal.Order) error {
in.Time = order.CreateTime
return nil
}
func PaypalIncomingHandler(client *paypal.Client) ProviderHandler {
return func(wr http.ResponseWriter, req *http.Request, in *Incoming) {
if client == nil {
respondWithError(wr, errors.New(
"server is not authenticated with PayPal",
))
return
}
order, err := client.GetOrder(context.Background(), in.ProviderSession)
if err != nil {
respondWithError(wr, err)
return
}
switch in.Cycle {
case "onetime":
err = processOrder(in, order)
case "monthly":
err = processSubscription(in, order)
}
if err != nil {
respondWithError(wr, err)
}
if err = incoming.Insert(in); err != nil {
respondWithError(wr, err)
}
}
}