• Resolved tsccorp

    (@tsccorp)


    Hello I’m developing a mobile app for a website that make use of your plugin, are there endpoints? or how can I make custom endpoints as needed ?, like for instance list of transportation and prices for trip, I need the website and app to have same information for users.

    Also can this plugin be further customized to deliver parcels packages shopping and food ?

    I tried to get these two scripts to communicate, this one on the site –

    // Enqueue and localize the mptbm_registration.js file
    function enqueue_mptbm_registration_script() {
    wp_enqueue_script('mptbm-registration-script', plugin_dir_url(__FILE__) . 'assets/frontend/mptbm_registration.js', array('jquery'), null, true);
    wp_localize_script('mptbm-registration-script', 'vehicle_prices_ajax', [
    'ajax_url' => admin_url('admin-ajax.php'),
    'nonce' => wp_create_nonce('get_vehicle_prices_nonce'), // Make sure this matches verification
    ]);
    }
    add_action('wp_enqueue_scripts', 'enqueue_mptbm_registration_script');

    // Register AJAX actions for both logged-in and non-logged-in users
    add_action('wp_ajax_get_vehicle_prices', 'get_vehicle_prices_callback');
    add_action('wp_ajax_nopriv_get_vehicle_prices', 'get_vehicle_prices_callback');

    // Register a REST route to generate a nonce
    add_action('rest_api_init', function () {
    register_rest_route('vehicle-prices/v1', '/nonce', [
    'methods' => 'GET',
    'callback' => 'get_vehicle_prices_nonce',
    'permission_callback' => '__return_true',
    ]);
    });

    // Function to generate the nonce for REST API
    function get_vehicle_prices_nonce() {
    return rest_ensure_response(['nonce' => wp_create_nonce('get_vehicle_prices_nonce')]);
    }

    // Callback function to process the vehicle price request
    function get_vehicle_prices_callback() {
    // Verify request method
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    wp_send_json_error(['message' => 'Invalid request method. Use POST.']);
    }

    // Verify the nonce for security
    if ( !isset($_POST['nonce']) ) {
    wp_send_json_error(['message' => 'Nonce is missing.']);
    }
    if ( !wp_verify_nonce($_POST['nonce'], 'get_vehicle_prices_nonce') ) {
    wp_send_json_error(['message' => 'Invalid nonce received.', 'received_nonce' => $_POST['nonce']]);
    }

    // Sanitize and process input data from the POST request
    $start_place = sanitize_text_field($_POST['_mptbm_start_place']);
    $end_place = sanitize_text_field($_POST['_mptbm_end_place']);
    $date = sanitize_text_field($_POST['_mptbm_date']);
    $time = sanitize_text_field($_POST['_mptbm_time']);
    $distance = floatval($_POST['_mptbm_distance']);
    $duration = intval($_POST['_mptbm_duration']);

    // Query the available vehicles
    $vehicle_posts = get_posts([
    'post_type' => 'mptbm_vehicle',
    'posts_per_page' => -1,
    'post_status' => 'publish',
    ]);

    // Return error if no vehicles are found
    if (empty($vehicle_posts)) {
    wp_send_json_error(['message' => 'No vehicles available.']);
    }

    $response = [];
    foreach ($vehicle_posts as $vehicle) {
    $vehicle_id = $vehicle->ID;
    $base_price = floatval(get_post_meta($vehicle_id, '_mptbm_base_price', true));
    $price_per_distance = floatval(get_post_meta($vehicle_id, '_mptbm_price_per_distance', true));
    $price_per_time = floatval(get_post_meta($vehicle_id, '_mptbm_price_per_time', true));

    // Calculate the total price for the vehicle
    $total_price = $base_price + ($price_per_distance * $distance) + ($price_per_time * $duration);

    // Add vehicle data to the response array
    $response[] = [
    'vehicle_id' => $vehicle_id,
    'vehicle_name' => get_the_title($vehicle_id),
    'vehicle_sku' => get_post_meta($vehicle_id, '_sku', true),
    'total_price' => number_format($total_price, 2),
    ];
    }

    // Send the JSON response back to the client
    wp_send_json_success($response);
    }

    and this one in the app –

    using UnityEngine;
    using UnityEngine.Networking;
    using System.Collections;
    using System;

    public class NonceFetcher : MonoBehaviour
    {
    // The URL of the WordPress API endpoint that returns the nonce
    string nonceUrl = "https://riodrivers.com/wp-json/vehicle-prices/v1/nonce";

    // Variable to store the nonce after it is fetched
    private string nonce = "";

    public void Start()
    {
    FetchNonce(); // Fetch the nonce first
    }

    // Function to trigger fetching the nonce from the server
    public void FetchNonce()
    {
    StartCoroutine(GetNonceFromServer());
    }

    // Coroutine to send GET request to WordPress API and retrieve nonce
    private IEnumerator GetNonceFromServer()
    {
    UnityWebRequest request = UnityWebRequest.Get(nonceUrl);
    yield return request.SendWebRequest();

    if (request.result == UnityWebRequest.Result.Success)
    {
    string responseText = request.downloadHandler.text;
    Debug.Log("Nonce Response: " + responseText);

    try
    {
    // Deserialize the JSON response to extract the nonce
    var jsonResponse = JsonUtility.FromJson<NonceResponse>(responseText);
    nonce = jsonResponse.nonce;

    Debug.Log("Nonce: " + nonce);
    VehiclePriceFetcher(); // Fetch vehicle prices after nonce is obtained
    }
    catch (Exception e)
    {
    Debug.LogError("Error parsing nonce JSON: " + e.Message);
    }
    }
    else
    {
    Debug.LogError("Failed to fetch nonce: " + request.error);
    }
    }

    // Create a C# class to represent the structure of the JSON response from the WordPress API
    [System.Serializable]
    public class NonceResponse
    {
    public string nonce;
    }

    // Function to fetch vehicle prices using the nonce
    public void VehiclePriceFetcher()
    {
    if (string.IsNullOrEmpty(nonce))
    {
    Debug.LogError("Nonce is missing, cannot make request.");
    return;
    }

    string requestUrl = "https://riodrivers.com/wp-admin/admin-ajax.php";
    string startLocation = "Blue Ridge, GA 30513, USA";
    string endLocation = "16177 Birwood Avenue, Beverly Hills, MI, USA";
    string pickupDate = "2025-03-01";
    string pickupTime = "12:30";
    float distance = 20f;
    int duration = 30;

    WWWForm form = new WWWForm();
    form.AddField("action", "get_vehicle_prices");
    form.AddField("nonce", nonce);
    form.AddField("_mptbm_start_place", startLocation);
    form.AddField("_mptbm_end_place", endLocation);
    form.AddField("_mptbm_date", pickupDate);
    form.AddField("_mptbm_time", pickupTime);
    form.AddField("_mptbm_distance", distance.ToString());
    form.AddField("_mptbm_duration", duration.ToString());

    StartCoroutine(SendRequest(requestUrl, form));
    }

    // Coroutine to send the actual request to WordPress
    private IEnumerator SendRequest(string url, WWWForm form)
    {
    UnityWebRequest request = UnityWebRequest.Post(url, form);
    yield return request.SendWebRequest();

    if (request.result == UnityWebRequest.Result.Success)
    {
    string responseText = request.downloadHandler.text;
    Debug.Log("Response: " + responseText);

    try
    {
    // Deserialize JSON response to extract vehicle data
    var jsonResponse = JsonUtility.FromJson<VehiclePriceResponseWrapper>(responseText);

    if (jsonResponse.success)
    {
    if (jsonResponse.data != null && jsonResponse.data.Length > 0)
    {
    Debug.Log("First vehicle: " + jsonResponse.data[0].vehicle_name);
    }
    else
    {
    Debug.LogWarning("No vehicle data found in response.");
    }
    }
    else
    {
    Debug.LogWarning("Error in response: " + jsonResponse.message);
    }
    }
    catch (Exception e)
    {
    Debug.LogError("Error parsing JSON response: " + e.Message);
    }
    }
    else
    {
    Debug.LogError("Failed to send request: " + request.error + "\n" + request.downloadHandler.text);
    }
    }

    // Classes for JSON deserialization
    [System.Serializable]
    public class VehiclePriceResponseWrapper
    {
    public bool success;
    public string message;
    public VehiclePriceResponse[] data;
    }

    [System.Serializable]
    public class VehiclePriceResponse
    {
    public int vehicle_id;
    public string vehicle_name;
    public string vehicle_sku;
    public string total_price;
    }
    }
Viewing 7 replies - 1 through 7 (of 7 total)
  • Plugin Contributor hamidxazad

    (@hamidxazad)

    While registering custom post you can show custom post type in rest by putting below code.

    'show_in_rest' => true,

    Later you can fetch custom post type data in rest api

    Thread Starter tsccorp

    (@tsccorp)

    Sorry but this didn’t help me at all, this not answering , what I’m asking, and you didn’t even answer my other questions…

    Thread Starter tsccorp

    (@tsccorp)

    Yeah I didn’t register a custom post type , then you say place code below “show in rest(true)” – where??? then how would I get the correct prices in the app as I would on the site . you’re not very helpful here or I’m not clear, can you please explain?

    Thread Starter tsccorp

    (@tsccorp)

    are you saying place that line in this code block ? – like so or what?

    // Register a REST route to generate a nonceadd_action('rest_api_init', function () {    register_rest_route('vehicle-prices/v1', '/nonce', [        'methods' => 'GET', 'show_in_rest' => true,       'callback' => 'get_vehicle_prices_nonce',        'permission_callback' => '__return_true',    ]);});
    Thread Starter tsccorp

    (@tsccorp)

    or should this –

    'post_type' => 'mptbm_vehicle',

    read this?

    'post_type' => 'mptbm_rent',
    Thread Starter tsccorp

    (@tsccorp)

    I stumbled on it while letting the mouse hover over Title in vehicle list in wp dashboard now I have to work some more – I changed this –

    'post_type' => 'mptbm_vehicle',

    to this –

    'post_type' => 'mptbm_rent',

    I’m getting more feed back now In the app I just have to do some more coding and making things align, but what you said didn’t help me at all and you didn’t even address my other questions and you also marked the topic as resolved or it auto did when it’s not.

    Plugin Contributor hamidxazad

    (@hamidxazad)

    I’ve already provided an idea on how you can enable the REST API for the custom post type of transports. We do not provide any built-in endpoints. While you can create custom endpoints as needed, please note that any customizations will be lost if the eCab plugin is updated.

    We cannot assist you with your custom development. However, if you encounter any functional issues with the plugin itself, we’re here to help.

    Let me know if you need further support regarding the plugin.

Viewing 7 replies - 1 through 7 (of 7 total)

The topic ‘Endpoints’ is closed to new replies.