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

swiftpay

v1.0.2

Published

API of Swiftpay

Downloads

5

Readme

NodeJS SwiftPay API

Документация по API

  1. Документация на русском языке,
  2. Documentation on English

Начало работы с библиотекой

Установка

Запустите команду npm install swiftpay

Авторизация запросов

Для авторизации запросов выполните следующие шаги:

  1. Зарегистрируйтесь и авторизуйтесь на сайте

  2. Перейдите в раздел настройки

  3. Скопируйте API ключ, предварительно нажав кнопку Показать

  4. Теперь вы можете отсылать запросы на API с использованием библиотеки swiftpay

var SwiftPay = require('swiftpay');

var apiSwift = new SwiftPay('<ВАШ API КЛЮЧ>');

apiSwift.account(function(error, response, body){
  console.log(error, response);
});

P.S. Для усиления безопасности рекомендуем хранить ваш API ключ в переменной среды:

  1. Перейдите в папку с проектом: cd /путь/к/корню/проекта
  2. В CMD Windows: SET swiftpay=ВАШ API КЛЮЧ В Linux: export swiftpay=ВАШ API ключ
  3. Получить токен
var apiSwift = new SwiftPay(process.env.swiftpay);

Валидация уведомления при успешной оплате на примере Express

router.post('/your/notification/link', (req, res) => {
  if(!apiSwift.validateSign(req.body)){
    res.status(500).send('Sign validation error');
    return;
  }
  // ... остальной код для обработки платежа, возвращающий статус 200 при успешном выполнении
})

Полный список доступных методов с примерами

  1. Создание ссылки для оплаты

    apiSwift.createOrder({
      shop_id: 1, // ID мерчанта,  
      order_id: 1, // номер заказа в системе мерчанта. Должен быть уникальным!!!
      amount: 10, // сумма
      desc: 'Описание', // необязательный параметр,
      data: { // необязательный параметр. После успешной оплаты этот объект будет отправлен на ссылку уведомления. Макс. кол-во полей: 5
        field: value
      }
    }, function(err, response, body){
      console.log(err, response); // данная функция будет вызвана после завершения запроса
    })
  2. Создание выплаты

    apiSwift.createPayout({
      system_id: 1, // id системы
      amount: 100, // сумма вывода
      wallet: '79001234567' // кошелек для вывода
    }, function(err, response, body){
      console.log(err, response);
    })
  3. Получение информации об аккаунте

    apiSwift.account(function(error, response, body){
      console.log(error, response);
    });
  4. Получение статистики аккаунта

    apiSwift.stats(function(error, response, body){
      console.log(error, response);
    });
  5. Получение списка созданных мерчантов

    apiSwift.shops(function(error, response, body){
      console.log(error, response);
    });
  6. Получение информации о конкретном мерчанте

    apiSwift.shop({
      id: 1 // ID мерчанта
    }, function(error, response, body){
      console.log(error, response);
    });
  7. Включение мерчанта

    apiSwift.shopActivate({
      id: 1 // ID мерчанта
    }, function(error, response, body){
      console.log(error, response);
    });
  8. Отключение мерчанта

    apiSwift.shopDeactivate({
      id: 1 // ID мерчанта
    }, function(error, response, body){
      console.log(error, response);
    });
  9. Удаление мерчанта

    apiSwift.shopDelete({
      id: 1 // ID мерчанта
    }, function(error, response, body){
      console.log(error, response);
    });
  10. Получение списка пополнений аккаунта с фильтрами.

    1. Доступные поля для сортировки: id, amount, order_id, created_at, paid_at, shop_id.
    2. Доступные поля для поиска: id, amount, order_id, created_at, paid_at, shop_id, email, status.
    3. Доступные операторы поиска: =, >, <, >=, <=, !=.
      apiSwift.orders({
        sort: 'id', // поле, по которому будет выполнена сортировка. См. п. 1
        sortType: 'DESC', // ASC - по возрастанию, DESC - по убыванию
        data: [{ // Если нужно отобразить записи без фильтра, то передайте пустой массив -  data: [],
          field: 'created_at',
          type: '>',
          value: '2020-01-19'
        }, {
          field: 'amount',
          type: '=',
          value: '100'
        },], // Отобразит только те записи, где дата создания была позже 19.01.2020 и сумма равной 100.
        limit: 25, // Число записей (от 25 до 250)
        offset: 0 // Смещение по записям. При limit = 25, offset = 25 будет второй страницей, offset = 50 будет третьей и т.д.
      }, function(error, response, body){
        console.log(error, response);
      });
  11. Получение списка выводов аккаунта с фильтрами:

    1. Доступные поля для сортировки: id, amount, system_id, wallet, created_at, paid_at, api.
    2. Доступные поля для поиска: id, amount, system_id, wallet, created_at, paid_at, api, status.
    3. Доступные операторы поиска: =, >, <, >=, <=, !=.
      apiSwift.payouts({
        sort: 'id', // поле, по которому будет выполнена сортировка. См. п. 1
        sortType: 'DESC', // ASC - по возрастанию, DESC - по убыванию
        data: [{ // Если нужно отобразить записи без фильтра, то передайте пустой массив -  data: [],
          field: 'created_at',
          type: '>',
          value: '2020-01-19'
        }, {
          field: 'amount',
          type: '=',
          value: '100'
        },], // Отобразит только те записи, где дата создания была позже 19.01.2020 и сумма равной 100.
        limit: 25, // Число записей (от 25 до 250)
        offset: 0 // Смещение по записям. При limit = 25, offset = 25 будет второй страницей, offset = 50 будет третьей и т.д.
      }, function(error, response, body){
        console.log(error, response);
      });
  12. Получение информации о выводе

    apiSwift.payout({
      id: 1 // ID выплаты
    }, function(error, response, body){
      console.log(error, response);
    });
  13. Подтверждение выплаты (если в настройках аккаунта автовыплаты отключены)

    apiSwift.payoutAccept({
      id: 1 // ID выплаты
    }, function(error, response, body){
      console.log(error, response);
    });
  14. Отклонение оплаты (если в настройках аккаунта автовыплаты отключены)

    apiSwift.payoutDecline({
      id: 1 // ID выплаты
    }, function(error, response, body){
      console.log(error, response);
    });
  15. Получение списка активных систем и их комиссий

    apiSwift.systems(function(error, response, body){
      console.log(error, response);
    });
  16. Получение информации о заказе

    apiSwift.orderById({
      id: 1 // ID заказа
    }, function(error, response, body){
      console.log(error, response);
    });

Заметки

  1. Каждый API запрос возвращает callback функцию с параметрами err, response и body. Если err не null, то запрос был произведен с ошибкой, указанной в err. Если err = null, то запрос успешно завершен и информация о нем лежит в следующем параметре response.