• Сообщество
  • Блог
Документация
Плагины и интеграцииВсе расширения для Medusa от сообществаСтартерыЗапускайте проекты быстрее с готовыми решениями
ЭкспертыПодберите специалиста для разработки и развития вашего проекта на MedusaКейсыПосмотрите примеры Medusa в продакшене и успешные внедрения
Меч Moscow
Комплексная e-commerce платформа на Medusa для московского fashion-бренда

Меч Moscow · Fashion

Gorgo снижает затраты на адаптацию Medusa к локальным рынкам.

Мы разрабатываем плагины интеграции, осуществляем поддержку и развиваем сообщество разработчиков на Medusa в Telegram.

  • Ресурсы Medusa
  • Плагины и интеграции
  • Стартеры
  • Эксперты
  • Кейсы
  • Medusa Чат в Telegram
  • Medusa Новости в Telegram
  • Документация Gorgo
  • Связаться с нами
  • TelegramGitHub
Плагины
BTCPay logo

BTCPay

Принимайте Bitcoin-платежи через BTCPay

npm install medusa-plugin-btcpay
Категория
Платежи
Создано
Sgfgov
Версия
0.0.6
Последнее обновление
11 месяцев назад
Ежемесячные загрузки
Загрузка данных
Звезды на Github
17
npmNPMGitHubGithub

Support the Payment-BitcoinPayServer Provider – Power the Future of Medusa Commerce!

Dear Developers and E-commerce Pioneers,

Get ready to embrace the world of decentralized finance for your online stores with MedusaJS! We are excited to introduce the Payment-BitcoinPayServer provider – a community-driven project that brings the powerful Bitcoin PayServer gateway to our MedusaJS commerce stack.

What's in it for You:

🛡️ Secure & Sovereign Payments: Enable direct Bitcoin Network payments without relying on third-party payment processors.

🌍 Borderless Transactions: Serve a global audience with permissionless payments that know no borders.

🚀 Empower Open Commerce: By sponsoring this provider, you contribute to the Medusa community's growth, independence, and innovation!

Installation Made Simple

Use the package manager npm to install Payment-BitcoinPayServer.

yarn add medusa-plugin-btcpay

Usage

Set up a Bitcoin PayServer instance, either self-hosted or via a trusted host.

In your environment file () define:

1BTCPAY_URL=https://your-btcpayserver-instance.com
2BTCPAY_API_KEY=<your api key>
3BTCPAY_STORE_ID=<your store id>
4BTCPAY_WEBHOOK_SECRET=<your webhook secret>

You need to add the provider into your :

1module.exports = defineConfig({
2 modules: [
3 ...
4 {
5 resolve: "@medusajs/medusa/payment",
6 options: {
7 providers: [
8 ...
9 {
10 resolve: "@yourorg/payment-btcpayserver",
11 id: "btcpayserver",
12 options: {
13 url: process.env.BTCPAY_URL,
14 apiKey: process.env.BTCPAY_API_KEY,
15 storeId: process.env.BTCPAY_STORE_ID,
16 webhookSecret: process.env.BTCPAY_WEBHOOK_SECRET,
17 },
18 },
19 ...
20 ],
21 },
22 },
23 ...
24 ]
25})

Client Side Configuration

For your Medusa Next.js storefront, follow these steps:

Step 1. Install the Bitcoin Payment Button package

(optional - depends on your design)

yarn add react-btcpay-button

Step 2. Create the Bitcoin Payment Button Component in packages/storefront/src/modules/checkout/components/payment-button/index.tsx

Step 2.1 introduce a state variable to track clicks.

1const PaymentButton: React.FC<PaymentButtonProps> = ({
2 cart,
3 "data-testid": dataTestId,
4}) => {
5 const [btcClicked, setBtcClicked] = useState(false)
6 ....
7}

Step 2.2 Then in the case

1case isBtcpay(paymentSession?.provider_id):
2 return (
3 <Button disabled={btcClicked} onClick={() => {setBtcClicked(true);
4 window.open(`${(paymentSession?.data as any).btc_invoice.checkoutLink}`)}}>
5 Pay with BtcPay
6 </Button>
7 )

Step 3. Extend Payment Constants

In :

1export const isBtcpay = (providerId?: string) => {
2 return providerId?.startsWith("pp_btcpay")
3}
4
5export const paymentInfoMap: Record<
6 string,
7 { title: string; icon: React.JSX.Element }
8> = {
9 ...
10 pp_btcpay_btcpay: {
11 title: "BtcPay",
12 icon: <CurrencyDollarSolid />,
13 },
14 ...
15}

Step 4. Hook Up the Payment Button

In :

1import { BtcpayserverPaymentButton } from "./btcpayserver-payment-button"
2
3...
4
5case "btcpayserver":
6 return <BtcpayserverPaymentButton session={paymentSession} notReady={notReady} cart={cart} />

step 5 . Create a confirmation page to poll the server --

You can use any mechanism, but i'chosen long polling, coz its just simple. You could use websockets or any other call back mechanism.

processing/page.tsx

1"use client";
2
3import { useEffect } from "react";
4import { useRouter } from "next/navigation";
5
6import { useSearchParams } from "next/navigation";
7import { sdk } from "@lib/config";
8import axios from "axios";
9
10const ProcessingPage = () => {
11 const router = useRouter();
12 const searchParams = useSearchParams();
13
14 const cart= searchParams.get("cart");
15
16
17 useEffect(() => {
18 let isCancelled = false;
19
20 const fetchData = async () => {
21 try {
22 const url = `${process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL}/checkout/is-paid?cart=${cart}`
23 console.log("Fetching data from URL:", url);
24 let response = await axios.get(url,{
25 headers: {
26 'content-type': 'application/json',
27 'x-publishable-api-key': process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY,
28 }
29 }) as any;
30
31 const result = await sdk.store.cart.complete(cart!) as {
32 order: {
33 id: string;
34 };
35 }
36 const redirectUrl = `/order/${result.order.id}/confirmed`
37
38 //const response = await fetch(`${process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL}/checkout/is-paid?cart=${cart}`);
39 /// const data = response.data;
40 if (!isCancelled && redirectUrl) {
41 router.push(redirectUrl);
42 }
43 } catch (error) {
44 if (!isCancelled) {
45 console.log("Error fetching data:", JSON.stringify(error));
46 }
47 } finally {
48 if (!isCancelled) {
49 setTimeout(fetchData, 5000); // Poll every 5 seconds
50 }
51 }
52 };
53
54 fetchData();
55
56 return () => {
57 isCancelled = true;
58 };
59 }, []);
60
61 return (
62 <div>
63 <h1>Processing...</h1>
64 <p>Please wait while we process your request.</p>
65 </div>
66 );
67};
68
69export default ProcessingPage;

Step 6. Configure Environment Variables in Frontend

Set the following environment variables for your storefront:

1NEXT_PUBLIC_SHOP_NAME=<your shop name>
2NEXT_PUBLIC_MEDUSA_BACKEND_URL=<your medusa store>

Setting Up BTCPay Server Webhook

In BTCPayServer, add a webhook with this URL:

<your-host-url>/hooks/payment/btcpay_btcpay

Make sure you set the webhook secret to match your value.

Contributing

Pull requests are welcome! For significant changes, please open an issue first to discuss improvements or new features.

Please ensure tests and documentation are updated appropriately.

License

MIT License

Untested Features

Some features exist but haven't been fully tested in client integration:

  • Refund support
  • Lightning Network (LNURL and other advanced flows)

Disclaimer

This project is community-driven and tested in limited scenarios. Bugs may occur; please raise issues or submit pull requests if you encounter any.

Support the Payment-BitcoinPayServer Provider – Fuel Open Commerce!

Dear Medusa Enthusiasts,

Thank you for your passion and energy for open e-commerce!
The Payment-BitcoinPayServer provider is an open-source project crafted to connect MedusaJS with the powerful Bitcoin payment ecosystem.

If you find this project useful, consider sponsoring it on GitHub to help maintain and expand it.
Your support makes a world of difference in creating decentralized, open, and innovative commerce for all.

Let's keep building the future together!

With gratitude,
SGFGOV
Lead Developer, Payment-BitcoinPayServer Provider

Еще в этой категории

Посмотреть все
Платежи
Braintree logo

Braintree

От Lambda Curry

Поддержка платежей и 3D Secure через Braintree

Загрузка данных
GitHubnpm
Платежи
Pay. logo

Pay.

От Webbers

Принимайте кредитные карты, цифровые платежи и купи сейчас — плати потом

Загрузка данных
GitHubnpm
Платежи
Mollie logo

Mollie

От Variable Vic

Легко принимайте мультивалютные платежи через Mollie

Загрузка данных
GitHubnpm

Еще от этого автора

Посмотреть все
Другое
Razorpay logo

Razorpay

От Sgfgov

Интегрируйте новейшие платежные API Razorpay

Загрузка данных
GitHubnpm