# Sending Payments Through Your Peer-to-Peer App

Canonical: https://docs.projectbabbage.com/docs/quickstarts/sending-payments-through-your-peer-to-peer-app

A step-by-step tutorial for quickly integrating PeerPay into your peer-to-peer application to enable real-time micropayments on BSV. This guide covers setting up PeerPayClient, sending live payments, and handling incoming payments.

Payments are a key enabler for efficient transactions on BSV. In this guide, you’ll learn how to set up PeerPay to send live payments and handle incoming payments using both WebSocket and HTTP fallback methods. You will also see how to accept or reject payments as needed.

---

### 1. Prerequisites

- **BSV-Compatible Wallet:**  
  You’ll use this for key management, signing, and authentication.

- **Node.js & npm (or Yarn):**  
  Required for developing your app and managing dependencies.

- **PeerPay Client Library:**  
  Install the messaging client library with:
  ```bash
  npm install @bsv/message-box-client
  ```
- Basic JavaScript/TypeScript Knowledge:
Familiarity with Node.js development is assumed.
________________________________________
### 2. Set Up Your Project
1. **Initialize a New Project:**
```bash
mkdir my-payment-app && cd my-payment-app
npm init -y
```
2. **Install Dependencies:**
```bash
npm install @bsv/message-box-client @bsv/sdk
```
3. **Folder Structure (example):**
my-payment-app/
├─ package.json
├─ index.js
└─ …
________________________________________
### 3. Building the Payment Functionality
a. **Initialize PeerPay Client**
Below is an example of how to instantiate the PeerPayClient using a WalletClient. Adjust the wallet client initialization as needed:
```ts
import { PeerPayClient } from '@bsv/message-box-client'
import { WalletClient } from '@bsv/sdk'

// Example walletClient initialization
const walletClient = new WalletClient('auto')

// Instantiate the PeerPayClient with the public MessageBox Server endpoint.
const peerPayClient = new PeerPayClient({
  messageBoxHost: 'https://your-messagebox.example',
  walletClient,
  enableLogging: true  // Enable logging for debugging (disabled by default)
})

// Initialize the connection
await peerPayClient.initializeConnection()
```

b. **Sending a Payment**
Use the `sendLivePayment()` method to send a payment via WebSocket. If the live channel fails, the request falls back to HTTP automatically:
```ts
await peerPayClient.sendLivePayment({
  recipient: 'recipient_identity_key',  // Replace with the actual recipient's identity key
  amount: 1000  // Payment amount in satoshis
})
```

c. **Handling Live Incoming Payments**
Set up a listener to process incoming payments in real time using WebSocket:
```ts
await peerPayClient.listenForLivePayments({
  onPayment: (payment) => {
    console.log('Incoming Payment:', payment)
    // Process the incoming payment (update UI, trigger business logic, etc.)
  }
})
```

d. **Managing Payments via HTTP (Listing, Accepting, and Rejecting)**
In addition to live updates, you can retrieve pending payments over HTTP. Use `listIncomingPayments()` to fetch them and then process individual payments with `acceptPayment()` or `rejectPayment()`.
**Listing Incoming Payments**
```ts
const payments = await peerPayClient.listIncomingPayments()
console.log('HTTP Incoming Payments:', payments)
```

**Accepting a Payment**
```ts
// Assume payments is an array and we take the first payment for demonstration.
const paymentToAccept = payments[0]
if (paymentToAccept) {
  const acceptResult = await peerPayClient.acceptPayment(paymentToAccept)
  console.log('Payment accepted:', acceptResult)
}
```

**Rejecting a Payment**
```ts
// Assume payments is an array and we take the first payment for demonstration.
const paymentToReject = payments[0]
if (paymentToReject) {
  await peerPayClient.rejectPayment(paymentToReject)
  console.log('Payment rejected and refunded (if applicable).')
}
```
________________________________________
### 4. Testing Your Payment App
1. **Run Your Application:**
```bash
node index.js
```

2. **Verify Functionality:**
    - Confirm that live payments are sent and received.
    - Check that HTTP fallback correctly lists pending payments.
    - Validate that accepting or rejecting payments behaves as expected.
________________________________________
### 5. Next Steps & Resources
- **Enhance Your Payment Flow:**
Expand your app with improved error handling, UI integration, and support for payment confirmations.
- **Advanced Integration:**
Explore further configuration and advanced features by reviewing the full [PeerPay and MessageBox](https://github.com/bsv-blockchain/ts-stack/tree/main/packages/messaging/message-box-client) documentation.
- **Developer Support:**
Visit Project Babbage for community support and feedback.
________________________________________
### Conclusion
By following this guide, you’ve built a basic payment system using PeerPay on BSV. This Quick Start provides a solid foundation for sending live payments via WebSocket and managing transactions over HTTP. Use this foundation to further integrate payment capabilities into your broader peer-to-peer application.
Happy building and enjoy the seamless world of payments on BSV!

________________________________________
