Google Pay API PaymentRequest 가이드
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
Google Pay API는 PaymentRequest
의 지원되는 다른 결제 수단과 함께 사용할 수 있습니다.
1단계: PaymentDataRequest 객체 만들기
결제 게이트웨이 및 허용된 결제 수단을 지정하여 PaymentDataRequest
객체를 구성합니다.
결제 수단 간의 일관성을 위해 Google Pay API가 아닌 브라우저의 PaymentRequest
options
인수를 통해 배송지 주소, 이메일 주소, 전화번호를 얻는 것이 좋습니다.
결제 사용자 인증 정보와 청구서 수신 주소(선택사항) 수신에만 Google Pay API를 사용합니다.
const googlePaymentDataRequest = {
environment: 'TEST',
apiVersion: 2,
apiVersionMinor: 0,
merchantInfo: {
// A merchant ID is available after approval by Google.
// @see {@link https://developers.google.com/pay/api/web/guides/test-and-deploy/integration-checklist}
// merchantId: '12345678901234567890',
merchantName: 'Example Merchant'
},
allowedPaymentMethods: [{
type: 'CARD',
parameters: {
allowedAuthMethods: ["PAN_ONLY", "CRYPTOGRAM_3DS"],
allowedCardNetworks: ["AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA"]
},
tokenizationSpecification: {
type: 'PAYMENT_GATEWAY',
// Check with your payment gateway on the parameters to pass.
// @see {@link https://developers.google.com/pay/api/web/reference/request-objects#gateway}
parameters: {
'gateway': 'example',
'gatewayMerchantId': 'exampleGatewayMerchantId'
}
}
}]
};
2단계: Google Pay API 지원 선언
Google Pay API의 결제 수단 식별자와 구성을 PaymentRequest
에 전달된 methodData
매개변수에 추가합니다.
const methodData = [
{supportedMethods: 'https://google.com/pay', data: googlePaymentDataRequest},
{supportedMethods: 'basic-card'}
];
총정리
다음 예시에서는 PaymentRequest
에서 지원되는 다른 결제 수단과 Google Pay API를 함께 구현하는 방법을 보여줍니다.
<div id="checkout">
<button id="buyButton">Checkout</button>
</div>
<script>
const allowedCardNetworks = ["AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA"];
const allowedCardAuthMethods = ["PAN_ONLY", "CRYPTOGRAM_3DS"];
if (window.PaymentRequest) {
const request = createPaymentRequest();
request.canMakePayment()
.then(function(result) {
if (result) {
// Display PaymentRequest dialog on interaction with the existing checkout button
document.getElementById('buyButton')
.addEventListener('click', onBuyClicked);
}
})
.catch(function(err) {
showErrorForDebugging(
'canMakePayment() error! ' + err.name + ' error: ' + err.message);
});
} else {
showErrorForDebugging('PaymentRequest API not available.');
}
/**
* Show a PaymentRequest dialog after a user clicks the checkout button
*/
function onBuyClicked() {
createPaymentRequest()
.show()
.then(function(response) {
// Dismiss payment dialog.
response.complete('success');
handlePaymentResponse(response);
})
.catch(function(err) {
showErrorForDebugging(
'show() error! ' + err.name + ' error: ' + err.message);
});
}
/**
* Define your unique Google Pay API configuration
*
* @returns {object} data attribute suitable for PaymentMethodData
*/
function getGooglePaymentsConfiguration() {
return {
environment: 'TEST',
apiVersion: 2,
apiVersionMinor: 0,
merchantInfo: {
// A merchant ID is available after approval by Google.
// 'merchantId':'12345678901234567890',
merchantName: 'Example Merchant'
},
allowedPaymentMethods: [{
type: 'CARD',
parameters: {
allowedAuthMethods: allowedCardAuthMethods,
allowedCardNetworks: allowedCardNetworks
},
tokenizationSpecification: {
type: 'PAYMENT_GATEWAY',
// Check with your payment gateway on the parameters to pass.
// @see {@link https://developers.google.com/pay/api/web/reference/request-objects#gateway}
parameters: {
'gateway': 'example',
'gatewayMerchantId': 'exampleGatewayMerchantId'
}
}
}]
};
}
/**
* Create a PaymentRequest
*
* @returns {PaymentRequest}
*/
function createPaymentRequest() {
// Add support for the Google Pay API.
const methodData = [{
supportedMethods: 'https://google.com/pay',
data: getGooglePaymentsConfiguration()
}];
// Add other supported payment methods.
methodData.push({
supportedMethods: 'basic-card',
data: {
supportedNetworks:
Array.from(allowedCardNetworks, (network) => network.toLowerCase())
}
});
const details = {
total: {label: 'Test Purchase', amount: {currency: 'USD', value: '1.00'}}
};
const options = {
requestPayerEmail: true,
requestPayerName: true
};
return new PaymentRequest(methodData, details, options);
}
/**
* Process a PaymentResponse
*
* @param {PaymentResponse} response returned when a user approves the payment request
*/
function handlePaymentResponse(response) {
const formattedResponse = document.createElement('pre');
formattedResponse.appendChild(
document.createTextNode(JSON.stringify(response.toJSON(), null, 2)));
document.getElementById('checkout')
.insertAdjacentElement('afterend', formattedResponse);
}
/**
* Display an error message for debugging
*
* @param {string} text message to display
*/
function showErrorForDebugging(text) {
const errorDisplay = document.createElement('code');
errorDisplay.style.color = 'red';
errorDisplay.appendChild(document.createTextNode(text));
const p = document.createElement('p');
p.appendChild(errorDisplay);
document.getElementById('checkout').insertAdjacentElement('afterend', p);
}
</script>
결제 수단 매개변수 목록
PaymentRequest
에 전달된 Google Pay API 구성은 다음 예외를 제외하고는 Google Pay API 자바스크립트 클라이언트 라이브러리에서 사용하는 PaymentDataRequest
객체와 비슷합니다.
PaymentOptions
에 설명된 문자열 값과 일치하는 객체에 environment
속성을 설정해야 합니다.
transactionInfo
속성은 생략해야 합니다. 총 가격과 통화는 PaymentRequest
에 전달된 details
인수에 지정해야 합니다.
다음은 PaymentRequest
결제 수단 데이터 속성에서 Google Pay API 결제 수단에 지정된 추가 객체 속성입니다.
속성 |
유형 |
필요성 |
설명 |
environment |
문자열 |
선택사항 |
PRODUCTION : 도메인에 대해 유효한 Google 판매자 ID가 지정되고 구성되면 청구 가능한 결제 수단을 반환합니다.
TEST : 테스트에 적합하게 반환된 더미 결제 수단(기본값)입니다.
|
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 Oracle 계열사의 등록 상표입니다.
최종 업데이트: 2024-10-16(UTC)
[null,null,["최종 업데이트: 2024-10-16(UTC)"],[[["\u003cp\u003eGoogle Pay can be integrated with other payment methods using the Payment Request API, primarily supported by Chrome.\u003c/p\u003e\n"],["\u003cp\u003eTo ensure wider compatibility, use the Google Pay API JavaScript client library with a branded Google Pay button.\u003c/p\u003e\n"],["\u003cp\u003eImplementing Google Pay involves creating a PaymentDataRequest object to specify payment details and configuring the Payment Request API to include Google Pay as a supported method.\u003c/p\u003e\n"],["\u003cp\u003eThe Google Pay API configuration in Payment Request is similar to the PaymentDataRequest object in the Google Pay API JavaScript library, with minor differences in environment and transaction information handling.\u003c/p\u003e\n"]]],["This guide outlines using the Google Pay API within the `PaymentRequest` API. Key actions include: creating a `PaymentDataRequest` object to define payment gateway and accepted methods, such as card types and authentication methods. Add Google Pay's identifier and configuration to the `methodData` parameter for `PaymentRequest`. This configuration involves setting environment (e.g., 'TEST'), API versions, and merchant information. Shipping details should be requested through `PaymentRequest` options. Configure `environment` and use the `details` argument for pricing.\n"],null,["# Google Pay API PaymentRequest Tutorial\n\nThe Google Pay API can be used in conjunction with other supported\npayment methods in\n[`PaymentRequest`](https://developer.mozilla.org/en-US/docs/Web/API/PaymentRequest \"MDN: PaymentRequest documentation\").\n| **Important:** Chrome is currently the only web browser supporting the Payment Request API with third-party payment methods, including Google Pay. Sites wishing to implement Google Pay as a standalone payment method should use the [Google Pay API JavaScript client library](/pay/api/web/guides/tutorial) with a [branded Google Pay button](/pay/api/web/guides/brand-guidelines) to reach a broader Google audience across multiple browsers and platforms.\n\nStep 1: Create a PaymentDataRequest object\n------------------------------------------\n\nConfigure a\n[`PaymentDataRequest`](/pay/api/web/reference/request-objects#PaymentDataRequest)\nobject specifying your payment gateway and accepted methods of payment.\nWe recommend you obtain shipping address, email address, and phone number\nthrough the browser's `PaymentRequest` `options` argument,\nnot the Google Pay API, for consistency across payment methods.\nUse the Google Pay API to receive only the payment credentials and\noptional billing address. \n\n```javascript\nconst googlePaymentDataRequest = {\n environment: 'TEST',\n apiVersion: 2,\n apiVersionMinor: 0,\n merchantInfo: {\n // A merchant ID is available after approval by Google.\n // @see {@link https://developers.google.com/pay/api/web/guides/test-and-deploy/integration-checklist}\n // merchantId: '12345678901234567890',\n merchantName: 'Example Merchant'\n },\n allowedPaymentMethods: [{\n type: 'CARD',\n parameters: {\n allowedAuthMethods: [\"PAN_ONLY\", \"CRYPTOGRAM_3DS\"],\n allowedCardNetworks: [\"AMEX\", \"DISCOVER\", \"INTERAC\", \"JCB\", \"MASTERCARD\", \"VISA\"]\n },\n tokenizationSpecification: {\n type: 'PAYMENT_GATEWAY',\n // Check with your payment gateway on the parameters to pass.\n // @see {@link https://developers.google.com/pay/api/web/reference/request-objects#gateway}\n parameters: {\n 'gateway': 'example',\n 'gatewayMerchantId': 'exampleGatewayMerchantId'\n }\n }\n }]\n};\n```\n\nStep 2: Declare Google Pay API support\n--------------------------------------\n\nAdd the Google Pay API payment method identifier and its configuration to\nthe `methodData` parameter passed to `PaymentRequest`. \n\n```javascript\nconst methodData = [\n {supportedMethods: 'https://google.com/pay', data: googlePaymentDataRequest}\n];\n```\n\nPutting it all together\n-----------------------\n\nThe following example shows an implementation of the Google Pay API with\nother supported payment methods in `PaymentRequest`: \n\n```html\n\u003cdiv id=\"checkout\"\u003e\n \u003cbutton id=\"buyButton\"\u003eCheckout\u003c/button\u003e\n\u003c/div\u003e\n\n\u003cscript\u003e\nconst allowedCardNetworks = [\"AMEX\", \"DISCOVER\", \"INTERAC\", \"JCB\", \"MASTERCARD\", \"VISA\"];\nconst allowedCardAuthMethods = [\"PAN_ONLY\", \"CRYPTOGRAM_3DS\"];\nif (window.PaymentRequest) {\n const request = createPaymentRequest();\n\n request.canMakePayment()\n .then(function(result) {\n if (result) {\n // Display PaymentRequest dialog on interaction with the existing checkout button\n document.getElementById('buyButton')\n .addEventListener('click', onBuyClicked);\n }\n })\n .catch(function(err) {\n showErrorForDebugging(\n 'canMakePayment() error! ' + err.name + ' error: ' + err.message);\n });\n} else {\n showErrorForDebugging('PaymentRequest API not available.');\n}\n\n/**\n * Show a PaymentRequest dialog after a user clicks the checkout button\n */\nfunction onBuyClicked() {\n createPaymentRequest()\n .show()\n .then(function(response) {\n // Dismiss payment dialog.\n response.complete('success');\n handlePaymentResponse(response);\n })\n .catch(function(err) {\n showErrorForDebugging(\n 'show() error! ' + err.name + ' error: ' + err.message);\n });\n}\n\n/**\n * Define your unique Google Pay API configuration\n *\n * @returns {object} data attribute suitable for PaymentMethodData\n */\nfunction getGooglePaymentsConfiguration() {\n return {\n environment: 'TEST',\n apiVersion: 2,\n apiVersionMinor: 0,\n merchantInfo: {\n // A merchant ID is available after approval by Google.\n // 'merchantId':'12345678901234567890',\n merchantName: 'Example Merchant'\n },\n allowedPaymentMethods: [{\n type: 'CARD',\n parameters: {\n allowedAuthMethods: allowedCardAuthMethods,\n allowedCardNetworks: allowedCardNetworks\n },\n tokenizationSpecification: {\n type: 'PAYMENT_GATEWAY',\n // Check with your payment gateway on the parameters to pass.\n // @see {@link https://developers.google.com/pay/api/web/reference/request-objects#gateway}\n parameters: {\n 'gateway': 'example',\n 'gatewayMerchantId': 'exampleGatewayMerchantId'\n }\n }\n }]\n };\n}\n\n/**\n * Create a PaymentRequest\n *\n * @returns {PaymentRequest}\n */\nfunction createPaymentRequest() {\n // Add support for the Google Pay API.\n const methodData = [{\n supportedMethods: 'https://google.com/pay',\n data: getGooglePaymentsConfiguration()\n }];\n\n const details = {\n total: {label: 'Test Purchase', amount: {currency: 'USD', value: '1.00'}}\n };\n\n const options = {\n requestPayerEmail: true,\n requestPayerName: true\n };\n\n return new PaymentRequest(methodData, details, options);\n}\n\n/**\n * Process a PaymentResponse\n *\n * @param {PaymentResponse} response returned when a user approves the payment request\n */\nfunction handlePaymentResponse(response) {\n const formattedResponse = document.createElement('pre');\n formattedResponse.appendChild(\n document.createTextNode(JSON.stringify(response.toJSON(), null, 2)));\n document.getElementById('checkout')\n .insertAdjacentElement('afterend', formattedResponse);\n}\n\n/**\n * Display an error message for debugging\n *\n * @param {string} text message to display\n */\nfunction showErrorForDebugging(text) {\n const errorDisplay = document.createElement('code');\n errorDisplay.style.color = 'red';\n errorDisplay.appendChild(document.createTextNode(text));\n const p = document.createElement('p');\n p.appendChild(errorDisplay);\n document.getElementById('checkout').insertAdjacentElement('afterend', p);\n}\n\u003c/script\u003e\n```\n\nPayment method parameter list\n-----------------------------\n\nThe Google Pay API configuration passed in `PaymentRequest` is similar to the\n[`PaymentDataRequest`](/pay/api/web/reference/request-objects#PaymentDataRequest)\nobject used by the Google Pay API JavaScript client library with a few exceptions:\n\n- An `environment` property should be set on the object matching a string value described in [`PaymentOptions`](/pay/api/web/reference/request-objects#PaymentOptions)\n- The `transactionInfo` property should be omitted. Total price and currency should instead be specified in the `details` argument passed to `PaymentRequest`\n\nAdditional object properties specified for the Google Pay API payment method in a `PaymentRequest` payment method data property:\n\n| Property | Type | Necessity | Description |\n|---------------|--------|-----------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| `environment` | string | optional | - `PRODUCTION`: return chargeable methods of payment when a valid Google merchant ID is specified and configured for the domain - `TEST`: dummy payment methods returned suitable for testing (default) |"]]