1
+ /*
2
+ * This sample demonstrates how to configure the library for the Onshape API.
3
+ * To generate OAuth credentials, create an OAuth application here:
4
+ * https://dev-portal.onshape.com/
5
+ */
6
+
7
+ // Make sure to include any trailng '=' symbols in the ID and Secret.
8
+ var CLIENT_ID = '...' ;
9
+ var CLIENT_SECRET = '...' ;
10
+
11
+ /**
12
+ * Authorizes and makes a request to the Onshape API.
13
+ */
14
+ function run ( ) {
15
+ var service = getService_ ( ) ;
16
+ if ( service . hasAccess ( ) ) {
17
+ // Make a request to retrieve a list of the user's documents.
18
+ // This requires enabling the OAuth2Read scope for the application in the
19
+ // Onshape developer portal. ("Application can read your documents")
20
+ var url = 'https://cad.onshape.com/api/documents' ;
21
+ var response = UrlFetchApp . fetch ( url , {
22
+ headers : {
23
+ Authorization : 'Bearer ' + service . getAccessToken ( )
24
+ }
25
+ } ) ;
26
+ var result = JSON . parse ( response . getContentText ( ) ) ;
27
+ Logger . log ( JSON . stringify ( result , null , 2 ) ) ;
28
+ } else {
29
+ var authorizationUrl = service . getAuthorizationUrl ( ) ;
30
+ Logger . log ( 'Open the following URL and re-run the script: %s' ,
31
+ authorizationUrl ) ;
32
+ }
33
+ }
34
+
35
+ /**
36
+ * Reset the authorization state, so that it can be re-tested.
37
+ */
38
+ function reset ( ) {
39
+ getService_ ( ) . reset ( ) ;
40
+ }
41
+
42
+ /**
43
+ * Configures the service.
44
+ */
45
+ function getService_ ( ) {
46
+ return OAuth2 . createService ( 'Onshape' )
47
+ // Set the Onshape OAuth endpoint URLs.
48
+ . setAuthorizationBaseUrl ( 'https://oauth.onshape.com/oauth/authorize' )
49
+ . setTokenUrl ( 'https://oauth.onshape.com/oauth/token' )
50
+
51
+ // Set the client ID and secret.
52
+ . setClientId ( CLIENT_ID )
53
+ . setClientSecret ( CLIENT_SECRET )
54
+
55
+ // Set the name of the callback function that should be invoked to
56
+ // complete the OAuth flow.
57
+ . setCallbackFunction ( 'authCallback' )
58
+
59
+ // Set the property store where authorized tokens should be persisted.
60
+ . setPropertyStore ( PropertiesService . getUserProperties ( ) ) ;
61
+ }
62
+
63
+ /**
64
+ * Handles the OAuth callback.
65
+ */
66
+ function authCallback ( request ) {
67
+ var service = getService_ ( ) ;
68
+ var authorized = service . handleCallback ( request ) ;
69
+ if ( authorized ) {
70
+ return HtmlService . createHtmlOutput ( 'Success!' ) ;
71
+ } else {
72
+ return HtmlService . createHtmlOutput ( 'Denied.' ) ;
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Logs the redict URI to register.
78
+ */
79
+ function logRedirectUri ( ) {
80
+ Logger . log ( OAuth2 . getRedirectUri ( ) ) ;
81
+ }
0 commit comments