@coinbase/cbpay-js

中文文档
2.4.0发布于 2024/11/09MITTypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 6.9万

The Coinbase Onramp JS SDK contains helper methods to simplify integrating with our fiat onramp. Wallet providers and dapps can leverage Coinbase Onramp and let their users top up their self-custody wallets.

原始使用文档
文档目录8 节
  1. Documentation
  2. Installation
  3. Basic example
  4. React example
  5. React-Native example
  6. Prerequisites
  7. Aggregator Example
  8. Contributing

@coinbase/cbpay-js

The Coinbase Onramp JS SDK contains helper methods to simplify integrating with our fiat onramp. Wallet providers and dapps can leverage Coinbase Onramp and let their users top up their self-custody wallets.

Documentation

See the Coinbase Onramp documentation for instructions on how to onboard to Coinbase Onramp and get started.

Installation

With yarn:

yarn add @coinbase/cbpay-js

With npm:

npm install @coinbase/cbpay-js

The package is distributed as both ESModules and CommonJS. To use the CommonJS output, the regenerator-runtime package will also need to be installed:

With yarn:

yarn add regenerator-runtime

With npm:

npm install regenerator-runtime

Basic example

import { initOnRamp } from '@coinbase/cbpay-js';

const options = {
  appId: '<Your Project ID obtained from Coinbase Developer Platform>',
  widgetParameters: {
    // Specify the addresses and which networks they support
    addresses: { '0x0': ['ethereum','base'], 'bc1': ['bitcoin']},
    // Filter the available assets on the above networks to just these ones
    assets: ['ETH','USDC','BTC'],
  },
  onSuccess: () => {
    console.log('success');
  },
  onExit: () => {
    console.log('exit');
  },
  onEvent: (event) => {
    console.log('event', event);
  },
  experienceLoggedIn: 'popup',
  experienceLoggedOut: 'popup',
  closeOnExit: true,
  closeOnSuccess: true,
};

// Initialize the CB Pay instance
let onrampInstance;
initOnRamp(options, (error, instance) => {
  onrampInstance = instance;
});

// Open the widget when the user clicks a button
onrampInstance.open();

React example

import { CBPayInstanceType, initOnRamp } from "@coinbase/cbpay-js";
import { useEffect, useState } from "react";

export const PayWithCoinbaseButton: React.FC = () => {
  const [onrampInstance, setOnrampInstance] = useState<CBPayInstanceType | null>();

  useEffect(() => {
    initOnRamp({
      appId: '<Your Project ID obtained from Coinbase Developer Platform>',
      widgetParameters: {
        // Specify the addresses and which networks they support
        addresses: { '0x0': ['ethereum','base'], 'bc1': ['bitcoin']},
        // Filter the available assets on the above networks to just these ones
        assets: ['ETH','USDC','BTC'],
      },
      onSuccess: () => {
        console.log('success');
      },
      onExit: () => {
        console.log('exit');
      },
      onEvent: (event) => {
        console.log('event', event);
      },
      experienceLoggedIn: 'popup',
      experienceLoggedOut: 'popup',
      closeOnExit: true,
      closeOnSuccess: true,
    }, (_, instance) => {
      setOnrampInstance(instance);
    });

    // When button unmounts destroy the instance
    return () => {
      onrampInstance?.destroy();
    };
  }, []);

  const handleClick = () => {
    onrampInstance?.open();
  };

  return <button onClick={handleClick} disabled={!onrampInstance}>Buy with Coinbase</button>;
};

React-Native example

Prerequisites

yarn add react-native-url-polyfill
import React, { useMemo } from 'react'
import { WebView } from 'react-native-webview'
import { generateOnRampURL } from '@coinbase/cbpay-js'
import 'react-native-url-polyfill/auto'

const CoinbaseWebView = ({ currentAmount }) => {
  const coinbaseURL = useMemo(() => {
    const options = {
      appId: '<Your Project ID obtained from Coinbase Developer Platform>',
      // Specify the addresses and which networks they support
      addresses: { '0x0': ['ethereum','base'], 'bc1': ['bitcoin']},
      // Filter the available assets on the above networks to just these ones
      assets: ['ETH','USDC','BTC'],
      handlingRequestedUrls: true,
      presetCryptoAmount: currentAmount,
    }

    return generateOnRampURL(options)
  }, [currentAmount, destinationAddress])

  const onMessage = useCallback((event) => {
    // Check for Success and Error Messages here
    console.log('onMessage', event.nativeEvent.data)
    try {
      const { data } = JSON.parse(event.nativeEvent.data);
      if (data.eventName === 'request_open_url') {
        viewUrlInSecondWebview(data.url);
      }
    } catch (error) {
      console.error(error);
    }
  }, [])

  return (
    <WebView source={{ uri: coinbaseURL }} onMessage={onMessage} />
  )
}

export default CoinbaseWebView

Aggregator Example

Review the Coinbase Developer docs for how to produce the parameters for use within an on ramp aggregator.

import { CBPayInstanceType, initOnRamp } from "@coinbase/cbpay-js";
import { useEffect, useState } from "react";

export const PayWithCoinbaseButton: React.FC = () => {
  const [onrampInstance, setOnrampInstance] = useState<CBPayInstanceType | null>();

  useEffect(() => {
    initOnRamp({
      appId: '<Your Project ID obtained from Coinbase Developer Platform>',
      widgetParameters: {
        // Specify the addresses and which networks they support
        addresses: { '0x0': ['ethereum','base'], 'bc1': ['bitcoin']},
        // Filter the available assets on the above networks to just these ones
        assets: ['ETH','USDC','BTC'],
        // Aggregator params are ignored unless they are all provided.
        // defaultNetwork is the exception - it's optional.
        quoteId: '<quote_id from the Buy Quote API>',
        defaultAsset: 'USDC',
        defaultNetwork: 'base',
        defaultPaymentMethod: 'CARD',
        presetFiatAmount: 20,
        fiatCurrency: 'USD',
      },
      onSuccess: () => {
        console.log('success');
      },
      onExit: () => {
        console.log('exit');
      },
      onEvent: (event) => {
        console.log('event', event);
      },
      experienceLoggedIn: 'popup',
      experienceLoggedOut: 'popup',
      closeOnExit: true,
      closeOnSuccess: true,
    }, (_, instance) => {
      setOnrampInstance(instance);
    });

    // When button unmounts destroy the instance
    return () => {
      onrampInstance?.destroy();
    };
  }, []);

  const handleClick = () => {
    onrampInstance?.open();
  };

  return <button onClick={handleClick} disabled={!onrampInstance}>Buy with Coinbase</button>;
};

Contributing

Commit signing is required for contributing to this repo. For details, see the docs on contributing and commit-signing.

版本与发布记录

@coinbase/cbpay-js 共发布 18 个版本,首次发布于 2022/04/22;过去 12 个月发布了 0 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
2.4.0latest2024/11/092 年前
2.3.02024/10/222 年前
2.2.12024/08/022 年前
2.2.02024/06/132 年前
2.1.02024/03/162 年前
1.10.02024/01/122 年前

关于 @coinbase/cbpay-js 的常见问题

@coinbase/cbpay-js 是什么?

The Coinbase Onramp JS SDK contains helper methods to simplify integrating with our fiat onramp. Wallet providers and dapps can leverage Coinbase Onramp and let their users top up their self-custody wallets.

如何安装 @coinbase/cbpay-js?

在项目目录运行 npm install @coinbase/cbpay-js,或使用 pnpm add / yarn add / bun add。

@coinbase/cbpay-js 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@coinbase/cbpay-js 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@coinbase/cbpay-js 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >= 14。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@coinbase/cbpay-js 可以商用吗?

@coinbase/cbpay-js 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@coinbase/cbpay-js 的下载量有多少?

根据 npm 官方下载统计,@coinbase/cbpay-js 在 2026/10/11 – 2026/11/09 这 30 天内被下载 68,589 次,日均约 2,286 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@coinbase/cbpay-js 还在维护吗?

最新版本 2.4.0 发布于 2024/11/09(2 年前);至今共发布 18 个版本,其中过去 12 个月发布了 0 个;首次发布于 2022/04/22。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。