Tweed Docs
  • Welcome to Tweed
    • What Can Tweed Do?
  • Getting Started
    • Embedded Wallets | WaaS
    • Token Checkout | Payments
      • Flow of Funds: Purchase to Settlement
      • Token Checkout
      • Legacy Token Checkout
        • Basic Checkout Integration
        • Checkout + WaaS + Auth
        • Features
          • Payment links
          • Whitelist
          • Flow of Funds
          • Apple & Google Pay
          • AML & KYC Policy Overview
  • Developer Tools
    • Tweed SDKs
      • core-react
        • useAuth
        • useWallet
        • useTweed
        • usePayments
        • useWeb3
      • core-js
      • core-vue
      • Payments SDKs (v1)
        • Frontend SDKs (Payments)
        • Backend SDK (Payments)
        • How to set up your smart contract for Tweed
        • Tezos chain considerations
    • Management Dashboard
      • Create platform
      • Create application
        • UI Customization
    • Webhooks
      • Checkout Webhooks
    • API
      • API (V1)
      • API (V2)
        • Authorization
        • API reference
          • Contracts
            • Add
            • Add contract function
            • Contract
          • Payouts
            • Add
            • Payout
          • Items
            • Add
            • All
              • Contract
                • Count
              • Payout
                • Count
          • Assets
            • Blockchain
            • All
              • Blockchains
          • Blockchains
            • Multiple
            • Native asset
          • Audit event mappings
          • Platform webhooks
            • Set active
          • Tickets
        • Specification
    • External Integrations
      • Wagmi connector
      • Onramp to Crypto
    • Example Projects
    • Supported Blockchains
    • Pricing
  • Products
    • WaaS
    • Payments
Powered by GitBook
On this page
  • 1. Contact Tweed support for Payments API keys
  • 2. List Your contract Address
  • 3. Let's start with the backend
  • 4. Prepare the frontend
  1. Getting Started
  2. Token Checkout | Payments
  3. Legacy Token Checkout

Basic Checkout Integration

To seamlessly integrate token checkout into your application, follow these steps

Last updated 5 months ago

We are migrating to V2 soon, and all the payments SDK for V1 will become deprecated

in V2 you don't need to have a backend for your application - all the catalog management is performed through our /

Related topic

Payments

Associated Development tools

API (V1)

Payments SDKs (v1)

Features

Payment links | Whitelist | Flow of Funds | Apple & Google Pay AML & KYC Policy Overview | Dynamic Token Amount | Marketplace Integration

Examples

Example Projects

1. Contact Tweed support for Payments API keys

You will receive two pairs of API keys. One pair is for the backend SDK, which authenticates your requests. The other pair is for facilitating your checkout implementation, such as adding contract addresses or creating whitelists.

2. List Your contract Address

3. Let's start with the backend

1. Add tweed to your Backend

npm i @paytweed/backend-sdk

2. Setup

Import TweedBackendSDK from the @paytweed/backend-sdk and implement the setup function. Pass your API keys and specify the default blockchains for your application.

Next, we will create an endpoint to be accessed by the frontend SDK for sending and receiving messages. Within this endpoint, we will use the handleMessageFromFrontend function. This function will handle messages arriving from the frontend SDK, along with the user ID and user email.

This implementation does not include WaaS. You can keep the user ID and email the same for each transaction, as demonstrated in our example. Alternatively, integrate our wallet product alongside the checkout process.

index.ts
import { TweedBackendSDK } from '@paytweed/backend-sdk'
import express from 'express'

const tweed = await TweedBackendSDK.setup({
  apiKey: 'YOUR_API_KEY',
  apiSecret: 'YOUR_API_SECRET',
  defaultBlockchainIds: ['ethereumSepolia'],
})

const app = express()
app.use(express.json())

app.post('/message', async (req, res) => {
  const userId = '1'
  const userEmail = 'a@a.com'
  
  const answer = await tweed.handleMessageFromFrontend(req.body.message, userId, userEmail)
  
  res.send({ answer })
})

app.listen(3000, () => console.log('Example app listening on port 3000'))

3. Token checkout callback

tweed facilitate multiple settlement options: you can receive payments via credit card and choose to receive funds in either fiat currency or crypto, including native chain currencies or ERC20 tokens.

The next step involves handling this purchase on your backend. To accomplish this, you need to implement a callback function named getTokenPurchaseData. This function receives the tokenId parameter from the frontend as an input and expects to retrieve transaction details such as contract address, price, and other relevant information.

tokenCheckout.ts
export const getTokenPurchaseData = async ({
  tokenId,
}: {
  tokenId: string
}) => {
  const tokenData = {
    tokenId,
    amount,
    tokenContractAddress,
    priceInCents:
    priceInCrypto:
    fiatCurrencyId:
    thumbnailPath:
    contractAddress:
    chain:
    title:
    description:
    abi:
    customMintParams: {
      amount,
    },
  }
  return tokenData
}

Next, Add the function to the setup function:

index.ts
// ...
const tweed = await TweedBackendSDK.setup({
  apiKey: 'YOUR_API_KEY',
  apiSecret: 'YOUR_API_SECRET',
  defaultBlockchainIds: ['ethereumSepolia'],
  callbacks: {
      getTokenPurchaseData // <<< Here
  }
})
// ...

4. Prepare the frontend

choose from our frontend SDKs for various frameworks: React, React Native, or vanilla JavaScript

1. Add tweed to your React app

install tweed SDK to your React app.

npm i @paytweed/frontend-sdk-react

2. Integrate Tweed Provider into Your App

  • Import the TweedFrontendSdkProvider from the Tweed React SDK and wrap your application with it.

  • Implement the function sendMessageToBackend, which will send a message to the backend SDK.

    App.tsx
    import { TweedFrontendSdkProvider } from '@paytweed/frontend-sdk-react'
    import DemoPage from "pages/demo";
    import { useCallback } from 'react'
    
    function App() {
    
    const sendMessageToBackend = useCallback(async (message: string) => {
        const response = await fetch('http://your-server.com/message', {
          body: JSON.stringify({ message }),
          headers: { 'Content-Type': 'application/json' },
          method: 'POST',
        })
        const { answer } = await response.json()
        return answer
      }, [])
      return (  
        <>
          <TweedFrontendSdkProvider
          sendMessageToBackend={sendMessageToBackend}
          defaultBlockchainIds={['ethereumSepolia', 'polygonMumbai']}
          theme="light" // "light" | "dark"
          >
            <HomePage />
          </TweedFrontendSdkProvider>
        </>
      );
    }

To call the token checkout widget, a wallet must be created for the user associated with this widget. Even if you plan to specify a different wallet address for each transaction to receive the token, you must still have an existing wallet.

3. Make sure user has wallet before calling token checkout widget

HomePage.tsx
import React, { useState, useEffect } from 'react';
import { hooks } from '@paytweed/frontend-sdk-react';

function HomePage() {
  const frontendSDK = hooks.useTweedFrontendSDK();
  const [isWalletExist, setIsWalletExist] = useState(false);
    
  async function handleWalletCreation() {
    if (isWalletExist) return;
    await frontendSDK.wallet.create();
    setIsWalletExist(true);
  }

  useEffect(() => {
    if (!isWalletExist) handleWalletCreation();
  }, [isWalletExist]);


  return (
    <div>
      <h1>HomePage</h1>
    </div>
  );
}

export default HomePage;

4. Let's call the buy token function

Use the toWalletAddress parameter within the buyWithFiat function to specify the destination wallet address where the token will be sent.

HomePage.tsx
import { hooks } from '@paytweed/frontend-sdk-react';

function HomePage() {
  const frontendSDK = hooks.useTweedFrontendSDK();
  const [isWalletExist, setIsWalletExist] = useState(false);
    
  async function handleWalletCreation() {
    if (isWalletExist) return;
    await frontendSDK.wallet.create();
    setIsWalletExist(true);
  }

  useEffect(() => {
    if (!isWalletExist) handleWalletCreation();
  }, [isWalletExist]);
    
  async function onClickBuy() {
    try {
      await frontendSDK.token.buyWithFiat({
        tokenId: '1',
        toWalletAddress: '0x12'
        callbacks: {
          onSuccess: (payload) => {
            console.log('success', payload);
          },
        },
      });
    } catch (error) {
      console.error('Error buying token:', error);
    }
  }
  
  return (
    <div>
      <h1>HomePage</h1>
      <button onClick={onClickBuy}>Buy</button>
    </div>
  );
}

export default HomePage;
const message = "hello world";
console.log(message);

introduce your contract address to tweed by our API, use the management API keys you got from us. read more how to deploy contract address .

This example demonstrates settlement with fiat currency.

Please refer to the detailed: for complete info regarding the purchase data callback.

Here are guides for alternative settlement options
Backend Payments SDK Reference
Management Dashboard
API
here
token checkout screenshots