### Install Yoco E-commerce Plugins Source: https://context7.com/context7/developer_yoco/llms.txt Instructions for installing and configuring Yoco payment gateway plugins on popular e-commerce platforms including WooCommerce, Wix, and Shopify. These steps enable immediate payment acceptance without custom development. ```bash # WooCommerce Installation # 1. Navigate to WordPress admin panel # 2. Go to Plugins > Add New # 3. Search for "Yoco Payment Gateway" # 4. Install and activate the plugin # 5. Configure with Yoco merchant credentials # Wix Integration # 1. Open Wix site editor # 2. Navigate to Settings > Accept Payments # 3. Click "Add Payment Method" # 4. Select "Yoco" from the list # 5. Connect Yoco account and authorize # Shopify Integration # 1. Go to Shopify Admin > Settings > Payments # 2. Under "Alternative payment methods", click "Choose alternative payment" # 3. Search for and select "Yoco" # 4. Complete merchant account connection # Expected: Payment gateway appears at checkout ``` -------------------------------- ### Configure Yoco Environment Variables Source: https://context7.com/context7/developer_yoco/llms.txt Example configuration for environment variables in a .env file for Yoco integration. It includes placeholders for public key, secret key, webhook secret, and environment type (test/live). This setup is crucial for authenticating API requests and verifying webhooks. ```bash # .env file configuration # Development environment YOCO_PUBLIC_KEY=pk_test_your_test_public_key_here YOCO_SECRET_KEY=sk_test_your_test_secret_key_here YOCO_WEBHOOK_SECRET=whsec_test_your_webhook_secret_here YOCO_ENV=test # Production environment # YOCO_PUBLIC_KEY=pk_live_your_live_public_key_here ``` -------------------------------- ### Yoco Checkout API - Custom Payment Integration Source: https://context7.com/context7/developer_yoco/llms.txt Integrate Yoco's Checkout API to create custom payment flows on your website. This example demonstrates initializing the SDK, opening the payment modal, and sending a payment token to your backend for charge creation. ```APIDOC ## Yoco Checkout API - Custom Payment Integration ### Description This API allows for direct integration to accept payments on custom websites, providing full control over the payment experience and enabling real-time event notifications. ### Method POST (Implicitly, through frontend JavaScript and backend interaction) ### Endpoint Frontend: N/A (uses SDK) Backend: `/api/charge` (example) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body (for backend `/api/charge` endpoint) - **token** (string) - Required - The payment token received from the Yoco SDK. - **amountInCents** (integer) - Required - The amount to charge in the smallest currency unit (e.g., cents). - **currency** (string) - Required - The ISO currency code (e.g., 'ZAR'). ### Request Example (Frontend - Yoco SDK Initialization and Popup) ```javascript const yoco = new YocoSDK({ publicKey: 'pk_live_your_public_key_here' }); const checkoutButton = document.getElementById('checkout-btn'); checkoutButton.addEventListener('click', async () => { try { const result = await yoco.showPopup({ amountInCents: 50000, // R500.00 in cents currency: 'ZAR', name: 'Premium Subscription', description: 'Monthly subscription payment', metadata: { orderId: 'ORD-12345', customerId: 'CUST-67890' } }); // ... send token to backend ... } catch (error) { console.error('Payment failed:', error.message); } }); ``` ### Request Example (Backend - `/api/charge`) ```json { "token": "tok_example123", "amountInCents": 50000, "currency": "ZAR" } ``` ### Response #### Success Response (200) (from backend `/api/charge`) - **id** (string) - The unique identifier for the charge. - **status** (string) - The status of the charge (e.g., 'successful'). - **amount** (integer) - The charged amount in cents. - **currency** (string) - The ISO currency code. - **createdDate** (string) - The date and time the charge was created. - **metadata** (object) - Any metadata associated with the charge. #### Response Example (from backend `/api/charge`) ```json { "id": "ch_abc123", "status": "successful", "amount": 50000, "currency": "ZAR", "createdDate": "2025-10-11T10:30:00Z", "metadata": { "orderId": "ORD-12345" } } ``` ``` -------------------------------- ### GET /v1/charges/{chargeId} Source: https://context7.com/context7/developer_yoco/llms.txt Retrieves the current status of a payment charge using its ID. Useful for reconciliation and order management. ```APIDOC ## GET /v1/charges/{chargeId} ### Description This endpoint allows you to retrieve the details and current status of a specific payment charge. ### Method GET ### Endpoint `/v1/charges/{chargeId}` ### Parameters #### Path Parameters - **chargeId** (string) - Required - The ID of the charge to retrieve. ### Response #### Success Response (200) - **id** (string) - The unique identifier for the charge. - **status** (string) - The current status of the charge (e.g., 'successful', 'pending', 'failed'). - **amount** (integer) - The amount of the charge in cents. - **currency** (string) - The currency of the charge (e.g., 'ZAR'). - **createdDate** (string) - The date and time the charge was created in ISO 8601 format. - **metadata** (object) - Optional - Additional metadata associated with the charge. - **orderId** (string) - Optional - The order ID associated with the charge. #### Response Example ```json { "id": "ch_abc123", "status": "successful", "amount": 50000, "currency": "ZAR", "createdDate": "2025-10-11T10:30:00Z", "metadata": { "orderId": "ORD-12345" } } ``` #### Error Response - **message** (string) - Description of the error if the charge retrieval fails. ``` -------------------------------- ### Check Payment Status with Yoco API using JavaScript Source: https://context7.com/context7/developer_yoco/llms.txt Implement a function to retrieve the current status of a Yoco payment charge. This function makes a GET request to the Yoco API using the charge ID. It returns detailed information about the charge, including its status, amount, currency, and creation date. Requires a secret key for authorization. ```javascript // Check payment status async function getChargeStatus(chargeId) { try { const response = await fetch(`https://online.yoco.com/v1/charges/${chargeId}`, { method: 'GET', headers: { 'Authorization': `Bearer sk_live_your_secret_key_here` } }); const charge = await response.json(); if (!response.ok) { throw new Error(charge.message || 'Failed to retrieve charge'); } return { id: charge.id, status: charge.status, amount: charge.amount, currency: charge.currency, createdDate: charge.createdDate, metadata: charge.metadata }; } catch (error) { console.error('Status check failed:', error); throw error; } } // Usage const status = await getChargeStatus('ch_abc123'); console.log(`Charge ${status.id}: ${status.status}`); // Expected response: // { // "id": "ch_abc123", // "status": "successful", // "amount": 50000, // "currency": "ZAR", // "createdDate": "2025-10-11T10:30:00Z", // "metadata": { "orderId": "ORD-12345" } // } ``` -------------------------------- ### Environment Configuration Source: https://context7.com/context7/developer_yoco/llms.txt Instructions for configuring API keys and environment settings for development and production using a .env file. ```APIDOC ## Environment Configuration ### Description Configure your Yoco API credentials and environment settings by creating or updating a `.env` file in your project's root directory. ### Development Environment ```bash # .env file configuration YOCO_PUBLIC_KEY=pk_test_your_test_public_key_here YOCO_SECRET_KEY=sk_test_your_test_secret_key_here YOCO_WEBHOOK_SECRET=whsec_test_your_webhook_secret_here YOCO_ENV=test ``` ### Production Environment ```bash # .env file configuration YOCO_PUBLIC_KEY=pk_live_your_live_public_key_here YOCO_SECRET_KEY=sk_live_your_live_secret_key_here YOCO_WEBHOOK_SECRET=whsec_live_your_webhook_secret_here YOCO_ENV=live ``` ### Parameters - **YOCO_PUBLIC_KEY** (string) - Your Yoco public API key for the current environment. - **YOCO_SECRET_KEY** (string) - Your Yoco secret API key for the current environment. - **YOCO_WEBHOOK_SECRET** (string) - The shared secret used to verify webhook signatures. - **YOCO_ENV** (string) - Specifies the environment ('test' or 'live'). ``` -------------------------------- ### Load Yoco Configuration from Environment Variables (JavaScript) Source: https://context7.com/context7/developer_yoco/llms.txt Loads Yoco API keys and environment settings from .env file using dotenv. Initializes a configuration object with public key, secret key, webhook secret, environment, and API base URL. Includes validation to ensure essential API keys are present. ```javascript // Configuration loader import dotenv from 'dotenv'; dotenv.config(); export const yocoConfig = { publicKey: process.env.YOCO_PUBLIC_KEY, secretKey: process.env.YOCO_SECRET_KEY, webhookSecret: process.env.YOCO_WEBHOOK_SECRET, environment: process.env.YOCO_ENV || 'test', apiBaseUrl: process.env.YOCO_ENV === 'live' ? 'https://online.yoco.com/v1' : 'https://sandbox.yoco.com/v1' }; // Validation if (!yocoConfig.publicKey || !yocoConfig.secretKey) { throw new Error('Missing required Yoco API keys'); } ``` -------------------------------- ### Yoco Checkout API for Custom Payment Integration Source: https://context7.com/context7/developer_yoco/llms.txt Client-side JavaScript code to initialize the Yoco SDK, create a payment form, and handle the payment process using the Yoco Checkout API. It opens a payment modal for users and sends a token to a backend endpoint for charge creation upon successful payment. Dependencies include the Yoco SDK and a backend endpoint for processing the payment token. ```javascript // Initialize Yoco Checkout const yoco = new YocoSDK({ publicKey: 'pk_live_your_public_key_here' }); // Create payment form const checkoutButton = document.getElementById('checkout-btn'); checkoutButton.addEventListener('click', async () => { try { // Open Yoco payment modal const result = await yoco.showPopup({ amountInCents: 50000, // R500.00 in cents currency: 'ZAR', name: 'Premium Subscription', description: 'Monthly subscription payment', metadata: { orderId: 'ORD-12345', customerId: 'CUST-67890' } }); // Send token to backend for charge creation const response = await fetch('/api/charge', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: result.id, amountInCents: 50000, currency: 'ZAR' }) }); const charge = await response.json(); if (charge.status === 'successful') { console.log('Payment successful:', charge.id); // Redirect to success page window.location.href = '/payment/success'; } } catch (error) { console.error('Payment failed:', error.message); // Handle payment failure } }); // Expected output on success: // { id: 'ch_abc123', status: 'successful', amount: 50000, currency: 'ZAR' } ``` -------------------------------- ### Backend Charge Creation with Yoco API (Node.js) Source: https://context7.com/context7/developer_yoco/llms.txt Node.js/Express backend code that implements a /api/charge endpoint to process payment tokens received from the frontend. It uses the Yoco API to create a charge and stores the transaction details in a database. This snippet requires Node.js, Express, and a database connection. ```javascript // Node.js/Express backend implementation import express from 'express'; import fetch from 'node-fetch'; const app = express(); app.use(express.json()); app.post('/api/charge', async (req, res) => { const { token, amountInCents, currency } = req.body; try { const response = await fetch('https://online.yoco.com/v1/charges/', { method: 'POST', headers: { 'Authorization': `Bearer sk_live_your_secret_key_here`, 'Content-Type': 'application/json' }, body: JSON.stringify({ token: token, amountInCents: amountInCents, currency: currency }) }); const charge = await response.json(); if (!response.ok) { throw new Error(charge.message || 'Charge failed'); } // Store charge details in database await db.charges.create({ chargeId: charge.id, amount: charge.amount, status: charge.status, createdAt: charge.createdDate }); res.json(charge); } catch (error) { console.error('Charge creation failed:', error); res.status(400).json({ error: error.message }); } }); // Expected response: // { // "id": "ch_abc123", // "status": "successful", // "amount": 50000, // "currency": "ZAR", // "createdDate": "2025-10-11T10:30:00Z", // "metadata": { "orderId": "ORD-12345" } // } ``` -------------------------------- ### Backend Charge Creation API Source: https://context7.com/context7/developer_yoco/llms.txt This endpoint on your backend processes the payment token received from the Yoco Checkout API to create a charge. ```APIDOC ## Backend Charge Creation API ### Description This backend endpoint receives a payment token from the frontend, uses it to create a charge via the Yoco API, and optionally stores the charge details. ### Method POST ### Endpoint `/api/charge` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **token** (string) - Required - The payment token generated by the Yoco SDK. - **amountInCents** (integer) - Required - The amount for the charge in cents. - **currency** (string) - Required - The ISO currency code for the charge. ### Request Example ```json { "token": "tok_example123", "amountInCents": 50000, "currency": "ZAR" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the created charge. - **status** (string) - The status of the charge (e.g., 'successful'). - **amount** (integer) - The amount charged in cents. - **currency** (string) - The ISO currency code. - **createdDate** (string) - The timestamp when the charge was created. - **metadata** (object) - Any metadata associated with the charge. #### Response Example ```json { "id": "ch_abc123", "status": "successful", "amount": 50000, "currency": "ZAR", "createdDate": "2025-10-11T10:30:00Z", "metadata": { "orderId": "ORD-12345" } } ``` #### Error Response (400) - **error** (string) - A message describing the error. #### Error Response Example ```json { "error": "Charge failed: Invalid token" } ``` ``` -------------------------------- ### Handle Yoco Webhooks with Node.js Source: https://context7.com/context7/developer_yoco/llms.txt Set up an Express.js endpoint to receive and verify Yoco webhook events. It parses incoming JSON payloads, verifies the signature using a webhook secret, and handles different event types like payment success, failure, and refunds. Requires the 'crypto' module and Express.js. ```javascript import crypto from 'crypto'; app.post('/webhooks/yoco', express.raw({ type: 'application/json' }), (req, res) => { const signature = req.headers['x-yoco-signature']; const webhookSecret = process.env.YOCO_WEBHOOK_SECRET; // Verify webhook signature const expectedSignature = crypto .createHmac('sha256', webhookSecret) .update(req.body) .digest('hex'); if (signature !== expectedSignature) { return res.status(401).json({ error: 'Invalid signature' }); } const event = JSON.parse(req.body); // Handle different event types switch (event.type) { case 'payment.succeeded': handlePaymentSuccess(event.data); break; case 'payment.failed': handlePaymentFailure(event.data); break; case 'refund.succeeded': handleRefundSuccess(event.data); break; default: console.log('Unhandled event type:', event.type); } res.json({ received: true }); }); async function handlePaymentSuccess(payment) { // Update order status await db.orders.update( { paymentStatus: 'paid', paidAt: new Date() }, { where: { chargeId: payment.id } } ); // Send confirmation email await emailService.sendReceipt({ to: payment.metadata.customerEmail, orderId: payment.metadata.orderId, amount: payment.amount / 100 }); console.log(`Payment ${payment.id} processed successfully`); } // Example webhook payload: // { // "type": "payment.succeeded", // "data": { // "id": "ch_abc123", // "amount": 50000, // "currency": "ZAR", // "status": "successful", // "metadata": { "orderId": "ORD-12345", "customerEmail": "user@example.com" } // } // } ``` -------------------------------- ### Process Refunds with Yoco API using JavaScript Source: https://context7.com/context7/developer_yoco/llms.txt Implement a function to process full or partial refunds for Yoco transactions. This function makes a POST request to the Yoco API, including the charge ID and an optional amount in cents for partial refunds. It handles API responses and updates a local database. Requires a secret key for authorization. ```javascript // Refund API implementation async function processRefund(chargeId, amountInCents = null) { try { const response = await fetch(`https://online.yoco.com/v1/charges/${chargeId}/refund`, { method: 'POST', headers: { 'Authorization': `Bearer sk_live_your_secret_key_here`, 'Content-Type': 'application/json' }, body: JSON.stringify({ // Omit amount for full refund, include for partial ...(amountInCents && { amountInCents }) }) }); const refund = await response.json(); if (!response.ok) { throw new Error(refund.message || 'Refund failed'); } // Update database await db.refunds.create({ refundId: refund.id, chargeId: chargeId, amount: refund.amount, status: refund.status, createdAt: new Date() }); return refund; } catch (error) { console.error('Refund processing failed:', error); throw error; } } // Usage examples // Full refund const fullRefund = await processRefund('ch_abc123'); // Partial refund (R100 of R500 charge) const partialRefund = await processRefund('ch_abc123', 10000); // Expected response: // { // "id": "rf_xyz789", // "chargeId": "ch_abc123", // "amount": 10000, // "status": "successful", // "createdDate": "2025-10-11T14:20:00Z" // } ``` -------------------------------- ### POST /webhooks/yoco Source: https://context7.com/context7/developer_yoco/llms.txt Endpoint to receive real-time notifications about payment events. It verifies the signature and handles different event types like payment success, failure, and refunds. ```APIDOC ## POST /webhooks/yoco ### Description This endpoint receives real-time payment notifications from Yoco. It verifies the incoming webhook signature using a shared secret and processes different event types. ### Method POST ### Endpoint `/webhooks/yoco` ### Parameters #### Headers - **x-yoco-signature** (string) - Required - The signature of the webhook payload for verification. #### Request Body - **type** (string) - Required - The type of event that occurred (e.g., `payment.succeeded`). - **data** (object) - Required - Contains the event-specific data. - **id** (string) - Required - The unique identifier for the event. - **amount** (integer) - Required - The amount of the transaction in cents. - **currency** (string) - Required - The currency of the transaction (e.g., 'ZAR'). - **status** (string) - Required - The status of the payment (e.g., 'successful'). - **metadata** (object) - Optional - Additional metadata associated with the payment. - **orderId** (string) - Optional - The order ID associated with the payment. - **customerEmail** (string) - Optional - The customer's email address. ### Request Example ```json { "type": "payment.succeeded", "data": { "id": "ch_abc123", "amount": 50000, "currency": "ZAR", "status": "successful", "metadata": { "orderId": "ORD-12345", "customerEmail": "user@example.com" } } } ``` ### Response #### Success Response (200) - **received** (boolean) - Indicates if the webhook was successfully received. #### Response Example ```json { "received": true } ``` #### Error Response (401) - **error** (string) - Indicates an invalid signature. ```json { "error": "Invalid signature" } ``` ``` -------------------------------- ### POST /v1/charges/{chargeId}/refund Source: https://context7.com/context7/developer_yoco/llms.txt Processes full or partial refunds for completed transactions. Requires the charge ID and optionally the amount to refund in cents. ```APIDOC ## POST /v1/charges/{chargeId}/refund ### Description This endpoint allows you to process refunds for Yoco charges. You can issue a full refund by omitting the amount, or a partial refund by specifying the amount in cents. ### Method POST ### Endpoint `/v1/charges/{chargeId}/refund` ### Parameters #### Path Parameters - **chargeId** (string) - Required - The ID of the charge to refund. #### Request Body - **amountInCents** (integer) - Optional - The amount to refund in cents. If omitted, a full refund is processed. ### Request Example ```json { "amountInCents": 10000 } ``` ### Response #### Success Response (200) - **id** (string) - The unique ID of the refund. - **chargeId** (string) - The ID of the original charge that was refunded. - **amount** (integer) - The amount refunded in cents. - **status** (string) - The status of the refund (e.g., 'successful'). - **createdDate** (string) - The date and time the refund was created in ISO 8601 format. #### Response Example ```json { "id": "rf_xyz789", "chargeId": "ch_abc123", "amount": 10000, "status": "successful", "createdDate": "2025-10-11T14:20:00Z" } ``` #### Error Response - **message** (string) - Description of the error if the refund fails. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.