-
Notifications
You must be signed in to change notification settings - Fork 16
/
example_test.go
105 lines (82 loc) · 2.26 KB
/
example_test.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
package patreon
import (
"fmt"
"os"
"time"
"golang.org/x/oauth2"
)
var testAccessToken = os.Getenv("PATREON_ACCESS_TOKEN")
// Fetches the list of pledges with corresponding users.
// This example is a port of PHP version https://github.com/Patreon/patreon-php/blob/master/examples/patron-list.php
func Example_fetchPatronsAndPledges() {
ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: testAccessToken})
tc := oauth2.NewClient(oauth2.NoContext, ts)
// Create client with static access token
client := NewClient(tc)
// Get your campaign data
campaignResponse, err := client.FetchCampaign()
if err != nil {
panic(err)
}
campaignId := campaignResponse.Data[0].ID
cursor := ""
page := 1
for {
pledgesResponse, err := client.FetchPledges(campaignId,
WithPageSize(25),
WithCursor(cursor))
if err != nil {
panic(err)
}
// Get all the users in an easy-to-lookup way
users := make(map[string]*User)
for _, item := range pledgesResponse.Included.Items {
u, ok := item.(*User)
if !ok {
continue
}
users[u.ID] = u
}
fmt.Printf("Page %d\r\n", page)
// Loop over the pledges to get e.g. their amount and user name
for _, pledge := range pledgesResponse.Data {
amount := pledge.Attributes.AmountCents
patronId := pledge.Relationships.Patron.Data.ID
patronFullName := users[patronId].Attributes.FullName
fmt.Printf("%s is pledging %d cents\r\n", patronFullName, amount)
}
// Get the link to the next page of pledges
nextLink := pledgesResponse.Links.Next
if nextLink == "" {
break
}
cursor = nextLink
page++
}
fmt.Print("Done!")
}
// Automatically refresh token
func Example_refreshToken() {
config := oauth2.Config{
ClientID: "<client_id>",
ClientSecret: "<client_secret>",
Endpoint: oauth2.Endpoint{
AuthURL: AuthorizationURL,
TokenURL: AccessTokenURL,
},
Scopes: []string{"users", "pledges-to-me", "my-campaign"},
}
token := oauth2.Token{
AccessToken: "<current_access_token>",
RefreshToken: "<current_refresh_token>",
// Must be non-nil, otherwise token will not be expired
Expiry: time.Now().Add(-24 * time.Hour),
}
tc := config.Client(oauth2.NoContext, &token)
client := NewClient(tc)
_, err := client.FetchUser()
if err != nil {
panic(err)
}
print("OK")
}