# Payments Configuration

> How to configure supported payment gateways, refunds, and payment processing flows in the Temp-Number App backend.



## Accept Payments from Users

Each payment gateway has its own method for handling payments and refunds. The Temp-Number Backend provides a unified interface for managing payments and refunds for multiple payment gateways. It includes support for popular gateways and can be extended to [support additional ones](#adding-custom-payment-gateways).

## Supported Payment Gateways

The Temp-Number Backend currently supports the following payment gateways:

1. [Stripe](#stripe)
2. [PayPal](#paypal)
3. [Cryptomus](#cryptomus)
4. [Apple App Store](#apple-app-store)
5. [Google Play Store](#google-play-store)

## How It Works

When a user makes a payment, the backend verifies the transaction and creates a record in the `tn_payments` database table. This record contains payment information including:

- Unique payment ID
- Firebase user ID
- Payment gateway identifier
- Payment amount
- Synchronization status (`is_synced` flag)

The backend attempts to synchronize the payment with the Platfone Retail API immediately. If synchronization fails, the `is_synced` flag remains `false`, and a background job periodically retries synchronization for unprocessed payments.

A positive amount increases the balance, while a negative amount decreases it (for refunds).

## Payment Gateways Webhook Endpoints

Each payment gateway requires a webhook endpoint URL to notify the Temp-Number Backend of payment events. These URLs must be configured in the respective payment gateway dashboards to ensure proper payment processing.

Table of webhook endpoints:

| Payment Gateway   | Webhook Endpoint URL Path         |
| ----------------- | --------------------------------- |
| Stripe            | `/stripe-handleWebhookEvents`     |
| Apple App Store   | `/appstore-handleWebhookEvents`   |
| Google Play Store | `/googleplay-handleWebhookEvents` |
| PayPal            | `/paypal-handleWebhookEvents`     |
| Cryptomus         | `/cryptomus-handleWebhookEvents`  |
| Payeer            | `/payeer-handleWebhookEvents`     |
| Anypay            | `/anypay-handleWebhookEvents`     |



Given Backend URL `https://your-domain.com/api/`, the full Stripe webhook URL would be:

```bash
https://your-domain.com/api/stripe-handleWebhookEvents
```




## Stripe

The Temp-Number Backend supports payments via the Stripe payment gateway.

**Basic Process Overview:**

- The app requests a payment intent from the Temp-Number Backend.
- The app sends the payment intent to Stripe.
- Stripe processes the payment and sends a webhook event to the Temp-Number Backend.
- The payment is verified and added to the database with either a positive amount (for payments) or a negative amount (for refunds).

**Configuration:**

1. Set `STRIPE_ENABLED=true` during the Temp-Number Backend installation.
2. Set up the Stripe webhook:
    - Go to the [Stripe Dashboard](https://dashboard.stripe.com/webhooks)
 and add a new endpoint.
    - Set the endpoint URL to

      ```curl
      https://<your-backend-url>/stripe-handleWebhookEvents
      ```

    - Select the `payment_intent.amount_capturable_updated`, `charge.refunded` and `review.closed` events, then click "Add endpoint" to save.
    - Click "Reveal" to get the signing secret, which you'll set as the `STRIPE_WEBHOOK_SECRET` during the Temp-Number Backend installation.
3. Get your Stripe API keys:
   - Go to [Stripe Dashboard](https://dashboard.stripe.com/apikeys)
 to get your `Publishable key` and `Secret key`. You will be prompted for them during the backend installation.
4. For instructions on configuring Stripe payments in your app, refer to the example apps:
   - [iOS example app Stripe configuration](https://github.com/platfone-com/temp-number-ios#stripe)

   - [Android example Stripe configuration](https://github.com/platfone-com/temp-number-android#stripe-payments-optional)



> **Tip**



- You can test Stripe payments using [Stripe Test Cards](https://stripe.com/docs/testing#cards)
.
- To test webhooks locally, consider using the [Stripe CLI](https://docs.stripe.com/stripe-cli/use-cli#forward-events-to-your-local-webhook-endpoint)
.



## PayPal

The Temp-Number Backend supports payments via the [PayPal Advanced Checkout integration](https://developer.paypal.com/docs/checkout/advanced/)
.

**Basic Process Overview:**

1. **Client-Side Integration:**
   - The app integrates PayPal's JavaScript SDK to render PayPal buttons and card fields.
   - Users interact with these components to initiate payments.

2. **Server-Side Order Creation:**
   - The app sends a request to a Temp-Number Backend to create an order.
   - The Backend utilizes PayPal's Orders API to create the order and returns an `orderID` to the client.

3. **Payment Approval:**
   - The client uses the `orderID` to approve the payment through PayPal's SDK components.

4. **Order Capture:**
   - Upon approval, the client notifies the Temp-Number Backend to capture the order.
   - The Backend captures the payment via PayPal's Orders API and updates the database with the transaction details, recording positive amount.

5. **Webhook Notification:**
   - PayPal sends a webhook `PAYMENT.CAPTURE.REFUNDED` event to a designated Backend endpoint upon payment refund.
   - The Backend verifies the event and updates the database with the transaction details, recording negative amount.

**Configuration:**

1. **Enable PayPal Integration:**
   - Set `PAYPAL_ENABLED=true` during the Temp-Number Backend installation.

2. **Obtain PayPal API Credentials:**
   - Log in to the [PayPal Developer Dashboard](https://developer.paypal.com/dashboard/)
.
   - Navigate to **Apps & Credentials** and create a new REST API app.
   - Retrieve your `Client ID` and `Secret`, which will be required during the backend installation.

3. **Set Up Webhook:**
   - In the PayPal Developer Dashboard, go to **Webhooks** under your application settings.
   - Set the endpoint URL to

      ```curl
      https://<your-backend-url>/paypal-handleWebhookEvents
      ```

   - Subscribe to the following events:
     - "Payment capture refunded" `PAYMENT.CAPTURE.REFUNDED` (for refunds)
   - Save the webhook configuration.

## Cryptomus

The Temp-Number Backend supports payments via the Cryptomus cryptocurrency payment gateway.

**Basic Process Overview:**

1. **Client-Side Integration:**
   - The app integrates Cryptomus's payment interface to facilitate cryptocurrency transactions.
   - Users initiate payments through the app, selecting their preferred cryptocurrency.

2. **Server-Side Invoice Creation:**
   - The app sends a request to a Temp-Number Backend to create a payment invoice.
   - The Backend utilizes Cryptomus's API to generate the invoice and returns the payment details to the client.

3. **Payment Processing:**
   - Users complete the payment using the provided cryptocurrency details.
   - Cryptomus processes the payment and confirms the transaction.

4. **Webhook Notification:**
   - Cryptomus sends a webhook event to a designated Temp-Number Backend endpoint upon payment completion.
   - The Backend verifies the payment and updates the database with the transaction details, recording positive amounts for payments and negative amounts for refunds.

**Configuration:**

1. **Enable Cryptomus Integration:**
   - Set `CRYPTOMUS_ENABLED=true` during the Temp-Number Backend installation.

2. **Obtain Cryptomus API Credentials:**
   - Sign up on the [Cryptomus website](https://cryptomus.com/gateway)
.
   - Create a new merchant project to manage your payments.
   - Generate your API keys from the merchant dashboard; these will be required during the backend installation.

3. **Set Up Webhook:**
   - In your Cryptomus merchant dashboard, navigate to the webhook settings.
   - Set the endpoint URL to

      ```curl
      https://<your-backend-url>/cryptomus-handleWebhookEvents
      ```

   - Configure the webhook to listen for relevant events, such as payment completions and refunds.
   - Save the webhook configuration.

4. **Client-Side Integration:**
   - Integrate Cryptomus's payment interface into your app to facilitate cryptocurrency transactions.
   - Ensure the client-side logic handles the initiation of payments and interacts with the Temp-Number Backend as needed.

For a visual walkthrough, you might find the following video helpful: [https://www.youtube.com/watch?v=x71wO2kDRiI](https://www.youtube.com/watch?v=x71wO2kDRiI)


## Apple App Store

The Temp-Number Backend supports in-app purchases through the Apple App Store.

**Basic Process Overview:**

- The payment transaction provided by the app is verified and added to the database with a positive amount.
- When a `REFUND` [Apple App Store notification](https://developer.apple.com/documentation/appstoreservernotifications/app-store-server-notifications-v2)
 is received, it is verified and added to the database with a negative amount.

**Configuration:**

1. Set `APPSTORE_ENABLED=true` during the Temp-Number Backend installation.
2. Set up the notification URL in App Store Connect:
    - Go to [App Store Connect](https://appstoreconnect.apple.com/apps)
.
    - In the `App Information` section set the notification URL:

      ```curl
      https://<your-backend-url>/appstore-handleWebhookEvents
      ```

3. For instructions on configuring in-app purchases in your app, refer to the [Apple in-app purchases ](https://github.com/platfone-com/temp-number-ios?tab=readme-ov-file#apple-in-app-purchases-optional)
 section of the iOS example app documentation.

## Google Play Store

The Temp-Number Backend supports in-app purchases through the Google Play Store.

**Basic Process Overview:**

- The payment transaction provided by the app is verified and added to the database with a positive amount.
- When a `ONE_TIME_PRODUCT_REFUNDED` [Google Play Store notification](https://developer.android.com/google/play/billing/getting-ready#configure-rtdn)
 is received, it is verified and added to the database with a negative amount.

**Configuration:**

1. Set `GOOGLE_PLAY_ENABLED=true` during the Temp-Number Backend installation.

2. Go to the [Google Play Console](https://play.google.com/apps/publish/)
 and select your app.

3. Configure products under `Products -> In-app products`.

4. Create a service account key:
   1. Go to the [Google Cloud Console](https://console.cloud.google.com/projectselector2/iam-admin/serviceaccounts)
.
   2. Select the project linked to your Play Store app, then click `Create Service Account`.
   3. Enter a name and description for the service account (e.g., temp-number-google-play), then click `Create`.
   4. Click `Create Key` and select `JSON` as the key type.
   5. Save the JSON file as `google-play-service-account.json`.

5. Grant the service account access to app financial data:
   1. In the [Google Play Console](https://play.google.com/apps/publish/)
, go to `Users and permissions` and click `Invite new users`.
   2. Paste the email address from the service account JSON file and select `Finance` as the role.
   3. In the app permission tab, click `Add app` and select your app.
   4. Allow the service account to access the financial data of the app.
   5. Click `Invite user`.

6. Configure a Google Pub/Sub topic:
   1. Go to the [Google Cloud Console](https://console.cloud.google.com/projectselector2/cloudpubsub/topic/list)
.
   2. Click on `Create a topic` and enter a `Topic ID` (a name for the topic).
   3. Click `Create`.
   4. Choose `Subscription` for the created topic and click `EDIT`.
   5. Change `Delivery type` to `Push` and paste the webhook URL into the `Endpoint URL`:

      ```curl
      https://<your-backend-url>/googleplay-handleWebhookEvents
      ```

   6. Change the `Retry policy` to `Retry after exponential backoff delay`.
   7. Click `Update`.

7. Grant the Google Play Store access to the Google Pub/Sub topic:
   1. In the [Google Cloud Console](https://console.cloud.google.com/projectselector2/cloudpubsub/topic/list)
, select the topic you created.
   2. Click on `ADD PRINCIPAL`.
   3. In the new principal field, enter `google-play-developer-notifications@system.gserviceaccount.com`.
   4. Select the `Role` as `Pub/Sub Publisher`.

8. Configure Google Play Store notifications:
   1. In the [Google Play Console](https://play.google.com/apps/publish/)
, select your app.
   2. Under the `Monetization setup` section in `Monetize`, check `Enable real-time notifications`.
   3. Fill in the `Topic name` with the name of the topic you created in the Google Cloud Console.
   4. Set `Notification content` to include `Subscriptions, voided purchases, and all one-time products`.
   5. Click `Save changes`.

9. Set `GOOGLE_PLAY_SECRET_FILE` variable during the Temp-Number Backend installation to include service account file contents. This should be a JSON string representing the contents of the `google-play-service-account.json` file created earlier.

## Adding Custom Payment Gateways

To add a custom payment gateway, you need to:

1. Add a new payment controller under `app/controllers/payments` that will:
   1. Handle incoming payment notification from custom payment gateway
   2. Verify the payment and its authenticity
   3. Add a record to the `tn_payments` database with at least the following fields:
      - `payment_id`: Unique ID for the payment. This can be the payment ID from the payment gateway.
      - `uid`: Firebase UID of the user making the payment.
      - `amount`: The amount of the payment in USD cents. Use a negative amount for refunds.
      - `gateway`: The name of the payment gateway.
      - `is_synced`: Should be set to `false`. A boolean flag to indicate if the payment has been synced with the Retail API.

      Field constraints can be found in the `createCustomerTransaction` endpoint of the Retail API.

2. Add a new route in in `start/routes.ts` to point to the new payment controller.
3. Add the necessary configuration variables to the `start/env.ts` file.
4. Configure the custom payment gateway to send payment notifications to the new route.
5. Configure any necessary environment variables and secrets during the Temp-Number Backend installation.
6. Redeploy the Temp-Number Backend.

