WordPress REST API endpoint doesn't respond - php

I have created a custom payment plugin now I need to set up an endpoint that will receive webhook callbacks from the payment gateway. My code for the endpoint is as seen below:
add_action('rest_api_init', function () {
register_rest_route(
'namespace/v1/', 'endpoint',
array (
'methods' => 'POST',
'callback' => 'return_payment_status'
)
);
});
function return_payment_status (WP_REST_Request $request_data) {
$pay_resp = array();
$params = $request_data->get_params();
if ( isset($params['result']) ) {
$pay_resp['result'] = $params['result'];
$pay_resp['message'] = $params['message'];
}
else {
$pay_resp['result'] = 'Payment failed';
$pay_resp['message'] = $params['message'];
}
return $pay_resp;
}
Now when I try the endpoint in POSTMAN and send data I get the following response:
{ "result":"Payment failed", "message":null }
Which seems that no data is being sent to the endpoint. What can I do to fix it?

Related

PayPal Express Error: Unexpected token S in JSON at position 0

I am integrating PayPal express checkout (server-side) in my PHP website. While I am integrating the PayPal express popup is not opening and it is giving me "Unexpected token S in JSON at position 0" in the console. Here is the screenshot https://prnt.sc/10f10qi
Here is HTML code:
<script src="https://www.paypal.com/sdk/js?client-id=<client-id>"></script>
<script>
paypal.Buttons({
createOrder: function() {
return fetch('paypal/create-payment.php', {
method: 'post',
headers: {
'content-type': 'application/json'
}
}).then(function(res) {
return res.json();
}).then(function(data) {
return data.id;
});
},
onAuthorize: function(data, actions) {
return actions.payment.execute().then(function() {
alert(data.orderID);
});
}
}).render('#paypal-button');
</script>
<div id="paypal-button"></div>
Here is the server side code for create-payment.php
<?php
namespace Sample\CaptureIntentExamples;
require __DIR__ . '/vendor/autoload.php';
//1. Import the PayPal SDK client that was created in `Set up Server-Side SDK`.
use Sample\PayPalClient;
use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
require 'paypal-client.php';
class CreateOrder
{
// 2. Set up your server to receive a call from the client
/**
*This is the sample function to create an order. It uses the
*JSON body returned by buildRequestBody() to create an order.
*/
public static function createOrder($debug=false)
{
$request = new OrdersCreateRequest();
$request->prefer('return=representation');
$request->body = self::buildRequestBody();
// 3. Call PayPal to set up a transaction
$client = PayPalClient::client();
$response = $client->execute($request);
if ($debug)
{
print "Status Code: {$response->statusCode}\n";
print "Status: {$response->result->status}\n";
print "Order ID: {$response->result->id}\n";
print "Intent: {$response->result->intent}\n";
print "Links:\n";
foreach($response->result->links as $link)
{
print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
}
// To print the whole response body, uncomment the following line
// echo json_encode($response->result, JSON_PRETTY_PRINT);
}
// 4. Return a successful response to the client.
return $response;
}
/**
* Setting up the JSON request body for creating the order with minimum request body. The intent in the
* request body should be "AUTHORIZE" for authorize intent flow.
*
*/
private static function buildRequestBody()
{
return array(
'intent' => 'CAPTURE',
'application_context' =>
array(
'return_url' => 'https://example.com/return',
'cancel_url' => 'https://example.com/cancel'
),
'purchase_units' =>
array(
0 =>
array(
'amount' =>
array(
'currency_code' => 'USD',
'value' => '220.00'
)
)
)
);
}
}
/**
*This is the driver function that invokes the createOrder function to create
*a sample order.
*/
if (!count(debug_backtrace()))
{
CreateOrder::createOrder(true);
}
?>
Please let me know what I am doing wrong? Thanks!

Wordpress custom endpoints (WP_REST_Controller) 404 only on mobile

I currently have a working controller that extends WP_REST_Controller in a file under the current theme. These are being called using jQuery ajax. (all code below)
The issue I am facing is that I receive this error ONLY when accessing with a mobile device.
{"code": "rest_no_route", "message": "No route was found matching the URL and request method" "data": {"status": 404}}
settings -> permalinks -> save changes
tried using controller namespace "api/v1" and "wp/v2"
javascript
function getAllClients() {
jQuery.ajax({
url: "http://myurl.com/index.php/wp-json/wp/v2/get_all_clients",
type: "GET",
data: { /*data object*/},
success: function (clientList) {
// success stuff here
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR.statusText);
}
})
}
api/base.php
<?php
class ApiBaseController extends WP_REST_Controller
{
//The namespace and version for the REST SERVER
var $my_namespace = 'wp/v';
var $my_version = '2';
public function register_routes()
{
$namespace = $this->my_namespace . $this->my_version;
register_rest_route(
$namespace,
'/get_all_clients',
array(
array(
'methods' => 'GET',
'callback' => array(new ApiDefaultController('getAllClients'), 'init'),
)
)
);
$ApiBaseController = new ApiBaseController();
$ApiBaseController->hook_rest_server();
api/func.php
<?php
class ApiDefaultController extends ApiBaseController
{
public $method;
public $response;
public function __construct($method)
{
$this->method = $method;
$this->response = array(
// 'Status' => false,
// 'StatusCode' => 0,
// 'StatusMessage' => 'Default'
// );
}
private $status_codes = array(
'success' => true,
'failure' => 0,
'missing_param' => 150,
);
public function init(WP_REST_Request $request)
{
try {
if (!method_exists($this, $this->method)) {
throw new Exception('No method exists', 500);
}
$data = $this->{$this->method}($request);
$this->response['Status'] = $this->status_codes['success'];
$this->response['StatusMessage'] = 'success';
$this->response['Data'] = $data;
} catch (Exception $e) {
$this->response['Status'] = false;
$this->response['StatusCode'] = $e->getCode();
$this->response['StatusMessage'] = $e->getMessage();
}
return $this->response['Data'];
}
public function getAllClients()
{
// db calls here
return json_encode($stringArr,true);
}
}
These are registered in the Functions.php file
require get_parent_theme_file_path('api/base.php');
require get_parent_theme_file_path('api/func.php');
Turns out the issue was a plugin my client installed called "oBox mobile framework" that was doing some weird routing behind the scenes. Disabling it resolved the issue, though there is probably a way to hack around this and get both to play together.

paypal success url error laravel

I'm using laravel Omni plugin for transactions. Once payment has been done , I'm getting error for success url.
public function checkOut(Request $request)
{
$params = array(
'cancelUrl' => 'http://localhost/vis/public/cancel_order',
'returnUrl' => 'http://localhost/vis/public/payment_success',
'name' => 'Meal',
'description' => 'Casper',
'amount' => '1.00',
'currency' => 'USD'
);
Session::put('params', $params);
Session::save();
$gateway = Omnipay::create('PayPal_Express');
$gateway->setUsername('un');
$gateway->setPassword('pwd');
$gateway->setSignature('signature');
$gateway->setTestMode(true);
$response = $gateway->purchase($params)->send();
if ($response->isSuccessful()) {
print_r($params);
redirect('payment_success/' . $this->orderNo);
// payment was successful: update database
print_r($response);
} elseif ($response->isRedirect()) {
// redirect to offsite payment gateway
$response->redirect();
} else {
// payment failed: display message to customer
echo $response->getMessage();
}
}
public function getSuccessPayment()
{
$gateway = Omnipay::create('PayPal_Express');
$gateway->setUsername('un');
$gateway->setPassword('pwd');
$gateway->setSignature('signature');
$gateway->setTestMode(true);
$params = Session::get('params');
$response = $gateway->completePurchase($params)->send();
$paypalResponse = $response->getData(); // this is the raw response object
if(isset($paypalResponse['PAYMENTINFO_0_ACK']) && $paypalResponse['PAYMENTINFO_0_ACK'] === 'Success') {
// Response
print_r($params);
// print_r($paypalResponse);
} else {
//Failed transaction
}
// return View('result');
print_r($params);
print_r($paypalResponse);
}
I'm getting following error
Not Found
HTTP Error 404. The requested resource is not found.
http://localhost/vis/public/payment_success?token=EC-1R845179Asss493N&PayerID=swdw3BS9REA4AN
It looks like you may have forgotten to add that route in the routes.php, Make sure you have something like this in routes.php
Route::get('/payment_success', 'StoreController#getSuccessPayment');
Change StoreController to the name of the controller this function is in.

Mandrill message not registered but status is sent

I am trying to send an email using Mandrill API using "messages/send-template" request
in return I receive the following response:
[
{
email: "test#email.com",
status: "sent",
_id: "8ff773d1c683434891cee94e461e53e7",
reject_reason: null
}
]
but when i try to execute "messages/info" request I get an error
Mandrill_Unknown_Message: No message exists with the id '8ff773d1c683434891cee94e461e53e7'
I use the following code for those actions:
$message_data = array(
'text' => '123',
'from_email' => 'sender#email.com',
'to' => array(
array('email' => 'test#email.com')
),
);
try {
$md_message = $this->_mandrill->messages->send($message_data);
foreach($md_message as $message) {
if($message['status'] != 'sent') {
trigger_error("Internal Error (Mandrill): ".$message['reject_reason']);
return false;
}
$info = $this->_mandrill->messages->info($message['_id']);
}
return true;
} catch (Exception $m) {
trigger_error("Internal Error (Mandrill): ".$m->getMessage());
return false;
}
Also the message doesn't appear in the control panel at Mandrill
Ok, Looks like test API key won't get any messages recorded.
I created a new API key (not test) - and it worked =]
Cheers

why coinbase callback url not working?

i have the below code for button creation.
public function createButton($name, $price, $currency, $custom=null, $options=array(),$callback)
{
// $callback=$this->generateReceiveAddress("http://www.tgigo.com");
// print_r($callback);exit;
$params = array(
"name" => $name,
"price_string" => $price,
"price_currency_iso" => $currency,
"callback_url"=>"http://www.tgigo.com"
);
if($custom !== null) {
$params['custom'] = $custom;
}
foreach($options as $option => $value) {
$params[$option] = $value;
}
return $this->createButtonWithOptions($params);
}
public function createButtonWithOptions($options=array())
{
$response = $this->post("buttons", array( "button" => $options ));
if(!$response->success) {
return $response;
}
$returnValue = new stdClass();
$returnValue->button = $response->button;
$returnValue->embedHtml = "<div class=\"coinbase-button\" data-code=\"" . $response->button->code . "\"></div><script src=\"https://coinbase.com/assets/button.js\" type=\"text/javascript\"></script>";
$returnValue->success = true;
return $returnValue;
}
and i have the below response for above code.
{"success":true,"button":{"code":"675cda22e31b314db557f0538f8ad27e","type":"buy_now","style":"buy_now_large","text":"Pay With Bitcoin","name":"Your Order #1234","description":"1 widget at $100","custom":"my custom tracking code for this order","callback_url":"http://www.tgigo.com","price":{"cents":100000,"currency_iso":"BTC"}}}
using this code payment process completed,but not redirected to the call back url.
any one please help me.
Thanks in advance :)
The callback_url parameter is for a callback that receives a POST request behind the scenes when payment is complete. The user's browser is not redirected there. You probably want success_url.
https://coinbase.com/api/doc/1.0/buttons/create.html

Categories