docs
集成指南

快速入门

前提条件

在开始之前,您需要具备以下条件:

✓已关联到您账户的 X.509 客户端证书(PEM、RSA 2048、有效期 2 年)及其私钥
✓OAuth 凭证(clientId 和 clientSecret)

在 FyPay 控制面板 的 设置 → 凭证 中生成您的凭证。clientSecret 仅显示一次,请立即复制。

1. 配置环境

使用您的凭证创建 .env 文件:

FYPAY_CLIENT_ID=6967c0a0-3566-48d0-8c13-717038b52279
FYPAY_CLIENT_SECRET=your-client-secret
FYPAY_API_URL=https://api.fypay.me/api

将证书保存为 client.crt,将私钥保存为 client.key,放在项目目录中。证书仅用于生成令牌,在 TLS 握手中出示(mTLS)。

2. 安装依赖

npm install axios dotenv
pip install requests python-dotenv

3. 完整代码

以下示例演示认证、查询余额和创建 PIX 收款:

require('dotenv').config();
const axios = require('axios');
const fs = require('fs');
const https = require('https');

const API_URL = process.env.FYPAY_API_URL;

const mtlsAgent = new https.Agent({
  cert: fs.readFileSync('./client.crt'),
  key: fs.readFileSync('./client.key')
});

// 1. Get token (mTLS: certificate in the TLS handshake)
async function getToken() {
  const response = await axios.post(`${API_URL}/auth/token`, {
    clientId: process.env.FYPAY_CLIENT_ID,
    clientSecret: process.env.FYPAY_CLIENT_SECRET
  }, {
    httpsAgent: mtlsAgent,
    headers: { 'Content-Type': 'application/json' }
  });
  return response.data.access_token;
}

// 2. Check balance
async function getBalance(token) {
  const response = await axios.get(`${API_URL}/balance`, {
    headers: { 'Authorization': `Bearer ${token}` }
  });
  return response.data;
}

// 3. Create PIX charge
async function createPixCharge(token, value, description, externalId, payer) {
  const response = await axios.post(`${API_URL}/pix/cash-in`, {
    transaction: {
      value,
      description,
      externalId,
      expirationTime: 3600, // 1 hour
      generateQrCode: true
    },
    payer: {
      fullName: payer.name,
      document: payer.document
    }
  }, {
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    }
  });
  return response.data;
}

// Run
async function main() {
  try {
    // Authenticate
    console.log('Authenticating...');
    const token = await getToken();
    console.log('Token obtained successfully!');

    // Check balance
    console.log('\nChecking balance...');
    const balance = await getBalance(token);
    console.log(`Available balance: R$ ${balance.netBalance.toFixed(2)}`);

    // Create charge
    console.log('\nCreating PIX charge...');
    const charge = await createPixCharge(token, 100.00, 'Integration test', 'ORDER-001', {
      name: 'John Smith',
      document: '12345678909'
    });

    console.log(`\nCharge created!`);
    console.log(`ID: ${charge.transactionId}`);
    console.log(`Status: ${charge.status}`);
    console.log(`PIX Copy and Paste: ${charge.pixCode}`);
    console.log(`Expires at: ${charge.expirationDate}`);

  } catch (error) {
    console.error('Error:', error.response?.data || error.message);
  }
}

main();
import os
import requests
from dotenv import load_dotenv

load_dotenv()

API_URL = os.getenv('FYPAY_API_URL')

# 1. Get token (mTLS: certificate in the TLS handshake)
def get_token():
    response = requests.post(f'{API_URL}/auth/token',
        json={
            'clientId': os.getenv('FYPAY_CLIENT_ID'),
            'clientSecret': os.getenv('FYPAY_CLIENT_SECRET')
        },
        cert=('client.crt', 'client.key')
    )
    response.raise_for_status()
    return response.json()['access_token']

# 2. Check balance
def get_balance(token):
    response = requests.get(f'{API_URL}/balance',
        headers={'Authorization': f'Bearer {token}'}
    )
    response.raise_for_status()
    return response.json()

# 3. Create PIX charge
def create_pix_charge(token, value, description, external_id, payer_name, payer_document):
    response = requests.post(f'{API_URL}/pix/cash-in',
        json={
            'transaction': {
                'value': value,
                'description': description,
                'externalId': external_id,
                'expirationTime': 3600,
                'generateQrCode': True
            },
            'payer': {
                'fullName': payer_name,
                'document': payer_document
            }
        },
        headers={
            'Authorization': f'Bearer {token}',
            'Content-Type': 'application/json'
        }
    )
    response.raise_for_status()
    return response.json()

# Run
def main():
    try:
        # Authenticate
        print('Authenticating...')
        token = get_token()
        print('Token obtained successfully!')

        # Check balance
        print('\nChecking balance...')
        balance = get_balance(token)
        print(f"Available balance: R$ {balance['netBalance']:.2f}")

        # Create charge
        print('\nCreating PIX charge...')
        charge = create_pix_charge(
            token,
            100.00,
            'Integration test',
            'ORDER-001',
            'John Smith',
            '12345678909'
        )

        print(f"\nCharge created!")
        print(f"ID: {charge['transactionId']}")
        print(f"Status: {charge['status']}")
        print(f"PIX Copy and Paste: {charge['pixCode']}")
        print(f"Expires at: {charge['expirationDate']}")

    except requests.exceptions.RequestException as e:
        print(f'Error: {e.response.json() if e.response else e}')

if __name__ == '__main__':
    main()

4. 运行

node quickstart.js
python quickstart.py

预期输出:

Authenticating...
Token obtained successfully!

Checking balance...
Available balance: R$ 48734.90

Creating PIX charge...

Charge created!
ID: 7845
Status: PENDING
PIX Copy and Paste: 00020126580014br.gov.bcb.pix...
Expires at: 2024-01-20T14:30:00.000Z

5. 接收通知 (Webhook)

设置一个端点,在付款确认时接收通知:

// Express.js
app.post('/webhook/fypay', (req, res) => {
  const { event, transactionId, status, finalAmount } = req.body;

  if (event === 'CashIn' && status === 'CONFIRMED') {
    console.log(`Payment ${transactionId} confirmed: R$ ${finalAmount}`);
    // Update order in your system
  }

  res.status(200).send('OK');
});

在 FyPay 控制面板 的 设置 → Webhooks 中配置 webhook URL。 详情请参阅 Webhooks 指南。

后续步骤

故障排查

本页目录