Xbase++
Xbase++
UPS OAuth2 Client Credentials
See more UPS Examples
Get an OAuth2 access token for the UPS REST API using the client credentials flow (no interactivity with a web browser required).Chilkat Xbase++ Downloads
LOCAL nSuccess
LOCAL oHttp
LOCAL oReq
LOCAL oResp
LOCAL oSbResponseBody
LOCAL oJResp
LOCAL nRespStatusCode
LOCAL cToken_type
LOCAL cIssued_at
LOCAL cClient_id
LOCAL cAccess_token
LOCAL cExpires_in
LOCAL cStatus
nSuccess := 0
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
oHttp := CreateObject("Chilkat.Http")
// Implements the following CURL command:
// curl -i -X POST \
// -u 2498righ8wr6aihe98rt8rhowirtyw9er6twe80rtywrehrt:nerf254578uh8rgt7y3h57358ouyth387h8h53h6yyh80hh578per9y7u5ruyuy4 \
// https://wwwcie.ups.com/security/v1/oauth/token \
// -H 'Content-Type: application/x-www-form-urlencoded' \
// -H 'x-merchant-id: 7B3027' \
// -d grant_type=client_credentials
// Use the following online tool to generate HTTP code from a CURL command
// Convert a cURL Command to HTTP Source Code
oHttp:BasicAuth := 1
oHttp:Login := "2498righ8wr6aihe98rt8rhowirtyw9er6twe80rtywrehrt"
oHttp:Password := "nerf254578uh8rgt7y3h57358ouyth387h8h53h6yyh80hh578per9y7u5ruyuy4"
oReq := CreateObject("Chilkat.HttpRequest")
oReq:AddParam("grant_type", "client_credentials")
oReq:AddHeader("x-merchant-id", "7B3027")
oReq:HttpVerb := "POST"
oReq:ContentType := "application/x-www-form-urlencoded"
oResp := CreateObject("Chilkat.HttpResponse")
nSuccess := oHttp:HttpReq("https://wwwcie.ups.com/security/v1/oauth/token", oReq, oResp)
IF (nSuccess == 0)
? oHttp:LastErrorText
oHttp:destroy()
oReq:destroy()
oResp:destroy()
RETURN
ENDIF
oSbResponseBody := CreateObject("Chilkat.StringBuilder")
oResp:GetBodySb(oSbResponseBody)
oJResp := CreateObject("Chilkat.JsonObject")
oJResp:LoadSb(oSbResponseBody)
oJResp:EmitCompact := 0
? "Response Body:"
? oJResp:Emit()
nRespStatusCode := oResp:StatusCode
? "Response Status Code = " + Str(nRespStatusCode)
IF (nRespStatusCode >= 400)
? "Response Header:"
? oResp:Header
? "Failed."
oHttp:destroy()
oReq:destroy()
oResp:destroy()
oSbResponseBody:destroy()
oJResp:destroy()
RETURN
ENDIF
// Save the OAuth2 access token for other examples to use.
oJResp:WriteFile("qa_data/tokens/ups_oauth2_token.json")
// If successful, the OAuth2 access token JSON looks like this:
// {
// "token_type": "Bearer",
// "issued_at": "1686911985606",
// "client_id": "2498righ8wr6aihe98rt8rhowirtyw9er6twe80rtywrehrt",
// "access_token": "eyJraW......R2sbqrY",
// "expires_in": "14399",
// "status": "approved"
// }
cToken_type := oJResp:StringOf("token_type")
cIssued_at := oJResp:StringOf("issued_at")
cClient_id := oJResp:StringOf("client_id")
cAccess_token := oJResp:StringOf("access_token")
cExpires_in := oJResp:StringOf("expires_in")
cStatus := oJResp:StringOf("status")
oHttp:destroy()
oReq:destroy()
oResp:destroy()
oSbResponseBody:destroy()
oJResp:destroy()