Code for Oauth 2.0
Stay organized with collections
Save and categorize content based on your preferences.
All requests to Google Pay APIs must be authorized by an authenticated user. Your
application must include the following code to authorize the Omnichannel API.
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.common.io.CharStreams;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.util.Collections;
public class OauthClient {
private static final String JWT_PATH = "service-account-key.json";
private static final String API_SCOPE = "https://www.googleapis.com/auth/nbupaymentsmerchants";
private static final String POST_JSON = "initiate.json";
private static final String API_URL =
"https://nbupayments.googleapis.com/v1/merchantPayments:initiate";
public static final Charset UTF8 = Charset.forName("UTF-8");
public static final int HTTP_TIMEOUT_MS = 10000;
public static void main(String args[]) {
HttpTransport httpTransport;
HttpRequestFactory httpRequestFactory;
try {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredential credential = getGoogleCredential(httpTransport);
httpRequestFactory = httpTransport.createRequestFactory(credential);
doPostApplication(httpRequestFactory);
} catch (IOException | GeneralSecurityException e) {
System.out.println("Error in posting data.");
}
}
/** Creates a {@link HttpContent} from the json file. */
private static HttpContent getContent() {
return new FileContent("application/json", new File(POST_JSON));
}
/** Creates a new credential using the service account json file and Oauth scope. */
private static GoogleCredential getGoogleCredential(HttpTransport httpTransport)
throws FileNotFoundException, IOException {
return GoogleCredential.fromStream(
new FileInputStream(new File(JWT_PATH)),
httpTransport,
JacksonFactory.getDefaultInstance())
.createScoped(Collections.singleton(API_SCOPE));
}
/** Gets the specification of an application from the Google servers. */
private static void doPostApplication(HttpRequestFactory requestFactory) throws IOException {
GenericUrl url = new GenericUrl(API_URL);
HttpRequest httpRequest = requestFactory.buildPostRequest(url, getContent());
doHttpRequest(httpRequest);
}
/** Executes HTTP request against the API and prints response. */
private static void doHttpRequest(HttpRequest httpRequest) throws IOException {
// Set read timeout.
httpRequest.setReadTimeout(HTTP_TIMEOUT_MS).setThrowExceptionOnExecuteError(false);
HttpResponse httpResponse = httpRequest.execute();
System.out.println("Status code: " + httpResponse.getStatusCode());
String responseContent = inputStreamToString(httpResponse.getContent());
// Parse and print formatted response.
JsonObject response = new JsonParser().parse(responseContent).getAsJsonObject();
System.out.println("response: " + response);
}
/** Reads input stream contents using the UTF-8 charset into a string. */
private static String inputStreamToString(InputStream in) throws IOException {
return CharStreams.toString(new InputStreamReader(in, UTF8));
}
}
Maven dependencies
To make your code work, you must add the following Maven dependencies while
building the app.
<dependencies>
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>1.22.0</version>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client</artifactId>
<version>1.22.0</version>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-jackson</artifactId>
<version>1.22.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>
</dependencies>
Oauth 2.0 References
Google API client libraries - Java
https://developers.google.com/identity/protocols/OAuth2#serviceaccount
https://developers.google.com/identity/protocols/OAuth2ServiceAccount
The following client libraries integrate with popular frameworks, which makes
implementing OAuth 2.0 simpler.
- Google-api-client
- Google-http-java-client
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2024-10-16 UTC.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2024-10-16 UTC."],[[["\u003cp\u003eAll requests to Google Pay's Omnichannel API must be authorized using OAuth 2.0 with a service account.\u003c/p\u003e\n"],["\u003cp\u003eThe provided Java code demonstrates how to authorize requests using a service account key file and make API calls.\u003c/p\u003e\n"],["\u003cp\u003eTo use the code, you need to add specific Maven dependencies for Google API Client, HTTP Client, and Gson libraries.\u003c/p\u003e\n"],["\u003cp\u003eFurther information on OAuth 2.0 and Google API client libraries is available through provided links.\u003c/p\u003e\n"]]],["The provided code authorizes the Google Pay Omnichannel API by using a service account key file (`service-account-key.json`) and a defined OAuth scope. It initializes an HTTP transport and creates Google credentials. It then posts an application defined in `initiate.json` to the API endpoint, specified as `https://nbupayments.googleapis.com/v1/merchantPayments:initiate`, using a POST request. The response is then processed and the status code is displayed. Maven dependencies for Google API client and JSON processing are also detailed.\n"],null,["All requests to Google Pay APIs must be authorized by an authenticated user. Your\napplication must include the following code to authorize the Omnichannel API. \n\n import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;\n import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;\n import com.google.api.client.http.FileContent;\n import com.google.api.client.http.GenericUrl;\n import com.google.api.client.http.HttpContent;\n import com.google.api.client.http.HttpRequest;\n import com.google.api.client.http.HttpRequestFactory;\n import com.google.api.client.http.HttpResponse;\n import com.google.api.client.http.HttpTransport;\n import com.google.api.client.json.jackson2.JacksonFactory;\n import com.google.common.io.CharStreams;\n import com.google.gson.JsonObject;\n import com.google.gson.JsonParser;\n\n import java.io.File;\n import java.io.FileInputStream;\n import java.io.FileNotFoundException;\n import java.io.IOException;\n import java.io.InputStream;\n import java.io.InputStreamReader;\n import java.nio.charset.Charset;\n import java.security.GeneralSecurityException;\n import java.util.Collections;\n\n public class OauthClient {\n private static final String JWT_PATH = \"service-account-key.json\";\n private static final String API_SCOPE = \"https://www.googleapis.com/auth/nbupaymentsmerchants\";\n private static final String POST_JSON = \"initiate.json\";\n private static final String API_URL = \n \"https://nbupayments.googleapis.com/v1/merchantPayments:initiate\";\n public static final Charset UTF8 = Charset.forName(\"UTF-8\");\n public static final int HTTP_TIMEOUT_MS = 10000;\n\n public static void main(String args[]) {\n HttpTransport httpTransport;\n HttpRequestFactory httpRequestFactory;\n try {\n httpTransport = GoogleNetHttpTransport.newTrustedTransport();\n GoogleCredential credential = getGoogleCredential(httpTransport);\n httpRequestFactory = httpTransport.createRequestFactory(credential);\n\n doPostApplication(httpRequestFactory);\n } catch (IOException | GeneralSecurityException e) {\n System.out.println(\"Error in posting data.\");\n }\n }\n\n /** Creates a {@link HttpContent} from the json file. */\n private static HttpContent getContent() {\n return new FileContent(\"application/json\", new File(POST_JSON));\n }\n\n /** Creates a new credential using the service account json file and Oauth scope. */\n private static GoogleCredential getGoogleCredential(HttpTransport httpTransport)\n throws FileNotFoundException, IOException {\n return GoogleCredential.fromStream(\n new FileInputStream(new File(JWT_PATH)),\n httpTransport,\n JacksonFactory.getDefaultInstance())\n .createScoped(Collections.singleton(API_SCOPE));\n }\n\n /** Gets the specification of an application from the Google servers. */\n private static void doPostApplication(HttpRequestFactory requestFactory) throws IOException {\n GenericUrl url = new GenericUrl(API_URL);\n HttpRequest httpRequest = requestFactory.buildPostRequest(url, getContent());\n doHttpRequest(httpRequest);\n }\n\n /** Executes HTTP request against the API and prints response. */\n private static void doHttpRequest(HttpRequest httpRequest) throws IOException {\n // Set read timeout.\n httpRequest.setReadTimeout(HTTP_TIMEOUT_MS).setThrowExceptionOnExecuteError(false);\n HttpResponse httpResponse = httpRequest.execute();\n System.out.println(\"Status code: \" + httpResponse.getStatusCode());\n String responseContent = inputStreamToString(httpResponse.getContent());\n\n // Parse and print formatted response.\n JsonObject response = new JsonParser().parse(responseContent).getAsJsonObject();\n System.out.println(\"response: \" + response);\n }\n\n /** Reads input stream contents using the UTF-8 charset into a string. */\n private static String inputStreamToString(InputStream in) throws IOException {\n return CharStreams.toString(new InputStreamReader(in, UTF8));\n }\n }\n\nMaven dependencies\n\nTo make your code work, you must add the following Maven dependencies while\nbuilding the app. \n\n \u003cdependencies\u003e\n \u003cdependency\u003e\n \u003cgroupId\u003ecom.google.api-client\u003c/groupId\u003e\n \u003cartifactId\u003egoogle-api-client\u003c/artifactId\u003e\n \u003cversion\u003e1.22.0\u003c/version\u003e\n \u003c/dependency\u003e\n \u003cdependency\u003e\n \u003cgroupId\u003ecom.google.http-client\u003c/groupId\u003e\n \u003cartifactId\u003egoogle-http-client\u003c/artifactId\u003e\n \u003cversion\u003e1.22.0\u003c/version\u003e\n \u003c/dependency\u003e\n \u003cdependency\u003e\n \u003cgroupId\u003ecom.google.http-client\u003c/groupId\u003e\n \u003cartifactId\u003egoogle-http-client-jackson\u003c/artifactId\u003e\n \u003cversion\u003e1.22.0\u003c/version\u003e\n \u003c/dependency\u003e\n \u003cdependency\u003e\n \u003cgroupId\u003ecom.google.code.gson\u003c/groupId\u003e\n \u003cartifactId\u003egson\u003c/artifactId\u003e\n \u003cversion\u003e2.8.0\u003c/version\u003e\n \u003c/dependency\u003e\n \u003c/dependencies\u003e\n\nOauth 2.0 References\n\n- [Google API client libraries - Java](https://developers.google.com/api-client-library/java/google-api-java-client/oauth2)\n\n- https://developers.google.com/identity/protocols/OAuth2#serviceaccount\n\n- https://developers.google.com/identity/protocols/OAuth2ServiceAccount\n\nThe following client libraries integrate with popular frameworks, which makes\nimplementing OAuth 2.0 simpler.\n\n- Google-api-client\n- Google-http-java-client"]]