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 🙏

© 2026 – Pkg Stats / Ryan Hefner

choco-one-click-payment

v1.0.16

Published

Встраиваемый виджет для быстрой оплаты с bottom sheet интерфейсом

Downloads

1,668

Readme

Choco One-Click Widget

Встраиваемый виджет для быстрой оплаты с bottom sheet интерфейсом.

Установка

npm i choco-one-click-payment

Использование

ESM:

import ChocoOneClickWidget from 'choco-one-click-payment';

const widget = new ChocoOneClickWidget({
  clientId: '12345678',
  trackId: 'your-track-id',
  terminalId: 1234,
  amount: 10000,
  environment: 'stage',
  onSuccess: (data) => console.log('Success', data),
  onError: (error) => console.error('Error', error),
  onCancel: () => console.log('Cancelled'),
  onConfirmPay: () => console.log('payment button was pressed')
});

await widget.init();

Инициализация без trackId (способ оплаты будет заблокирован до вызова updateTrackId):

const widget = new ChocoOneClickWidget({
  clientId: '12345678',
  terminalId: 1234,
  amount: 10000,
  environment: 'stage',
  onSuccess: (data) => console.log('Success', data),
  onError: (error) => console.error('Error', error),
});

await widget.init();

// Когда trackId станет известен
await widget.updateTrackId('your-track-id');

CommonJS:

const ChocoOneClickWidget = require('choco-one-click-payment');

Поведение init()

  • clientId обязателен. Без него вызывается onError и init() возвращает false.
  • Запрос на контекст оплаты (context) не отправляется, если нет ни trackId, ни accessToken (из cookie). В этом случае показывается виджет с заблокированным выбором способа оплаты; кнопка «Оплатить» активна.
  • Если есть trackId или accessToken — запрашиваются токены (при необходимости) и context, подключается WebSocket, отображается полный виджет.

Параметры конфигурации

| Параметр | Тип | Обязательный | Описание | |----------|-----|--------------|----------| | clientId | string | да | OAuth2 client_id приложения | | trackId | string | нет | Идентификатор для получения access token | | terminalId | number | да | ID терминала Choco | | amount | number | да | Сумма в тиынах (1₸ = 100 тиынов) | | merchantOrderId | string | нет | Уникальный ID заказа в вашей системе | | currency | string | нет | Код валюты (по умолчанию KZT) | | environment | 'production' | 'stage' | нет | Окружение API (по умолчанию production) | | backlink | string | нет | URL для возврата после оплаты (Kaspi Pay, 3DS) | | locale | string | нет | Язык: ru, en, kk (по умолчанию ru) | | preorderId | number | нет | Preorder ID | | color | string | нет | Акцентный цвет (по умолчанию #2F2F2F) | | onlyKaspiAvailable | boolean | нет | Только Kaspi в списке способов оплаты | | disableKaspi | boolean | нет | Скрыть Kaspi среди способов оплаты | | bonuses | { amount: number, percent: number } | нет | Бонусы для ЗПЛ |

Callbacks

| Параметр | Описание | |----------|----------| | onSuccess | Вызывается при успешной оплате | | onError | Вызывается при ошибке | | onCancel | Вызывается при отмене/закрытии | | onConfirmPay | Callback перед оплатой; для подтверждения вызовите widget.pay() | | onAppliedBonus | Вызывается при включении/выключении бонусов |

Методы

| Метод | Описание | |-------|----------| | init() | Инициализация виджета. Возвращает Promise<boolean>. | | destroy() | Уничтожает виджет (WebSocket, DOM). | | close() | Закрывает виджет и вызывает onCancel. | | openPaymentSheet() | Открывает bottom sheet выбора способа оплаты. | | closePaymentSheet() | Закрывает bottom sheet. | | updateAmount(amount) | Обновляет сумму (в тиынах) и текст кнопки. | | updateLocale(locale) | Меняет язык интерфейса. | | updateTrackId(trackId) | Обновляет trackId, запрашивает токены и context, перерисовывает виджет. Возвращает Promise<boolean>. | | setLoading(boolean) | Включает/выключает состояние загрузки. | | setDisabled(boolean) | Блокирует/разблокирует интеракции. | | setPreorderId(preorderId) | Обновляет preorderId в рантайме. | | setMerchantOrderId(merchantOrderId) | Обновляет merchantOrderId в рантайме. | | onConfirmPay(callback) | Регистрирует callback подтверждения оплаты. | | pay() | Подтверждает оплату и запускает создание заказа (после onConfirmPay). |

Сборка пакета (для разработчиков)

npm install
npm run build

Сборка генерирует:

  • index.js (UMD/CJS)
  • index.esm.js (ESM)
  • index.d.ts (типы TypeScript)