# @coinbase/cbpay-js 中文文档

规范地址：https://npmcn.com/package/%40coinbase/cbpay-js/

版本：2\.4\.0
npm 元数据更新时间：2025-03-25T22:26:53.348Z
中文译文更新时间：2026-11-10T10:22:51.190Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40coinbase/cbpay-js
原文对照：https://npmcn.com/package/%40coinbase/cbpay-js/?lang=original
项目主页：https://github.com/coinbase/cbpay-js#readme
源码仓库：https://github.com/coinbase/cbpay-js

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：126 kB，9 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>= 14
- 运行依赖：0 个
- peer 依赖：regenerator-runtime ^0\.13\.9
- 首次发布：2022-04-22T03:11:58.358Z
- 最新版本发布：2024-11-08T18:53:10.722Z
- 近 30 天下载量：68589（2026-10-11 至 2026-11-09，npm 官方下载统计）
- 已发布版本数：18（近 12 个月 0 个）

## 中文简介

Coinbase Onramp JS SDK 包含了帮助者的方法 来简化与我们的fiat onramp的融合. 钱包提供商和dapp可以利用Coinbase Onramp来杠杆,让用户将自控钱包顶上.

## 安装

```sh
npm install @coinbase/cbpay-js
```

也可以使用：`pnpm add @coinbase/cbpay-js`、`yarn add @coinbase/cbpay-js`、`bun add @coinbase/cbpay-js`

## README

# @coinbase/ cbpay-js (英语)

Coinbase Onramp JS SDK 包含了帮助者的方法 来简化与我们的fiat onramp的融合. 钱包提供商和dapp可以利用Coinbase Onramp来杠杆,让用户将自控钱包顶上.

## 文档

见 [Conbase Onramp 文档](https://docs.cdp.coinbase.com/onramp/docs/getting-started/) 说明如何登机前往Coinbase Onramp并开始.

## 安装

与 `yarn`数字 :

```shell
yarn add @coinbase/cbpay-js
```

与 `npm`数字 :

```shell
npm install @coinbase/cbpay-js
```

该软件包既作为无害环境管理模块分发,又作为通用JS分发。 要使用通用JS输出,请输入 `regenerator-runtime` 还需要安装软件包 :

与 `yarn`数字 :

```shell
yarn add regenerator-runtime
```

与 `npm`数字 :

```shell
npm install regenerator-runtime
```

## 基本实例

```jsx
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();
```

## 反应示例

```tsx
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>;
};
```

## 反应- Native 示例

### 先决条件

```
yarn add react-native-url-polyfill
```

```tsx
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
```

## 聚合实例

评议 [Coinbase 开发者文件](https://docs.cdp.coinbase.com/onramp/docs/api-aggregating/) 如何在坡道聚合器内生成使用参数.

```tsx
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>;
};
```

## 捐款

需要签名才能为这项还款作出贡献。 详情见文件 [捐款](https://npmcn.com/package/%40coinbase/cbpay-js/CONTRIBUTING.md) 财务报告和审定财务报表 [承诺签署](https://npmcn.com/package/%40coinbase/cbpay-js/docs/commit-signing.md)。 。 。 .

## 常见问题

### @coinbase/cbpay-js 是什么？

Coinbase Onramp JS SDK 包含了帮助者的方法 来简化与我们的fiat onramp的融合\. 钱包提供商和dapp可以利用Coinbase Onramp来杠杆,让用户将自控钱包顶上\.

### 如何安装 @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 和提交记录判断。

