<!-- ZenPays documentation · https://docs.zenpayz.com/docs/getting-started/quick-start -->

# Quick Start

Learn how to create your first payment with the ZenPays SDK.

## Initialize the Client

<Tabs groupId="language">
  <TabItem value="javascript" label="JavaScript" default>

```typescript
import { ZenPays } from '@zenxdigitalholdings/zenpays'

const zenpays = new ZenPays({
  apiKey: 'your-api-key',
})
```

  </TabItem>
  <TabItem value="python" label="Python">

```python
from zenpays import ZenPays

zenpays = ZenPays(api_key="your-api-key")
```

  </TabItem>
</Tabs>

## Create a Payment Intent

A payment intent represents a single payment flow. Create one to start accepting payments:

<Tabs groupId="language">
  <TabItem value="javascript" label="JavaScript" default>

```typescript
const paymentIntent = await zenpays.payments.createPaymentIntent({
  amount: 100,
  currency: 'INR',
  paymentMethod: 'upi',
  customerEmail: 'john@example.com',
  customerFirstName: 'John',
  customerLastName: 'Doe',
  customerCountry: 'IN',
  description: 'Premium subscription',
})

console.log('Payment Intent ID:', paymentIntent.intentId)
console.log('Payment Page URL:', paymentIntent.paymentPageUrl)
```

  </TabItem>
  <TabItem value="python" label="Python">

```python
payment_intent = zenpays.payments.create_payment_intent({
    "amount": 100,
    "currency": "INR",
    "paymentMethod": "upi",
    "customerEmail": "john@example.com",
    "customerFirstName": "John",
    "customerLastName": "Doe",
    "customerCountry": "IN",
    "description": "Premium subscription",
})

print("Payment Intent ID:", payment_intent["intentId"])
print("Payment Page URL:", payment_intent["paymentPageUrl"])
```

  </TabItem>
</Tabs>

## Confirm the Payment

Once the customer provides payment details, confirm the payment:

<Tabs groupId="language">
  <TabItem value="javascript" label="JavaScript" default>

```typescript
const result = await zenpays.payments.confirmPayment(paymentIntent.intentId, {
  customerDetails: {
    name: 'John Doe',
    email: 'john@example.com',
    address: { country: 'US' },
  },
  paymentMethodDetails: {
    type: 'upi',
    vpa: 'john@upi',
  },
})

if (result.status === 'succeeded') {
  console.log('Payment successful!')
}
else if (result.nextAction) {
  // Handle 3D Secure or other required actions
  console.log('Redirect to:', result.nextAction.redirectUrl)
}
```

  </TabItem>
  <TabItem value="python" label="Python">

```python
result = zenpays.payments.confirm_payment(
    payment_intent["intent_id"],
    {
        "customer_details": {
            "name": "John Doe",
            "email": "john@example.com",
            "address": {"country": "US"},
        },
        "payment_method_details": {
            "type": "upi",
            "vpa": "john@upi",
        },
    },
)

if result["status"] == "succeeded":
    print("Payment successful!")
elif "next_action" in result:
    # Handle 3D Secure or other required actions
    print("Redirect to:", result["next_action"]["redirect_url"])
```

  </TabItem>
</Tabs>

## Check Payment Status

<Tabs groupId="language">
  <TabItem value="javascript" label="JavaScript" default>

```typescript
const intent = await zenpays.payments.getPaymentIntent(paymentIntent.intentId)

console.log('Status:', intent.status)
// 'pending' | 'processing' | 'succeeded' | 'failed' | 'cancelled'
```

  </TabItem>
  <TabItem value="python" label="Python">

```python
intent = zenpays.payments.get_payment_intent(payment_intent["intent_id"])

print("Status:", intent["status"])
# 'pending' | 'processing' | 'succeeded' | 'failed' | 'cancelled'
```

  </TabItem>
</Tabs>

## Handle Webhooks

Set up webhooks to receive real-time payment updates:

<Tabs groupId="language">
  <TabItem value="javascript" label="JavaScript" default>

```typescript
// Register a webhook endpoint
await zenpays.merchants.createWebhook({
  url: 'https://your-site.com/webhooks/zenpays',
  events: [
    'payment.intent.succeeded',
    'payment.intent.failed',
    'refund.completed',
  ],
})
```

  </TabItem>
  <TabItem value="python" label="Python">

```python
# Register a webhook endpoint
zenpays.merchants.create_webhook({
    "url": "https://your-site.com/webhooks/zenpays",
    "events": [
        "payment.intent.succeeded",
        "payment.intent.failed",
        "refund.completed",
    ],
})
```

  </TabItem>
</Tabs>

## Error Handling

The SDK throws specific error types for different scenarios:

<Tabs groupId="language">
  <TabItem value="javascript" label="JavaScript" default>

```typescript
import { PaymentError, ValidationError, ZenPaysError } from '@zenxdigitalholdings/zenpays'

try {
  await zenpays.payments.createPaymentIntent({
    amount: 1000,
    currency: 'USD',
  })
}
catch (error) {
  if (error instanceof ValidationError) {
    console.error('Validation failed:', error.message)
  }
  else if (error instanceof PaymentError) {
    console.error('Payment failed:', error.message)
  }
  else if (error instanceof ZenPaysError) {
    console.error('API error:', error.message, error.code)
  }
}
```

  </TabItem>
  <TabItem value="python" label="Python">

```python
from zenpays.errors import PaymentError, ValidationError, ZenPaysError

try:
    zenpays.payments.create_payment_intent({
        "amount": 1000,
        "currency": "USD",
    })
except ValidationError as e:
    print(f"Validation failed: {e.message}")
except PaymentError as e:
    print(f"Payment failed: {e.message}")
except ZenPaysError as e:
    print(f"API error: {e.message} [{e.code}]")
```

  </TabItem>
</Tabs>

## Complete Example

Here's a complete example bringing it all together:

<Tabs groupId="language">
  <TabItem value="javascript" label="JavaScript" default>

```typescript
import { ZenPays, ZenPaysError } from '@zenxdigitalholdings/zenpays'

async function processPayment() {
  const zenpays = new ZenPays({
    apiKey: process.env.ZENPAYS_API_KEY!,
  })

  try {
    // 1. Create payment intent
    const intent = await zenpays.payments.createPaymentIntent({
      amount: 2999,
      currency: 'INR',
      paymentMethod: 'upi',
      customerEmail: 'jane@example.com',
      customerFirstName: 'Jane',
      customerLastName: 'Smith',
      customerCountry: 'IN',
      description: 'Pro Plan - Monthly',
    })

    // 2. Confirm with payment details
    const result = await zenpays.payments.confirmPayment(intent.intentId, {
      customerDetails: {
        name: 'Jane Smith',
        email: 'jane@example.com',
        address: { country: 'US' },
      },
      paymentMethodDetails: {
        type: 'upi',
        vpa: 'jane@upi',
      },
    })

    // 3. Handle result
    if (result.status === 'succeeded') {
      console.log('Payment completed successfully!')
      console.log('Transaction ID:', result.externalTransactionId)
    }
    else if (result.nextAction?.type === 'redirect') {
      console.log('3D Secure required, redirect to:', result.nextAction.redirectUrl)
    }
  }
  catch (error) {
    if (error instanceof ZenPaysError) {
      console.error(`Error [${error.code}]: ${error.message}`)
    }
    throw error
  }
}

processPayment()
```

  </TabItem>
  <TabItem value="python" label="Python">

```python
import os
from zenpays import ZenPays
from zenpays.errors import ZenPaysError

def process_payment():
    zenpays = ZenPays(api_key=os.environ["ZENPAYS_API_KEY"])

    try:
        # 1. Create payment intent
        intent = zenpays.payments.create_payment_intent({
            "amount": 2999,
            "currency": "INR",
            "paymentMethod": "upi",
            "customerEmail": "jane@example.com",
            "customerFirstName": "Jane",
            "customerLastName": "Smith",
            "customerCountry": "IN",
            "description": "Pro Plan - Monthly",
        })

        # 2. Confirm with payment details
        result = zenpays.payments.confirm_payment(
            intent["intent_id"],
            {
                "customer_details": {
                    "name": "Jane Smith",
                    "email": "jane@example.com",
                    "address": {"country": "US"},
                },
                "payment_method_details": {
                    "type": "upi",
                    "vpa": "jane@upi",
                },
            },
        )

        # 3. Handle result
        if result["status"] == "succeeded":
            print("Payment completed successfully!")
            print("Transaction ID:", result["external_transaction_id"])
        elif result.get("next_action", {}).get("type") == "redirect":
            print("3D Secure required, redirect to:", result["next_action"]["redirect_url"])

    except ZenPaysError as error:
        print(f"Error [{error.code}]: {error.message}")
        raise

if __name__ == "__main__":
    process_payment()
```

  </TabItem>
</Tabs>

## Next Steps

- [Configuration](/docs/getting-started/configuration) - Customize SDK behavior
- [Payments API](/docs/api-reference/payments) - Explore all payment methods
- [Error Handling](/docs/guides/error-handling) - Handle errors gracefully
