# Checkout + WaaS + Auth

{% hint style="danger" %}
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 [Management Dashboard](https://docs.paytweed.com/developer-tools/management-dashboard) / [API](https://docs.paytweed.com/developer-tools/api/api-v2)
{% endhint %}

<figure><img src="https://2034179314-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FgQyCg5IN7Cv6AnUUpGl2%2Fuploads%2FdIjyF8kdAS4G2zyRmhGx%2Fcheckout%20%2B%20waas%20%2B%20auth1.png?alt=media&#x26;token=9426467c-30c4-45bb-9105-0fdf429a5593" alt="token checkout and wallet screenshots "><figcaption></figcaption></figure>

> Related topics
>
> [payments](https://docs.paytweed.com/products/payments "mention") | [waas](https://docs.paytweed.com/products/waas "mention")&#x20;

> Related Guide
>
> [embedded-wallets-or-waas](https://docs.paytweed.com/getting-started/embedded-wallets-or-waas "mention")

> Associated Development tools
>
> [api-v1](https://docs.paytweed.com/developer-tools/api/api-v1 "mention")&#x20;
>
> [payments-sdks-v1](https://docs.paytweed.com/developer-tools/tweed-sdks/payments-sdks-v1 "mention")

> Features
>
> [payment-links](https://docs.paytweed.com/getting-started/token-checkout-or-payments/legacy-token-checkout/features/payment-links "mention") | [whitelist](https://docs.paytweed.com/getting-started/token-checkout-or-payments/legacy-token-checkout/features/whitelist "mention") | [flow-of-funds](https://docs.paytweed.com/getting-started/token-checkout-or-payments/legacy-token-checkout/features/flow-of-funds "mention") | [apple-and-google-pay](https://docs.paytweed.com/getting-started/token-checkout-or-payments/legacy-token-checkout/features/apple-and-google-pay "mention") \
> [aml-and-kyc-policy-overview](https://docs.paytweed.com/getting-started/token-checkout-or-payments/legacy-token-checkout/features/aml-and-kyc-policy-overview "mention") | [dynamic-token-amount](https://docs.paytweed.com/getting-started/token-checkout-or-payments/legacy-token-checkout/features/dynamic-token-amount "mention") | [marketplace-integration](https://docs.paytweed.com/getting-started/token-checkout-or-payments/legacy-token-checkout/features/marketplace-integration "mention")

> Examples
>
> [example-projects](https://docs.paytweed.com/developer-tools/example-projects "mention")

{% hint style="warning" %}
Before starting this guide, ensure WaaS is already implemented in your application. If not, use the [following guide](https://docs.paytweed.com/getting-started/embedded-wallets-or-waas)
{% endhint %}

### 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

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 [here](https://docs.paytweed.com/developer-tools/api/api-v1#payments).

### 3. Let's start with the backend

#### 1. Add tweed to your Backend

```bash
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.

{% hint style="info" %}
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.
{% endhint %}

{% code title="index.ts" %}

```typescript
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'))
```

{% endcode %}

#### 3. Token checkout callback

{% hint style="success" %}
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.
{% endhint %}

{% hint style="info" %}
This example demonstrates settlement with fiat currency.\
[Here are guides for alternative settlement options](https://docs.paytweed.com/getting-started/token-checkout-or-payments/legacy-token-checkout/features/flow-of-funds)
{% endhint %}

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.

{% code title="tokenCheckout.ts" %}

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

{% endcode %}

Please refer to the detailed: [Backend Payments SDK Reference](https://docs.paytweed.com/developer-tools/tweed-sdks/payments-sdks-v1/backend-sdk-payments) for complete info regarding the purchase data callback.

Next, Add the function to the setup function:

{% code title="index.ts" %}

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

{% endcode %}

### 4. Prepare the frontend

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

{% tabs %}
{% tab title="React" %}

#### 1. Add tweed Payments SDK to your React app:

```bash
npm i @paytweed/frontend-sdk-react
```

#### &#x20;2.  Integrate Tweed Provider (payments) into Your App

At this point, `TweedProvider` should already be in your app. Now, we are adding `TweedFrontendSdkProvider`to enable payments in your application.

* 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.<br>

  <pre class="language-tsx" data-title="App.tsx"><code class="lang-tsx">import { TweedFrontendSdkProvider } from '@paytweed/frontend-sdk-react'
  import { Network, TweedProvider } from "@paytweed/core-react";
  import HomePage from "pages/HomePage";
  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 (  
      &#x3C;>
        &#x3C;TweedFrontendSdkProvider
          sendMessageToBackend={sendMessageToBackend}
          defaultBlockchainIds={['polygon', 'ethereum']}
        >
          &#x3C;TweedProvider
            applicationId="YOUR_APP_ID"
            options={{
              chains: [Network.POLYGON, Network.ETHEREUM]
            }}
          >
            &#x3C;HomePage />
          &#x3C;/TweedProvider>
        &#x3C;/TweedFrontendSdkProvider>
      &#x3C;/>
    );
  }
  </code></pre>

{% hint style="warning" %}
To call the token checkout widget, a wallet must be created for the user associated with this widget on the payments SDK. Even though we are going to obtain the wallet address from the WaaS SDK for each transaction to receive the token, you must still have an existing wallet on the payments SDK.
{% endhint %}

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

{% code title="HomePage.tsx" %}

```tsx
import React, { useState, useEffect } from 'react';
import { hooks } from '@paytweed/frontend-sdk-react';
import { useAuth, useTweed } from "@paytweed/core-react";

function HomePage() {
  const { connect } = useAuth()
  const { client, loading } = useTweed();
  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]);
  
  
      function handleConnect() {
    if(!client) return
    connect()
  }


  return (
    <div>
      <h1>HomePage</h1>
            { loading ?
        <h2> loading... </h2> :
       <button onClick={handleConnect}>connect</button> 
       }
    </div>
  );
}

export default HomePage;
```

{% endcode %}

#### 4. Get the user wallet address

use the getEthereumProvider function from useWeb3 to obtain the user's wallet address. we will pass this address to the token checkout widget to handle sending the token to the user's wallet

```tsx
import { useState, useEffect } from 'react';
import { hooks } from '@paytweed/frontend-sdk-react';
import { useAuth, useTweed, useWeb3, Network } from "@paytweed/core-react";
import { BrowserProvider } from "ethers";

function HomePage() {
  const { connect } = useAuth();
  const { client, loading } = useTweed();
  const { getEthereumProvider } = useWeb3();
  const frontendSDK = hooks.useTweedFrontendSDK();
  const [isWalletExist, setIsWalletExist] = useState(false);
  const [walletAddress, setWalletAddress] = useState<string>();
  
  async function handleWalletCreation() {
    if (isWalletExist) return;
    await frontendSDK.wallet.create();
    setIsWalletExist(true);
  }
  
  useEffect(() => {
    if (!isWalletExist) handleWalletCreation();
  }, [isWalletExist]);
  
  function handleConnect() {
    if (!client) return;
    connect();
  }

  async function getWalletAddress() {
    const provider = await getEthereumProvider(Network.ETHEREUM_SEPOLIA);
    const web3provider = new BrowserProvider(provider);
    const signer = await web3provider.getSigner();
    const userAddress = await signer.getAddress();
    setWalletAddress(userAddress);
  }

  useEffect(() => {
    getWalletAddress();
  }, [walletAddress]);

  return (
    <div>
      <h1>HomePage</h1>
      {loading ? (
        <h2>Loading...</h2>
      ) : (
        <button onClick={handleConnect}>Connect</button>
      )}
    </div>
  );
}

export default HomePage;

```

#### 5. Let's call the buy token function

Use the `toWalletAddress` parameter in the `buyWithFiat` function to specify where the token should go. Use the wallet address we just got.

{% code title="HomePage.tsx" %}

```tsx
import { useState, useEffect } from 'react';
import { hooks } from '@paytweed/frontend-sdk-react';
import { useAuth, useTweed, useWeb3, Network } from "@paytweed/core-react";
import { BrowserProvider } from "ethers";

function HomePage() {
  const { connect } = useAuth();
  const { client, loading } = useTweed();
  const { getEthereumProvider } = useWeb3();
  const frontendSDK = hooks.useTweedFrontendSDK();
  const [isWalletExist, setIsWalletExist] = useState(false);
  const [walletAddress, setWalletAddress] = useState<string>();

  async function handleWalletCreation() {
    if (isWalletExist) return;
    await frontendSDK.wallet.create();
    setIsWalletExist(true);
  }

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

  function handleConnect() {
    if (!client) return;
    connect();
  }

  async function getWalletAddress() {
    const provider = await getEthereumProvider(Network.ETHEREUM_SEPOLIA);
    const web3provider = new BrowserProvider(provider);
    const signer = await web3provider.getSigner();
    const userAddress = await signer.getAddress();
    setWalletAddress(userAddress);
  }

  useEffect(() => {
    getWalletAddress();
  }, [walletAddress]);

  async function onClickBuy() {
  if(!isWalletExist) return
    try {
      await frontendSDK.token.buyWithFiat({
        tokenId: '1',
        toWalletAddress: walletAddress,
        callbacks: {
          onSuccess: (payload) => {
            console.log('success', payload);
          },
        },
      });
    } catch (error) {
      console.error('Error buying token:', error);
    }
  }

  return (
    <div>
      <h1>HomePage</h1>
      {loading ? (
        <h2>Loading...</h2>
      ) : (
        <button onClick={handleConnect}>Connect</button>
      )}
      <button onClick={onClickBuy}>Buy Token</button>
    </div>
  );
}

export default HomePage;

```

{% endcode %}
{% endtab %}
{% endtabs %}
