Sorry, that page does not exist [code] => 34 - php

POST /statuses/retweet is giving me this error while POST statuses/tweet and GET search/tweets are working fine.
public $host = "https://api.twitter.com/1.1/";
$con = $this->oauth();
$retweets = $con->post('statuses/retweet/', array('id' => $searchid));
The query will get the Status id_str of the object. It is in string format.
/**
* POST wrapper for oAuthRequest.
*/
function post($url, $parameters = array()) {
$response = $this->oAuthRequest($url, 'POST', $parameters);
if ($this->format === 'json' && $this->decode_json) {
return json_decode($response);
}
return $response;
}
API console gives me no error:
https://api.twitter.com/1.1/statuses/retweet/{id}.json

If you want to retweet the tweet with ID 1234 you need to send a POST request to
https://api.twitter.com/1.1/statuses/retweet/1234.json
It looks like you are trying to perform a GET request to
https://api.twitter.com/1.1/statuses/retweet/?id=1234

figured it out. Retweet ID cant be sent as paramemeter. It has to be added as part of url.
This is what i did. parameter to be null
$retweets = $con->post('statuses/retweet/'.$searchid, null);

Related

unit testing: send parameters to endpoint

my question is how to send parameter to my endpoint.
test
public function test_upgrade()
{
$billingChange3 = factory(Plan::class)->create([
'user_id' => 1,
'previous_price' => 150,
'current_price' => 100,
]);
$url = route(
'users.filters'
);
$response = $this->actingAs($this->admin)->getJson($url,['search'=>'upgrade']);
$response->assertStatus(200);
//till here correct
//but here it should return 2 since I have upgrade count 2 as correct it gives error
my api response is wrapped within data, so i have used data below
$response->assertJsonCount(2,'data');
}
my seach keyword can be any thing such as upgrade,downgradeetc. upgrade is whencurrent_price>previous_price``` and I have logic for that in controller
My vue dev tool shows url as below:
first:"https://localhost:800/users/plan?filter=upgrade&page=1"
In test I have passed params as getJson($url,['search'=>'upgrade']
Is that the correct way to pass paramters?
Not correct. See function signature - you pass headers:
public function getJson($uri, array $headers = [])
{
return $this->json('GET', $uri, [], $headers);
}
Correct way:
$response = $this
->actingAs($this->admin)
->getJson(route('users.filters', ['search'=>'upgrade']));

How do I get response from object sent via a request with wordpress api

I have registered a api request the following way in the code, then in postman I call that request and add some params, but when I run the api request endpoint it returns null.
How do I return the data that's being sent?
/**
* This is our callback
* function that embeds our phrase in a WP_REST_Response
*/
function addProductFromCRM($data) {
//$name = $data['name'];
// rest_ensure_response() wraps the data we want to return into a WP_REST_Response, and ensures it will be properly returned.
return rest_ensure_response($data);
}
/**
* This function is where we register our routes for our example endpoint.
*/
function wp_register_crm_routes() {
// register_rest_route() handles more arguments but we are going to stick to the basics for now.
register_rest_route('crm/v1', '/addproduct/', array(
// By using this constant we ensure that when the WP_REST_Server changes our readable endpoints will work as intended.
'methods' => 'POST',
// Here we register our callback. The callback is fired when this endpoint is matched by the WP_REST_Server class.
'callback' => 'addProductFromCRM',
));
}
add_action('rest_api_init', 'wp_register_crm_routes');
What addproduct endpoint should return? JSON? You can do something like this:
function addProductFromCRM($request) {
wp_send_json($request->get_params());
}
You can use below code snippet as per you need like on isset($_POST) or any other callback function. You must have the idea of your Register Route URL and must be working. you can use wp_remote_get or wp_remote_post as per your need. for more reference please check WordPress official site
$response = wp_remote_get("URL TO YOUR REGISTER ROUTE");
if ( is_array( $response ) ) {
$response_code = wp_remote_retrieve_response_code( $response );
$body = wp_remote_retrieve_body( $response );
$body_data = json_decode($body);
}

Making a api call to a third party api after receiving data form $.ajax call

I'm making a $.ajax post call to a controller on cakephp to send some data to the controller and then use that data to connect to a 3rd party API and create a link, the $.ajax call works as expected and I get the post data however there's a problem with call to the 3rd party API,
public function createLinks() {
if ($this->request->is('ajax') ) {
$this->autoRender = false;
}
if ($this->request->isPost()) {
$link = $this->request->data['spotifyLink'];
$token = $this->request->data['accessToken'];
$boardID = $this->request->data['boardID'];
$trackTitle = $this->request->data['trackTitle'];
}
$apiLink = 'https://api.linkfire.com/campaigns/boards/'.$boardID.'/links';
$body = array("track" => $trackTitle,"baseUrl" => $link);
$http = new Client();
$response = $http->post($apiLink, $body,
['headers' =>['Authorization' => 'Bearer '.$token,
'content-type' => 'application/json']]);
echo json_encode($response);
}
this is what I'm getting back
{"readyState":4,"responseText":"{}","responseJSON":{},"status":200,"statusText":"OK"}
my question is can I receive the post data from ajax call and make the http->post call in the same function? Is there any error in the above code because the $http->post call doesnt seem to work, any help would be appreciated.
if I change echo json_encode($response); to return $response; I get the 500 internal server error and in the log file it says
Controller actions can only return Cake\Http\Response or null

Created Request using die() also dies the Request caller

I don't know if it's the right terms to employ...
I made an API, in which the answer is sent by the die() function, to avoid some more useless calculations and/or functions calls.
example :
if (isset($authorize->refusalReason)) {
die ($this->api_return(true, [
'resultCode' => $authorize->resultCode,
'reason' => $authorize->refusalReason
]
));
}
// api_return method:
protected function api_return($error, $params = []) {
$time = (new DateTime())->format('Y-m-d H:i:s');
$params = (array) $params;
$params = ['error' => $error, 'date_time' => $time] + $params;
return (Response::json($params)->sendHeaders()->getContent());
}
But my website is based on this API, so I made a function to create a Request and return the contents of it, based on its URI, method, params, and headers:
protected function get_route_contents($uri, $type, $params = [], $headers = []) {
$request = Request::create($uri, $type, $params);
if (Auth::user()->check()) {
$request->headers->set('S-token', Auth::user()->get()->Key);
}
foreach ($headers as $key => $header) {
$request->headers->set($key, $header);
}
// things to merge the Inputs into the new request.
$originalInput = Request::input();
Request::replace($request->input());
$response = Route::dispatch($request);
Request::replace($originalInput);
$response = json_decode($response->getContent());
// This header cancels the one there is in api_return. sendHeaders() makes Content-Type: application/json
header('Content-Type: text/html');
return $response;
}
But now when I'm trying to call an API function, The request in the API dies but dies also my current Request.
public function postCard($token) {
$auth = $this->get_route_contents("/api/v2/booking/payment/card/authorize/$token", 'POST', Input::all());
// the code below is not executed since the API request uses die()
if ($auth->error === false) {
return Redirect::route('appts')->with(['success' => trans('messages.booked_ok')]);
}
return Redirect::back()->with(['error' => $auth->reason]);
}
Do you know if I can handle it better than this ? Any suggestion of how I should turn my code into ?
I know I could just use returns, but I was always wondering if there were any other solutions. I mean, I want to be better, so I wouldn't ask this question if I knew for sure that the only way of doing what I want is using returns.
So it seems that you are calling an API endpoint through your code as if it is coming from the browser(client) and I am assuming that your Route:dispatch is not making any external request(like curl etc)
Now There can be various approaches to handle this:
If you function get_route_contents is going to handle all the requests, then you need to remove the die from your endpoints and simply make them return the data(instead of echoing). Your this "handler" will take care of response.
Make your Endpoint function to have an optional parameter(or some property set in the $request variable), which will tell the function that this is an internal request and data should be returned, when the request comes directly from a browser(client) you can do echo
Make an external call your code using curl etc(only do this if there is no other option)

2 legged oath request without command line

i want to make an 2 legged oauth yql request with php.
So far:
// Include the PHP SDK.
include_once("yosdk/lib/Yahoo.inc");
// Define constants to store your API Key (Consumer Key) and
// Shared Secret (Consumer Secret).
define("API_KEY","her_comes the key");
define("SHARED_SECRET","here_comes_the_secret");
$two_legged_app = new YahooApplication(API_KEY,SHARED_SECRET);
$stock_query = "elect * from ......";
$stockResponse = $two_legged_app->query($stock_query);
var_dump($stockrResponse);
But the problem is, that i dont want to query the command line..... i just want to oauth with the api key i got and use the url directly i got of the command when i typed in yql....
like this:
$url='http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20('+url_stocks+')&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';
(i edited the url that came out my wishes for).Please dont ask why i dont use the command to query (long story). i would be pleased by getting some help.
thanks.
solved it:
http://code.google.com/p/oauth-php/wiki/ConsumerHowTo
include_once "oauth/library/OAuthStore.php";
include_once"oauth/library/OAuthRequester.php";
$key_1 = "your_key"; $secret_1 = "your_secret";
$ticks="%22AAPL%22%2C%22MSFT%22";
$options = array( 'consumer_key' => $key_1, 'consumer_secret' =>
$secret_1 ); OAuthStore::instance("2Leg", $options );
$url =
"http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20('$ticks')&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
// this is the URL of the request $method = "GET"; // you can also use
POST instead $params = null;
try {
// Obtain a request object for the request we want to make
$request = new OAuthRequester($url, $method, $params);
// Sign the request, perform a curl request and return the results,
// throws OAuthException2 exception on an error
// $result is an array of the form: array ('code'=>int, 'headers'=>array(), 'body'=>string)
$result = $request->doRequest();
$response = $result['body'];
$resp_array=json_decode($response,TRUE);
echo $resp_array['query']['results']['quote'][1]['symbol']; // MSFT
} catch(OAuthException2 $e) { }

Categories