Friday, 27 October 2023

Google Pay

Introduction

Google Pay for the web is built on the Payment Request API, an open web standard candidate that relies on the customer's browser as a secure intermediary for payments.

What is Payment Request API

It is one part of Web Payments standard.

Web Payments is an emerging web standard being developed by the W3C to simplify online payments. Web Payments consist of the following web standards:

  • Payment Request API
  • Payment Handler API
  • Payment Method Identifiers
  • Payment Method Manifest
//sample code for Payment Request
const request = new PaymentRequest(paymentMethods, paymentDetails);
request.canMakePayment().then(result => {
  if (result) {
    // This browser supports the specified payment method.
  } else {
    // This browser does NOT support the specified payment method.
  }
}).catch(e => {
  // An exception
});

Standalone page to show Google Pay

Google Pay Tutorial

<html>
<head>
    <script async src="https://pay.google.com/gp/p/js/pay.js" onload="onGooglePayLoaded()"></script>
    <script>
        const tokenizationSpec = {
            type: 'PAYMENT_GATEWAY',
            parameters: {
                gateway: 'example',
                gatewayMerchantId: 'gatewayMerchantId'
            }
        };

        const cardPaymentMethod = {
            type: 'CARD',
            tokenizationSpecification: tokenizationSpec,
            parameters: {
                allowedCardNetworks: ['VISA', 'AMEX'],
                allowedAuthMethods:
                    ['PAN_ONLY', 'CRYPTOGRAM_3DS'],
                billingAddressRequired: true,
                billingAddressParameters: {
                    format: 'FULL',
                    phoneNumberRequired: true
                }
            }
        }

        function onGooglePayLoaded() {
            const googlePayClient = new google.payments.api.PaymentsClient({ environment: "TEST" });

            const clientConfiguration = {
                apiVersion: 2,
                apiVersionMinor: 0,
                allowedPaymentMethods: [cardPaymentMethod]
            };

            googlePayClient.isReadyToPay(clientConfiguration)
                .then(function (response) {
                    console.log(response)
                    if (response.result) {
                        //create button
                        let button = googlePayClient.createButton({
                            buttonColor: 'default',
                            buttonType: 'long',
                            onClick: handleSubmit
                        })

                        document.getElementById('gp').appendChild(button);
                    }
                }).catch(function (err) {
                });

            function handleSubmit() {
                const paymentDataRequest = Object.assign({}, clientConfiguration);
                paymentDataRequest.transactionInfo = {
                    totalPriceStatus: 'FINAL',
                    totalPrice: '123.45',
                    currencyCode: 'USD'
                }

                paymentDataRequest.merchantInfo = {
                    merchantId: '0123456789',
                    merchantName: 'Example Merchant'
                }

                googlePayClient.loadPaymentData(paymentDataRequest)
                    .then(function (paymentData) {
                        console.log("payment data:", paymentData)
                    })
            }
        }

        
    </script>
</head>

<body>
    <p>Try Google Pay</p>
    <p id="gp"></p>
</body>

</html>

Local development

  • if it is localhost, Google allows it to be http
  • let a gmail to joined into sandbox test group and do not need to provide card when click "Google Pay button"

Join sandbox test group

Thursday, 26 October 2023

JSON Web Tokens

JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties.

For JWT token, it consists of three parts:

  • header about alg and type
  • payload
  • signature

PHP codes to generate a JWT


    function createJWT($payload, $secret)
    {
        //this is alg used
        $header = ["typ" => "JWT", "alg" => "HS256"];

        $encodedHead = base64url_encode(json_encode($header));
        $encodedPayLoad = base64url_encode(json_encode($payload));

        //build the first two parts
        $encodedHeaderAndPayload = $encodedHead . '.' . $encodedPayLoad;

        $signature = base64url_encode(hash_hmac('sha256', $encodedHeaderAndPayload, $secret, true));

        //build token
        return $encodedHeaderAndPayload. '.' . $signature;
    }

    function base64url_encode($data)
    {
        return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
    }

Wednesday, 11 October 2023

Multiple UpSell

React Hook Form

React Hook Form Tutorial

//sample
const [books, dispatch] = useReducer(bookReducer, [])

useReducer Hook

The idea behind it is the same as reduc. Here is useReducer doc

React Context

Here is react context toturial

  • Provider needs to wrap a children when return a provider. Here children has a special meaning of children components
  • in App.js, components will be wrapped by context provider
  • In the component itself, it can access context in three ways
    • contextType
    • consumer
    • const {isLight, light} = useContext(ThemeContext)

In Context file, we need to export both context and context provider

  • export const AuthContext = createContext()
  • export default AuthConextProvider (This is a component with AuthContext.Provider)