npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

capacitor-gpay-plugin

v0.4.1

Published

Plugin for payment via GooglePay

Downloads

414

Readme

Capacitor плагин для реализации нативной оплаты через Google Pay

Поддерживаются платформы: Android, Web

Работу плагина можно посмотреть в демо-приложении

Оформление кнопки оплаты обязательно должно соответствовать правилам использования бренда.

Добавление плагина

  1. Установить плагин
npm i capacitor-gpay-plugin
  1. Добавить инициализацию плагина в <project>/android/app/src/main/java/<...>/MainActivity.java
// ...
import pro.sharks.capacitor.gpay.GPayNative;

public class MainActivity extends BridgeActivity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    this.init(savedInstanceState, new ArrayList<Class<? extends Plugin>>() {{
      
        // Инициализация плагина
        add(GPayNative.class);
    }});
  }
}
  1. В файл манифеста <project>/android/app/src/main/AndroidManifest.xml добавить мета параметр:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    ...>

    <application
        android:allowBackup="true"
        ...>

        <!-- Необходимо включить данный флаг, для использования PaymentsClient. -->
        <meta-data
            android:name="com.google.android.gms.wallet.api.enabled"
            android:value="true" />

Инициализация и оплата

Все передаваемые данные описаны на странице: Google Pay (web tutorial).

import 'capacitor-gpay-plugin' // for web support
import { GPayNativePlugin } from 'capacitor-gpay-plugin'

const GPayNative = Plugins.GPayNative as GPayNativePlugin;
import {
    BaseRequestData,
    PaymentDataRequest,
    PaymentMethod,
    TokenizationSpecificationPaymentGateway,
    PaymentMethodCard,
    AuthMethod,
    CardNetwork,
    PaymentData,
} from 'capacitor-gpay-plugin'

const baseRequest: BaseRequestData = {
  apiVersion: 2,
  apiVersionMinor: 0
};

const tokenizationSpecification: TokenizationSpecificationPaymentGateway = {
    type: 'PAYMENT_GATEWAY',
    parameters: {
        gateway: 'example',
        gatewayMerchantId: 'exampleGatewayMerchantId',
    }
};

const baseCardPaymentMethod: PaymentMethodCard = {
    type: 'CARD',
    parameters: {
        allowedAuthMethods: ["PAN_ONLY", "CRYPTOGRAM_3DS"] as AuthMethod[],
        allowedCardNetworks: ["AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA"] as CardNetwork[],
    }
};

const cardPaymentMethod: PaymentMethod = {
    tokenizationSpecification,
    ...baseCardPaymentMethod,
};

/**
 * Создание объекта типа PaymentsClient, test - означает, что environment будет установлен в TEST
 * В случае WEB: будет загружен скрипт Google Pay Web Api
 */
await GPayNative.createClient({ test: true });

/* Получение информации о готовности к платежу */
const isReadyToPayRequest = {
    ...baseRequest,
    allowedPaymentMethods: [baseCardPaymentMethod],
};
const { isReady } = await GPayNative.isReadyToPay(isReadyToPayRequest);

/* Проведение оплаты */
const paymentDataRequest: PaymentDataRequest = {
    ...baseRequest,
    allowedPaymentMethods: [cardPaymentMethod],
    transactionInfo: {
        totalPriceStatus: 'FINAL',
        totalPrice: "12.34", // Итоговая стоимость
        currencyCode: 'USD',
        countryCode: 'US',
        checkoutOption: 'COMPLETE_IMMEDIATE_PURCHASE',
    },
    merchantInfo: {
        merchantName: 'Example Merchant',
        // merchantId: 'TEST',
    },
};

try {
    const paymentData = await GPayNative.loadPaymentData(paymentDataRequest);
    const token = paymentData.paymentMethodData.tokenizationData.token;

    // Отправка токена в процессинговый центр через ваш бэкенд...
} catch (e) {
    if (e.message === 'canceled') {
        // Пользователь закрыл окно оплаты
    } else {
        // Возникла ошибка e.message
    }
}

События

GPayNative.addListener('success', (paymentData: PaymentData) => {
    const token = paymentData.paymentMethodData.tokenizationData.token;

    // ...
});

GPayNative.addListener('canceled', () => {
    // Пользователь закрыл окно оплаты
});

GPayNative.addListener('error', err => {
    // Если err.code === -1, то это значит что при проведении оплаты был
    // получен успешный ответ, но paymentData не удалось преобразовать

    console.error(err.message);
});