Php WordPress上的RESTAPI。API没有';不要听任何URL调用

Php WordPress上的RESTAPI。API没有';不要听任何URL调用,php,android,wordpress,cordova,slim,Php,Android,Wordpress,Cordova,Slim,我们对API是全新的,我们在使用基于Cordova的Android应用程序时遇到了一个问题。API目前不监听程序外的任何URL调用,我们也不知道在哪里定义API来监听并向我们的应用程序发送JSON/AJAX 我们的.htaccess如下所示: RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [QSA,L] <?php require "vendor/autoload.php";

我们对API是全新的,我们在使用基于Cordova的Android应用程序时遇到了一个问题。API目前不监听程序外的任何URL调用,我们也不知道在哪里定义API来监听并向我们的应用程序发送JSON/AJAX

我们的
.htaccess
如下所示:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
<?php

require "vendor/autoload.php";

require "config.php";

spl_autoload_register(function ($class) {
  require "classes/{$class}.php";
});

session_start();
session_cache_limiter(false);

date_default_timezone_set("Europe/Helsinki");

$app = new CustomSlim;

$app->config("view", New \Slim\Views\Twig());

$view = $app->view();
$view->parserExtensions = [
  new \Slim\Views\TwigExtension(),
];


$app->databaseService = function () {
  return new DatabaseService(DB_HOST, DB_PORT, DB_NAME, DB_USERNAME, DB_PASSWORD);
};

$app->helperService = function () {
  return new HelperService();
};

$app->reservationService = function () {
  return new ReservationService();
};

$app->mailerService = function () use ($app) {
  return new MailerService(GOOGLE_MAIL_USERNAME, GOOGLE_MAIL_PASSWORD, GOOGLE_MAIL_PORT, $app->view()->getEnvironment());
};

$app->paybywayService = function () {
  return new PaybywayService(PAYBYWAY_MERCHANT_ID, PAYBYWAY_VERSION_NUMBER, PAYBYWAY_PRIVATE_KEY, PAYBYWAY_API_KEY, PAYBYWAY_REDIRECTION_URL, PAYBYWAY_TOKEN_REQUEST_URL);
};

$authenticate = function ($app) {
  return function () use ($app) {
    if (!isset($_SESSION['user'])) {
      $app->flash("error", "Sisäänkirjautuminen vaaditaan");
      $app->redirectTo('login');
    }
  };
};

$app->hook('slim.before.dispatch', function() use ($app) {
  if (isset($_SESSION['user'])) {
    $app->view()->setData('logged', TRUE);
    $app->view()->setData('username', $_SESSION['user']);
  } else {
    $app->view()->setData('logged', FALSE);
  }
});

require "api.php";
require "admin.php";

$app->run();
<?php

{
 "reservation_id" : 5,
 "token" : "f2e23e99c1f85f16497dcd15cf452617"
}

$app->post("/haeVaraus", function() use ($app) {
    $requestBody = json_decode($app->request()->getBody());

    //Tarkistetaan onko pyynnössä validia tokenia
    if (property_exists($requestBody, "token") && property_exists($requestBody, "reservation_id")) {
        $reservation = $app->databaseService->getReservationByTokenAndId($requestBody->reservation_id, $requestBody->token);
        if ($reservation != null) {
            $reservation = array_shift($reservation);
            $car = $app->databaseService->getCarById($reservation["car_id"]);

            $output = array(
                "reservation" => $reservation,
                "car" => $car
            );
            $app->helperService->json(200, $output);
        } else {
            $app->helperService->json(400, ["error" => "ERR_NO_RESERVATIONS_FOUND"]);
        }   
    } else {
        $app->helperService->json(400, ["error" => "ERR_TOKEN_NOT_FOUND"]);
    }
});

$app->post("/haeVaraukset", function() use ($app) {
    // Poista kaikki vanhentuneet varaukset
    $app->databaseService->deleteExpiredPreReservationsAndDummyCustomers(PRE_RESERVATION_EXPIRATION_TIME_LIMIT);

    $reservationDatetimes = $app->databaseService->getAllReservedDates();
    $app->helperService->json(200, $reservationDatetimes);
});

/* Hae tietyn varauksen ja asiakkaan tiedot tokenin ja id:n avulla
Kysely:
{
 "reservation_id" : 5,
 "token" : "f2e23e99c1f85f16497dcd15cf452617"
}
*/
$app->post("/haeVarausVahvistus", function() use ($app) {
    $requestBody = json_decode($app->request()->getBody());

    if (property_exists($requestBody, "token") && property_exists($requestBody, "reservation_id")) {
        $token = $requestBody->token;
        $reservationId = $requestBody->reservation_id;

        $customerId = $app->databaseService->getCustomerIdByToken($token);
        $customer = $app->databaseService->getCustomerData($customerId);

        unset($customer["person_identifier"]);

        $reservation = $app->databaseService->getReservationByTokenAndId($reservationId, $token)[0];
        $car = $app->databaseService->getCarById($reservation["car_id"]);

        $responseData = array(
            "customer" => $customer,
            "reservation" => $reservation,
            "car" => $car
        );
        $app->helperService->json(200, $responseData);
    } else {
        $app->helperService->json(400, ["error" => "ERR_TOKEN_NOT_FOUND"]);
    }
});

$app->post("/esivaraus", function() use ($app) {
    $userReservation = json_decode($app->request()->getBody());
    $validationResponse = $app->reservationService->validateReservationTime($userReservation);

    if (!$validationResponse) {

        $reservationFound = $app->databaseService->checkIfStartDatetimeHasReservation($userReservation->startDatetime);
        if ($reservationFound) {
            $app->helperService->json(400, ["error" => "ERR_DATE_HAS_RESERVATION"]);
        }

        // Captcha server-side validation
        $captchaValidation = $app->helperService->validateCaptcha($userReservation->captchaResponse);
        if ($captchaValidation->success == false) {
            $app->helperService->json(400,["error" => "CAPTCHA_ERROR"]);
        }

        if (property_exists($userReservation, "token")) {
            $customerId = $app->databaseService->getCustomerIdByToken($userReservation->token);
            $app->databaseService->removePreReservation($customerId);
        }

        static $campaignCarId = 1;
        $campaignCar = $app->databaseService->getCarById($campaignCarId);

        if ($campaignCar["car_id"] != 1) {
            $app->helperService->json(400,["error" => "ERR_CAMPAIGN_CAR_NOT_FOUND"]);
        }

        $campaignCar["totalPrice"] = 20;

        if (isset($campaignCar["totalPrice"])) {
            if ($userReservation->carId == $campaignCar['car_id']) {
                $lastInsertedCustomerId = $app->databaseService->addDummyCustomerAndReturnCustomerId();

                $token = $app->reservationService->addReservation($userReservation->carId, $lastInsertedCustomerId,
                    $userReservation->startDatetime, $userReservation->endDatetime, $campaignCar['totalPrice']);

                $reservation = $app->databaseService->getReservationByToken($token);

                $output = array(
                    "token" => $token,
                    "reservation_id" => $reservation["reservation_id"]
                );
                $app->helperService->json(200, $output);
            }
        }
    } else {
        $app->helperService->json(400,["error" => $validationResponse]);
    }
});

$app->post("/tarkistaAsiakasTiedot", function () use ($app) {
    $customer = json_decode($app->request()->getBody());

    $validationResponse = $app->reservationService->validateCustomer($customer);
    if (!$validationResponse) {

        $luottotiedot = $app->helperService->checkUserCreditInformation($customer->person_identifier);
        if ($luottotiedot === "true") {
            $customerId = $app->databaseService->getCustomerIdByToken($customer->token);
            $responseData = $app->reservationService->updateCustomerByCustomerId($customer, $customerId, false);

            $reservationId = $responseData["reservation"]["reservation_id"];

            $app->helperService->json(200, ["reservation_id" => $reservationId]);
        } else {
            $app->helperService->json(400, ["error" => "ERR_CREDIT_INFORMATION_DECLINED"]);
        }
    } else {
        $app->helperService->json(400, ["error" => $validationResponse]);
    }
});

$app->post("/varaus", function() use ($app) {
    $customer = json_decode($app->request()->getBody());
    $customerIdByToken = $app->databaseService->getCustomerIdByToken($customer->token);

    if ($customerIdByToken == $customer->customer_id) {
        // Päivitä varauksen tila varatuksi tietokantaan
        $output = $app->reservationService->updateCustomerByCustomerId($customer, $customerIdByToken, true);

        $priceInCents = $output["totalPrice"] * 100;
        $paymentInformation = $app->paybywayService->getPaymentInformation($priceInCents, $customer);

        $app->helperService->json(200, ['payment_information' => $paymentInformation]);
    } else {

        $reservation = $app->databaseService->getReservationByToken($customer->token);
        $app->databaseService->deleteReservationById($reservation["reservation_id"]);

        $app->helperService->json(400, ["error" => "ERR_TOKEN_NOT_FOUND"]);
    }
});

$app->get("/maksu", function() use ($app) {

    $paymentReturnData = array(
        "orderNumber" => $app->request()->get('ORDER_NUMBER'),
        "authcode" => $app->request()->get('AUTHCODE'),
        "returnCode" => $app->request()->get('RETURN_CODE'),
        "settled" => $app->request()->get('SETTLED')
    );

    $validationResponse = $app->paybywayService->validatePaymentReturnData($paymentReturnData);

    if (!$validationResponse) {

        $token = $paymentReturnData["orderNumber"];
        $customerId = $app->databaseService->getCustomerIdByToken($token);
        $reservation = $app->databaseService->getReservationByToken($token);

        if ($paymentReturnData["returnCode"] == 0) {

            $app->databaseService->updateReservationStatus($paymentReturnData);

            $customer = $app->databaseService->getCustomerData($customerId);
            // HUOM!
            // Ei palauteta käyttäjän henkilötunnusta tietoturva syiden vuoksi
            unset($customer["person_identifier"]);

            $reservation["duration"] = $app->helperService->formatDateDifference($reservation["start_datetime"], $reservation["end_datetime"]);

            $car = $app->databaseService->getCarById($reservation["car_id"]);

            // Sähköpostin lähetys käyttäjälle
            $app->mailerService->sendConfirmationEmail($reservation, $customer, $car);


            $app->redirect($app->urlFor('kiitos', array('token' => $token)));
        } else {

            $app->databaseService->deleteReservationById($reservation["reservation_id"]);

            $errorMessage = $app->paybywayService->handlePaymentErrorCode($paymentReturnData["returnCode"]);
            $app->render('paymentFail.twig', array(
                "errorMessage" => $errorMessage,
                "domain" => DOMAIN
            ));
        }
    } else {
        $app->helperService->json(400, ["error" => $validationResponse]);
    }
});

$app->get("/kiitos/:token", function($token) use ($app) {

    $customerId = $app->databaseService->getCustomerIdByToken($token);
    $customer = $app->databaseService->getCustomerData($customerId);


    unset($customer["person_identifier"]);

    $reservation = $app->databaseService->getReservationByToken($token);
    $reservation["duration"] = $app->helperService->formatDateDifference($reservation["start_datetime"], $reservation["end_datetime"]);

    $car = $app->databaseService->getCarById($reservation["car_id"]);

    $thankYouPageAttributes = array(
        "customer" => $customer,
        "reservation" => $reservation,
        "car" => $car,
        "domain" => DOMAIN,
        "google_maps_api_key" => GOOGLE_MAPS_API_KEY
    );

    $app->render('thankyou.twig', $thankYouPageAttributes);
})->name('kiitos');

$app->post("/laskeHinta", function() use($app) {
    $request = json_decode($app->request()->getBody());
    $reservation = $app->databaseService->getReservationByToken($request->token);
    // tyyppimuunnetaan string booleaniksi
    $extendedInsurance = ($request->extended_insurance === "true");
    $totalPrice = $app->reservationService->calculateTotalPrice($reservation, $request->mileage, $extendedInsurance);
    $output = [];
    $output["total_price"] = $totalPrice;
    $app->helperService->json(200, $output);
});
我们的
index.php
如下所示:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
<?php

require "vendor/autoload.php";

require "config.php";

spl_autoload_register(function ($class) {
  require "classes/{$class}.php";
});

session_start();
session_cache_limiter(false);

date_default_timezone_set("Europe/Helsinki");

$app = new CustomSlim;

$app->config("view", New \Slim\Views\Twig());

$view = $app->view();
$view->parserExtensions = [
  new \Slim\Views\TwigExtension(),
];


$app->databaseService = function () {
  return new DatabaseService(DB_HOST, DB_PORT, DB_NAME, DB_USERNAME, DB_PASSWORD);
};

$app->helperService = function () {
  return new HelperService();
};

$app->reservationService = function () {
  return new ReservationService();
};

$app->mailerService = function () use ($app) {
  return new MailerService(GOOGLE_MAIL_USERNAME, GOOGLE_MAIL_PASSWORD, GOOGLE_MAIL_PORT, $app->view()->getEnvironment());
};

$app->paybywayService = function () {
  return new PaybywayService(PAYBYWAY_MERCHANT_ID, PAYBYWAY_VERSION_NUMBER, PAYBYWAY_PRIVATE_KEY, PAYBYWAY_API_KEY, PAYBYWAY_REDIRECTION_URL, PAYBYWAY_TOKEN_REQUEST_URL);
};

$authenticate = function ($app) {
  return function () use ($app) {
    if (!isset($_SESSION['user'])) {
      $app->flash("error", "Sisäänkirjautuminen vaaditaan");
      $app->redirectTo('login');
    }
  };
};

$app->hook('slim.before.dispatch', function() use ($app) {
  if (isset($_SESSION['user'])) {
    $app->view()->setData('logged', TRUE);
    $app->view()->setData('username', $_SESSION['user']);
  } else {
    $app->view()->setData('logged', FALSE);
  }
});

require "api.php";
require "admin.php";

$app->run();
<?php

{
 "reservation_id" : 5,
 "token" : "f2e23e99c1f85f16497dcd15cf452617"
}

$app->post("/haeVaraus", function() use ($app) {
    $requestBody = json_decode($app->request()->getBody());

    //Tarkistetaan onko pyynnössä validia tokenia
    if (property_exists($requestBody, "token") && property_exists($requestBody, "reservation_id")) {
        $reservation = $app->databaseService->getReservationByTokenAndId($requestBody->reservation_id, $requestBody->token);
        if ($reservation != null) {
            $reservation = array_shift($reservation);
            $car = $app->databaseService->getCarById($reservation["car_id"]);

            $output = array(
                "reservation" => $reservation,
                "car" => $car
            );
            $app->helperService->json(200, $output);
        } else {
            $app->helperService->json(400, ["error" => "ERR_NO_RESERVATIONS_FOUND"]);
        }   
    } else {
        $app->helperService->json(400, ["error" => "ERR_TOKEN_NOT_FOUND"]);
    }
});

$app->post("/haeVaraukset", function() use ($app) {
    // Poista kaikki vanhentuneet varaukset
    $app->databaseService->deleteExpiredPreReservationsAndDummyCustomers(PRE_RESERVATION_EXPIRATION_TIME_LIMIT);

    $reservationDatetimes = $app->databaseService->getAllReservedDates();
    $app->helperService->json(200, $reservationDatetimes);
});

/* Hae tietyn varauksen ja asiakkaan tiedot tokenin ja id:n avulla
Kysely:
{
 "reservation_id" : 5,
 "token" : "f2e23e99c1f85f16497dcd15cf452617"
}
*/
$app->post("/haeVarausVahvistus", function() use ($app) {
    $requestBody = json_decode($app->request()->getBody());

    if (property_exists($requestBody, "token") && property_exists($requestBody, "reservation_id")) {
        $token = $requestBody->token;
        $reservationId = $requestBody->reservation_id;

        $customerId = $app->databaseService->getCustomerIdByToken($token);
        $customer = $app->databaseService->getCustomerData($customerId);

        unset($customer["person_identifier"]);

        $reservation = $app->databaseService->getReservationByTokenAndId($reservationId, $token)[0];
        $car = $app->databaseService->getCarById($reservation["car_id"]);

        $responseData = array(
            "customer" => $customer,
            "reservation" => $reservation,
            "car" => $car
        );
        $app->helperService->json(200, $responseData);
    } else {
        $app->helperService->json(400, ["error" => "ERR_TOKEN_NOT_FOUND"]);
    }
});

$app->post("/esivaraus", function() use ($app) {
    $userReservation = json_decode($app->request()->getBody());
    $validationResponse = $app->reservationService->validateReservationTime($userReservation);

    if (!$validationResponse) {

        $reservationFound = $app->databaseService->checkIfStartDatetimeHasReservation($userReservation->startDatetime);
        if ($reservationFound) {
            $app->helperService->json(400, ["error" => "ERR_DATE_HAS_RESERVATION"]);
        }

        // Captcha server-side validation
        $captchaValidation = $app->helperService->validateCaptcha($userReservation->captchaResponse);
        if ($captchaValidation->success == false) {
            $app->helperService->json(400,["error" => "CAPTCHA_ERROR"]);
        }

        if (property_exists($userReservation, "token")) {
            $customerId = $app->databaseService->getCustomerIdByToken($userReservation->token);
            $app->databaseService->removePreReservation($customerId);
        }

        static $campaignCarId = 1;
        $campaignCar = $app->databaseService->getCarById($campaignCarId);

        if ($campaignCar["car_id"] != 1) {
            $app->helperService->json(400,["error" => "ERR_CAMPAIGN_CAR_NOT_FOUND"]);
        }

        $campaignCar["totalPrice"] = 20;

        if (isset($campaignCar["totalPrice"])) {
            if ($userReservation->carId == $campaignCar['car_id']) {
                $lastInsertedCustomerId = $app->databaseService->addDummyCustomerAndReturnCustomerId();

                $token = $app->reservationService->addReservation($userReservation->carId, $lastInsertedCustomerId,
                    $userReservation->startDatetime, $userReservation->endDatetime, $campaignCar['totalPrice']);

                $reservation = $app->databaseService->getReservationByToken($token);

                $output = array(
                    "token" => $token,
                    "reservation_id" => $reservation["reservation_id"]
                );
                $app->helperService->json(200, $output);
            }
        }
    } else {
        $app->helperService->json(400,["error" => $validationResponse]);
    }
});

$app->post("/tarkistaAsiakasTiedot", function () use ($app) {
    $customer = json_decode($app->request()->getBody());

    $validationResponse = $app->reservationService->validateCustomer($customer);
    if (!$validationResponse) {

        $luottotiedot = $app->helperService->checkUserCreditInformation($customer->person_identifier);
        if ($luottotiedot === "true") {
            $customerId = $app->databaseService->getCustomerIdByToken($customer->token);
            $responseData = $app->reservationService->updateCustomerByCustomerId($customer, $customerId, false);

            $reservationId = $responseData["reservation"]["reservation_id"];

            $app->helperService->json(200, ["reservation_id" => $reservationId]);
        } else {
            $app->helperService->json(400, ["error" => "ERR_CREDIT_INFORMATION_DECLINED"]);
        }
    } else {
        $app->helperService->json(400, ["error" => $validationResponse]);
    }
});

$app->post("/varaus", function() use ($app) {
    $customer = json_decode($app->request()->getBody());
    $customerIdByToken = $app->databaseService->getCustomerIdByToken($customer->token);

    if ($customerIdByToken == $customer->customer_id) {
        // Päivitä varauksen tila varatuksi tietokantaan
        $output = $app->reservationService->updateCustomerByCustomerId($customer, $customerIdByToken, true);

        $priceInCents = $output["totalPrice"] * 100;
        $paymentInformation = $app->paybywayService->getPaymentInformation($priceInCents, $customer);

        $app->helperService->json(200, ['payment_information' => $paymentInformation]);
    } else {

        $reservation = $app->databaseService->getReservationByToken($customer->token);
        $app->databaseService->deleteReservationById($reservation["reservation_id"]);

        $app->helperService->json(400, ["error" => "ERR_TOKEN_NOT_FOUND"]);
    }
});

$app->get("/maksu", function() use ($app) {

    $paymentReturnData = array(
        "orderNumber" => $app->request()->get('ORDER_NUMBER'),
        "authcode" => $app->request()->get('AUTHCODE'),
        "returnCode" => $app->request()->get('RETURN_CODE'),
        "settled" => $app->request()->get('SETTLED')
    );

    $validationResponse = $app->paybywayService->validatePaymentReturnData($paymentReturnData);

    if (!$validationResponse) {

        $token = $paymentReturnData["orderNumber"];
        $customerId = $app->databaseService->getCustomerIdByToken($token);
        $reservation = $app->databaseService->getReservationByToken($token);

        if ($paymentReturnData["returnCode"] == 0) {

            $app->databaseService->updateReservationStatus($paymentReturnData);

            $customer = $app->databaseService->getCustomerData($customerId);
            // HUOM!
            // Ei palauteta käyttäjän henkilötunnusta tietoturva syiden vuoksi
            unset($customer["person_identifier"]);

            $reservation["duration"] = $app->helperService->formatDateDifference($reservation["start_datetime"], $reservation["end_datetime"]);

            $car = $app->databaseService->getCarById($reservation["car_id"]);

            // Sähköpostin lähetys käyttäjälle
            $app->mailerService->sendConfirmationEmail($reservation, $customer, $car);


            $app->redirect($app->urlFor('kiitos', array('token' => $token)));
        } else {

            $app->databaseService->deleteReservationById($reservation["reservation_id"]);

            $errorMessage = $app->paybywayService->handlePaymentErrorCode($paymentReturnData["returnCode"]);
            $app->render('paymentFail.twig', array(
                "errorMessage" => $errorMessage,
                "domain" => DOMAIN
            ));
        }
    } else {
        $app->helperService->json(400, ["error" => $validationResponse]);
    }
});

$app->get("/kiitos/:token", function($token) use ($app) {

    $customerId = $app->databaseService->getCustomerIdByToken($token);
    $customer = $app->databaseService->getCustomerData($customerId);


    unset($customer["person_identifier"]);

    $reservation = $app->databaseService->getReservationByToken($token);
    $reservation["duration"] = $app->helperService->formatDateDifference($reservation["start_datetime"], $reservation["end_datetime"]);

    $car = $app->databaseService->getCarById($reservation["car_id"]);

    $thankYouPageAttributes = array(
        "customer" => $customer,
        "reservation" => $reservation,
        "car" => $car,
        "domain" => DOMAIN,
        "google_maps_api_key" => GOOGLE_MAPS_API_KEY
    );

    $app->render('thankyou.twig', $thankYouPageAttributes);
})->name('kiitos');

$app->post("/laskeHinta", function() use($app) {
    $request = json_decode($app->request()->getBody());
    $reservation = $app->databaseService->getReservationByToken($request->token);
    // tyyppimuunnetaan string booleaniksi
    $extendedInsurance = ($request->extended_insurance === "true");
    $totalPrice = $app->reservationService->calculateTotalPrice($reservation, $request->mileage, $extendedInsurance);
    $output = [];
    $output["total_price"] = $totalPrice;
    $app->helperService->json(200, $output);
});

这和wordpress有什么关系?你想调用什么URL?结果是什么?你的期望是什么?