Sobes.tech
Middle

How would you implement a common component for different payment providers with different endpoints, parameters, and response formats, but a unified UI?

sobes.tech AI

Answer from AI

To implement a common component with a unified UI that works with different payment providers, you can use the adapter or strategy pattern.

  1. Create an interface or abstraction for interacting with the provider (methods for sending payments, checking status, etc.).
  2. Implement a separate adapter for each provider, which knows its endpoints, parameters, and response formats.
  3. The UI component works with the abstraction, independent of the specific implementation.

Example in React (simplified):

// Provider interface
class PaymentProvider {
  pay(paymentData) { throw 'Not implemented'; }
}

// Adapter for Provider A
class ProviderA extends PaymentProvider {
  pay(paymentData) {
    return fetch('https://api.providerA.com/pay', {
      method: 'POST',
      body: JSON.stringify(paymentData),
    }).then(res => res.json());
  }
}

// Adapter for Provider B
class ProviderB extends PaymentProvider {
  pay(paymentData) {
    // different request and processing format
  }
}

// UI component
function PaymentComponent({ provider }) {
  const handlePay = async () => {
    const result = await provider.pay({ amount: 100 });
    console.log(result);
  };

  return <button onClick={handlePay}>Pay</button>;
}

// Usage
const provider = new ProviderA();
<PaymentComponent provider={provider} />

This approach allows adding support for new providers without changing the UI component.

How would you implement a common component for… - sobes.tech