1
+ var CLIENT_ID = '...' ;
2
+ var CLIENT_SECRET = '...' ;
3
+
4
+ /**
5
+ * Authorizes and makes a request to the Wordpress API.
6
+ */
7
+ function run ( ) {
8
+ var service = getService ( ) ;
9
+ if ( service . hasAccess ( ) ) {
10
+ var blogId = service . getToken_ ( ) . blog_id ;
11
+ var url = 'https://public-api.wordpress.com/rest/v1.1/sites/' + blogId + '/posts' ;
12
+ var response = UrlFetchApp . fetch ( url , {
13
+ headers : {
14
+ 'Authorization' : 'Bearer ' + service . getAccessToken ( )
15
+ }
16
+ } ) ;
17
+ var result = JSON . parse ( response . getContentText ( ) ) ;
18
+ Logger . log ( JSON . stringify ( result , null , 2 ) ) ;
19
+ } else {
20
+ var authorizationUrl = service . getAuthorizationUrl ( ) ;
21
+ Logger . log ( 'Open the following URL and re-run the script: %s' ,
22
+ authorizationUrl ) ;
23
+ }
24
+ }
25
+
26
+ /**
27
+ * Reset the authorization state, so that it can be re-tested.
28
+ */
29
+ function reset ( ) {
30
+ var service = getService ( ) ;
31
+ service . reset ( ) ;
32
+ }
33
+
34
+ /**
35
+ * Configures the service.
36
+ */
37
+ function getService ( ) {
38
+ return OAuth2 . createService ( 'Wordpress' )
39
+ // Set the endpoint URLs.
40
+ . setTokenUrl ( 'https://public-api.wordpress.com/oauth2/token' )
41
+ . setAuthorizationBaseUrl ( 'https://public-api.wordpress.com/oauth2/authorize' )
42
+
43
+ // Set the client ID and secret.
44
+ . setClientId ( CLIENT_ID )
45
+ . setClientSecret ( CLIENT_SECRET )
46
+
47
+ // Set the name of the callback function in the script referenced
48
+ // above that should be invoked to complete the OAuth flow.
49
+ . setCallbackFunction ( 'authCallback' )
50
+
51
+ // Set the property store where authorized tokens should be persisted.
52
+ . setPropertyStore ( PropertiesService . getUserProperties ( ) ) ;
53
+ }
54
+
55
+ /**
56
+ * Handles the OAuth2 callback.
57
+ */
58
+ function authCallback ( request ) {
59
+ var service = getService ( ) ;
60
+ var authorized = service . handleCallback ( request ) ;
61
+ if ( authorized ) {
62
+ return HtmlService . createHtmlOutput ( 'Success!' ) ;
63
+ } else {
64
+ return HtmlService . createHtmlOutput ( 'Denied' ) ;
65
+ }
66
+ }
0 commit comments