GooglePay web 可動するサンプル


# web版のgooglepayを試すコード



<img width="307" alt="スクリーンショット 2020-01-20 23.13.14.png" src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1088/74f79998-fdde-24ce-ebcf-47461fa13a0e.png">


### JavaScript
```javascript

<!doctype html>
<html class="no-js" lang="">

    <head>
        <meta charset="utf-8">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

    </head>

    <body>

        <p>GooglePay</p>

        <div id="container"></div>
    </body>

</html>

<script>
    /**
    *
     * 可動！するサンプル
     * GooglePayment.jsが読み込まれた後に実行される処理
     *
     */
    function onGooglePayLoaded() {
        const googlePayClient = new google.payments.api.PaymentsClient({environment: 'TEST'});
        const allowedCardAuthMethods = ["PAN_ONLY", "CRYPTOGRAM_3DS"];
        const allowedCardNetworks = ["AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA"];

        /**
         *
         * @type {{type: string, parameters: {gatewayMerchantId: string, gateway: string}}}
         */
        const tokenizationSpec = {
            type: 'PAYMENT_GATEWAY',
            parameters: {
                gateway: 'example',
                gatewayMerchantId: 'gatewayMerchantId'
            }
        };

        /**
         *
         * @type {{apiVersionMinor: number, apiVersion: number, allowedPaymentMethods: [{type: string, parameters: {allowedAuthMethods: [string, string], allowedCardNetworks},
                      tokenizationSpecification: {type: string, parameters: {gatewayMerchantId: string, gateway: string}}}]}}
         */
        const baseClientConfigurateion = {
            apiVersion: 2,
            apiVersionMinor: 0,
            allowedPaymentMethods: [
                {
                    type: "CARD",
                    tokenizationSpecification: tokenizationSpec,
                    parameters: {
                        allowedAuthMethods: ["PAN_ONLY", "CRYPTOGRAM_3DS"],
                        allowedCardNetworks: ["AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA"]
                    }
                }
            ]
        };

        /**
         *
         * @type {{type: string, parameters: {allowedAuthMethods: [string, string], billingAddressRequired: boolean, billingAddressParameters: {format: string, phoneNumberRequired:
                      boolean}, allowedCardNetworks: string[]}}}
         */
        const cardPaymentMethod = {
            type: 'CARD',
            tokenizationSpecification: tokenizationSpec,
            parameters: {
                allowedCardNetworks: allowedCardNetworks,
                allowedAuthMethods: allowedCardAuthMethods,
                billingAddressRequired: false,
                billingAddressParameters: {
                    format: 'FULL',
                    phoneNumberRequired: true
                }
            }
        };

        const paymentDataRequest = Object.assign({}, baseClientConfigurateion);



        /**
         *
         *
         * @type {{totalPrice: string, totalPriceStatus: string, currencyCode: string}}
         */
        paymentDataRequest.transactionInfo = {
            totalPriceStatus: 'FINAL',
            totalPrice: '10',
            currencyCode: 'JPY',
        };

        /**
         *
         *  正式に審査が終わった後のmerchantIDが必要
         * @type {{merchantId: string, merchantName: string}}
         *
         */
        paymentDataRequest.merchantInfo = {
            merchantId: '01234567890123456789',
            merchantName: 'Example Merchant'
        };



        /**
         *
         */
        googlePayClient.isReadyToPay({
            allowedPaymentMethods: ["CARD"]
        }).then((response) => {
            if (response.result) {
                console.log('Payment結果', response.result);
                button = googlePayClient.createButton({
                    buttonColor: 'default',
                    buttonType: 'long',
                    onClick: onGooglePaymentsBjuttonClicked
                });
                document.getElementById('container').appendChild(button);

            }
        }).catch(function (err) {
            console.log('TEST1', err);
        });


        /**
         *
         */
        function onGooglePaymentsBjuttonClicked() {
            console.log('!')
            /**
             *
             */
            googlePayClient.loadPaymentData(paymentDataRequest).then((paymentData) => {
                googlePayClient.prefetchPaymentData(paymentDataRequest);

                paymentToken = paymentData.paymentMethodData.tokenizationData.token;
                console.log("paymenttoken:", paymentToken);
                console.log("paymentdata:", paymentData)
                //return new Promise(function(resolve, reject){ })
                  
                processPayment(paymentData)
            });
        }
    }

    /**
     * Process payment data returned by the Google Pay API
     *
     * @param {object} paymentData response from Google Pay API after user approves payment
     * @see {@link https://developers.google.com/pay/api/web/reference/object#PaymentData|PaymentData object reference}
     */
    function processPayment(paymentData) {
        // show returned data in developer console for debugging
        console.log(paymentData);
        // @todo pass payment token to your gateway to process payment
        paymentToken = paymentData.paymentMethodData.tokenizationData.token;
    }
</script>

<script async src="https://pay.google.com/gp/p/js/pay.js" onload="onGooglePayLoaded()"></script>

```



#### TEST実行画面

![スクリーンショット_2020-01-17_18_24_23.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1088/fd59b7fb-958b-7dd7-2a3e-208356c5e978.png)





### 参考にしたページ
GooglePay
https://developers.google.com/pay/api/web/reference/object?hl=ja#PaymentMethod
https://developer.android.com/google/play/billing/billing_testing?hl=ja
https://developers.google.com/pay/api/web/reference/object?hl=ja
https://developers.google.com/pay/api/web/guides/resources/update-to-latest-version
https://developers.google.com/pay/api/web/reference/client
https://developers.google.com/pay/api/web/reference/object#CardParameters