API Reference

Here is a Example of Execute Payments and Handle Transaction Initiation.

import axios from 'axios';

const FawaterakPayment = () => {
  const [paymentCompleted, setpaymentCompleted] = useState(false);
  const [fawaterkurl, setfawaterkurl] = useState(null);


  const API_URL = 'https://staging.fawaterk.com/api/v2/invoiceInitPay';
  const API_TOKEN = 'd83a5d07aaeb8442dcbe259e6dae80a3f2e21a3a581e1a5acd';
  const PAYMENT_ID = 4; // 2=Visa-MasterCard, 3=Fawry, 4=Meeza

const generateFawaterksession = async () => {
   const data = {
    payment_method_id: PAYMENT_id,
    cartTotal: '100',
    currency: 'EGP',
    customer: {
      first_name: 'test',
      last_name: 'test',
      email: '[email protected]',
      phone: '01000000000',
      address: 'test address',
    },
    redirectionUrls: {
      successUrl: 'https://dev.fawaterk.com/success',
      failUrl: 'https://dev.fawaterk.com/fail',
      pendingUrl: 'https://dev.fawaterk.com/pending',
    },
    cartItems: [
      {
        name: 'test',
        price: '100',
        quantity: '1',
      },
    ],
  };

  const config = {
    method: 'post',
    url: API_URL,
    headers: {
      Authorization: `Bearer ${API_TOKEN}`,
      'Content-Type': 'application/json',
    },
    data: data,
  };

  try {
    const response = await axios(config);
    const responseData = response.data;
    if (responseData) {
      setfawaterkurl(responseData?.data.payment_data?.redirectTo);
      setpaymentCompleted(true);
    }
  } catch (error) {
    console.log(error);
  }
};

  useEffect(() => {
    generateFawaterksession();
  }, []);

  const handleNavigationStateChange = (newNavState: { url: any }) => {
    // Check if the URL has changed to handle the response or perform further actions
    console.log('newNavState', newNavState);

    // Replace 'https://dev.fawaterk.com/' with your redirectionUrls
    if (newNavState.url.includes('https://dev.fawaterk.com/')) {
      // Handle the response or perform any required actions here
      newNavState?.url.includes('success')
        ? console.log('success')
        : console.log('Cancelled');
    }
  };
  

  return (
    <View style={{ flex: 1 }}>
      {paymentCompleted ? (
        <WebView
          source={{ uri: fawaterkurl }}
          onNavigationStateChange={handleNavigationStateChange}
          
        />
      ) : (
        <Text>Loading...</Text>
      )}
    </View>
  );
};

export default FawaterakPayment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private boolean paymentCompleted = false;
    private String fawaterkurl = null;

    private static final String API_URL = "https://staging.fawaterk.com/api/v2/invoiceInitPay";
    private static final String API_TOKEN = "d83a5d07aaeb8442dcbe259e6dae80a3f2e21a3a581e1a5acd";
    private static final int PAYMENT_ID = 4;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        generateFawaterksession();

        WebView webView = findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // Check if the URL has changed to handle the response or perform further actions
                if (url.contains("https://dev.fawaterk.com/")) {
                    // Handle the response or perform any required actions here
                    if (url.contains("success")) {
                        System.out.println("success");
                    } else {
                        System.out.println("Cancelled");
                    }
                }
                return false;
            }
        });

        if (paymentCompleted) {
            webView.loadUrl(fawaterkurl);
        }
    }

 public void generateFawaterksession() {
    OkHttpClient client = new OkHttpClient();

    MediaType mediaType = MediaType.parse("application/json");
    Map<String, Object> requestBody = new HashMap<>();
    requestBody.put("payment_method_id", PAYMENT_ID);
    requestBody.put("cartTotal", "100");
    requestBody.put("currency", "EGP");

    Map<String, String> customer = new HashMap<>();
    customer.put("first_name", "test");
    customer.put("last_name", "test");
    customer.put("email", "[email protected]");
    customer.put("phone", "01000000000");
    customer.put("address", "test address");
    requestBody.put("customer", customer);

    Map<String, String> redirectionUrls = new HashMap<>();
    redirectionUrls.put("successUrl", "https://dev.fawaterk.com/success");
    redirectionUrls.put("failUrl", "https://dev.fawaterk.com/fail");
    redirectionUrls.put("pendingUrl", "https://dev.fawaterk.com/pending");
    requestBody.put("redirectionUrls", redirectionUrls);

    Map<String, Object> cartItem = new HashMap<>();
    cartItem.put("name", "test");
    cartItem.put("price", "100");
    cartItem.put("quantity", "1");
    requestBody.put("cartItems", new Object[] { cartItem });

    RequestBody body = RequestBody.create(mediaType, new Gson().toJson(requestBody));

    Request request = new Request.Builder()
        .url(API_URL)
        .addHeader("Authorization", "Bearer " + API_TOKEN)
        .addHeader("Content-Type", "application/json")
        .post(body)
        .build();

    try {
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            String responseData = response.body().string();
            JSONObject json = new JSONObject(responseData);
            JSONObject paymentData = json.getJSONObject("data").getJSONObject("payment_data");
            String redirectTo = paymentData.optString("redirectTo");
            if (!redirectTo.isEmpty()) {
                fawaterkurl = redirectTo;
                paymentCompleted = true;
            }
        }
    } catch (IOException | JSONException e) {
        e.printStackTrace();
    }
}
}

import android.annotation.SuppressLint
import android.os.Bundle
import android.webkit.WebView
import android.webkit.WebViewClient
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import java.io.IOException

import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    private var paymentCompleted = false
    private var fawaterkurl: String? = null

    private val API_URL = "https://staging.fawaterk.com/api/v2/invoiceInitPay"
    private val API_TOKEN = "d83a5d07aaeb8442dcbe259e6dae80a3f2e21a3a581e1a5acd"
    private val PAYMENT_ID = 4

    @SuppressLint("SetJavaScriptEnabled")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        generateFawaterksession()

        val webView = findViewById<WebView>(R.id.webView)
        webView.settings.javaScriptEnabled = true

        webView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                // Check if the URL has changed to handle the response or perform further actions
                if (url.contains("https://dev.fawaterk.com/")) {
                    // Handle the response or perform any required actions here
                    if (url.contains("success")) {
                        println("success")
                    } else {
                        println("Cancelled")
                    }
                }
                return false
            }
        }

        if (paymentCompleted) {
            webView.loadUrl(fawaterkurl)
        }
    }

 fun generateFawaterksession() {
    val client = OkHttpClient()

    val mediaType = "application/json".toMediaTypeOrNull()
    val requestBody = JSONObject()
    requestBody.put("payment_method_id", PAYMENT_ID)
    requestBody.put("cartTotal", "100")
    requestBody.put("currency", "EGP")

    val customer = JSONObject()
    customer.put("first_name", "test")
    customer.put("last_name", "test")
    customer.put("email", "[email protected]")
    customer.put("phone", "01000000000")
    customer.put("address", "test address")
    requestBody.put("customer", customer)

    val redirectionUrls = JSONObject()
    redirectionUrls.put("successUrl", "https://dev.fawaterk.com/success")
    redirectionUrls.put("failUrl", "https://dev.fawaterk.com/fail")
    redirectionUrls.put("pendingUrl", "https://dev.fawaterk.com/pending")
    requestBody.put("redirectionUrls", redirectionUrls)

    val cartItem = JSONObject()
    cartItem.put("name", "test")
    cartItem.put("price", "100")
    cartItem.put("quantity", "1")
    requestBody.put("cartItems", listOf(cartItem))

    val request = Request.Builder()
        .url(API_URL)
        .addHeader("Authorization", "Bearer $API_TOKEN")
        .addHeader("Content-Type", "application/json")
        .post(requestBody.toString().toRequestBody(mediaType))
        .build()

    try {
        val response = client.newCall(request).execute()
        if (response.isSuccessful) {
            val responseData = response.body?.string()
            val json = JSONObject(responseData)
            val paymentData = json.getJSONObject("data").getJSONObject("payment_data")
            val redirectTo = paymentData.optString("redirectTo")
            if (!redirectTo.isNullOrEmpty()) {
                fawaterkurl = redirectTo
                paymentCompleted = true
            }
        }
    } catch (e: IOException) {
        e.printStackTrace()
    }
}
}

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {

    private var paymentCompleted = false
    private var fawaterkurl: String?

    private let API_URL = "https://staging.fawaterk.com/api/v2/invoiceInitPay"
    private let API_TOKEN = "d83a5d07aaeb8442dcbe259e6dae80a3f2e21a3a581e1a5acd"
    private let PAYMENT_ID = 4

    private var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        generateFawaterksession()

        webView = WKWebView(frame: view.frame)
        webView.navigationDelegate = self
        view.addSubview(webView)

        if paymentCompleted, let url = fawaterkurl, let webViewUrl = URL(string: url) {
            let request = URLRequest(url: webViewUrl)
            webView.load(request)
        }
    }

func generateFawaterksession() {
    let url = URL(string: API_URL)!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.addValue("Bearer \(API_TOKEN)", forHTTPHeaderField: "Authorization")
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    
    let parameters: [String: Any] = [
        "payment_method_id": PAYMENT_ID,
        "cartTotal": "100",
        "currency": "EGP",
        "customer": [
            "first_name": "test",
            "last_name": "test",
            "email": "[email protected]",
            "phone": "01000000000",
            "address": "test address"
        ],
        "redirectionUrls": [
            "successUrl": "https://dev.fawaterk.com/success",
            "failUrl": "https://dev.fawaterk.com/fail",
            "pendingUrl": "https://dev.fawaterk.com/pending"
        ],
        "cartItems": [
            [
                "name": "test",
                "price": "100",
                "quantity": "1"
            ]
        ]
    ]
    
    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
        
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            if let error = error {
                print(error)
                return
            }
            
            if let data = data {
                do {
                    let responseData = try JSONSerialization.jsonObject(with: data, options: [])
                    if let json = responseData as? [String: Any],
                       let paymentData = json["data"] as? [String: Any],
                       let redirectTo = paymentData["redirectTo"] as? String {
                        self.fawaterkurl = redirectTo
                        self.paymentCompleted = true
                    }
                } catch {
                    print(error)
                }
            }
        }
        
        task.resume()
    } catch {
        print(error)
    }
}


    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        // Check if the URL has changed to handle the response or perform further actions
        if let url = navigationAction.request.url, url.absoluteString.contains("https://dev.fawaterk.com/") {
            // Handle the response or perform any required actions here
            if url.absoluteString.contains("success") {
                print("success")
            } else {
                print("Cancelled")
            }
        }
        decisionHandler(.allow)
    }
}

import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class FawaterakPayment extends StatefulWidget {
  @override
  _FawaterakPaymentState createState() => _FawaterakPaymentState();
}

class _FawaterakPaymentState extends State<FawaterakPayment> {
  bool paymentCompleted = false;
  String? fawaterkurl;

  final apiUrl = 'https://staging.fawaterk.com/api/v2/invoiceInitPay';
  final apiToken = 'd83a5d07aaeb8442dcbe259e6dae80a3f2e21a3a581e1a5acd';
  final paymentId = 4; // 2=Visa-MasterCard, 3=Fawry, 4=Meeza

  void generateFawaterksession() async {
    final data = {
      'payment_method_id': paymentId,
      'cartTotal': '100',
      'currency': 'EGP',
      'customer': {
        'first_name': 'test',
        'last_name': 'test',
        'email': '[email protected]',
        'phone': '01000000000',
        'address': 'test address',
      },
      'redirectionUrls': {
        'successUrl': 'https://dev.fawaterk.com/success',
        'failUrl': 'https://dev.fawaterk.com/fail',
        'pendingUrl': 'https://dev.fawaterk.com/pending',
      },
      'cartItems': [
        {
          'name': 'test',
          'price': '100',
          'quantity': '1',
        },
      ],
    };

    final headers = {
      'Authorization': 'Bearer $apiToken',
      'Content-Type': 'application/json',
    };

    try {
      final response = await http.post(
        Uri.parse(apiUrl),
        headers: headers,
        body: json.encode(data),
      );

      final responseData = json.decode(response.body);
      if (responseData != null) {
        setState(() {
          fawaterkurl = responseData['data']['payment_data']['redirectTo'];
          paymentCompleted = true;
        });
      }
    } catch (error) {
      print(error);
    }
  }

  @override
  void initState() {
    super.initState();
    generateFawaterksession();
  }

  void handleNavigationStateChange(String newUrl) {
    // Check if the URL has changed to handle the response or perform further actions
    print('newUrl: $newUrl');

    // Replace 'https://dev.fawaterk.com/' with your redirectionUrls
    if (newUrl.contains('https://dev.fawaterk.com/')) {
      // Handle the response or perform any required actions here
      if (newUrl.contains('success')) {
        print('success');
      } else {
        print('Cancelled');
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: paymentCompleted
          ? WebView(
              initialUrl: fawaterkurl,
              navigationDelegate: (NavigationRequest request) {
                handleNavigationStateChange(request.url);
                return NavigationDecision.navigate;
              },
              javascriptMode: JavascriptMode.unrestricted,
            )
          : Center(
              child: Text('Loading...'),
            ),
    );
  }
}

void main() {
  runApp(MaterialApp(
    home: FawaterakPayment(),
  ));
}

**Please note that the code samples provided here are just examples, and you may need to customize them according to your specific application's requirements.

**

handleNavigationStateChange Function for React Native

The handleNavigationStateChange function is responsible for handling changes in the WebView's navigation state. It is typically used in conjunction with a WebView component to capture and handle the response from a redirected URL.

Usage

The function takes a single argument, newNavState, which is an object containing information about the URL being loaded. Here's how you can use the handleNavigationStateChange function:

Check if the URL has changed:

Use console.log to log the newNavState object. This provides information about the new URL being loaded, allowing you to inspect the navigation state.
Handle the response or perform further actions:

Replace the base URL 'https://dev.fawaterk.com/' with your actual redirection URL. This ensures that the response URL belongs to the expected domain.
Modify the condition to match your specific requirements for handling the response URL.
Perform actions based on the response:

Inside the condition, you can define different actions based on the response URL. For example, you can check if the URL includes 'success' to handle a successful payment or perform different actions for other scenarios.
Customize the actions within the condition to suit your application's needs. For instance, you can update the component state, display a success message, or navigate to a different screen in your application.

You can customize the actions inside the condition block to handle different response scenarios according to your specific application logic.