How to authorize API endpoint through header using wp_remote_get()? - php

I am testing API Football on my WP site and facing a difficulty in authentication. I have tested endpoint on postman and everything works fine but as soon as I test it on WP it gives me following response with error:
{ "get": "status", "parameters": [], "errors": { "token": "Error/Missing application key. Go to https://www.api-football.com/documentation-v3 to learn how to get your API application key." }, "results": 0, "paging": { "current": 1, "total": 1 }, "response": [] }
My WP code is:
$response = wp_remote_get( 'https://v3.football.api-sports.io/status', array(
'headers' => array(
'x-apisports-key' => $this->api_key
)
) );
$response_body = wp_remote_retrieve_body( $response );
return json_decode( $response_body );
I have tried php curl too but still getting same problem. For some reason I don't want to try it on rapidapi.
I have tried php cURL too but still getting same error. For some reasons I don't want to use rapidapi.

Related

Paymongo can't disable a webhook

I am trying to disable a webhook of Paymongo via the web console, but it seems I can not disable the webhook. When I do so, the interface shows the error like so:
{
"errors": [
{
"code": "resource_processing_state",
"detail": "Webhook with id hook_L0r3mIp5umD0L0r5itAm3t is still being processed."
}
]
}
It also has a 400 HTTP status code and its PHP code look like so:
<?php
require_once('vendor/autoload.php');
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'https://api.paymongo.com/v1/webhooks/hook_L0r3mIp5umD0L0r5itAm3t/disable', [
'headers' => [
'accept' => 'application/json',
'authorization' => 'Basic someBase64encodedStringOfAKey',
],
]);
echo $response->getBody();
Note: The shown codes above don't contain the exact credentials. I edited these before posting here for privacy reasons.
What does it mean by "Webhook with id hook_L0r3mIp5umD0L0r5itAm3t is still being processed."?

Slim 4 Framework: Unable to pass a payload to test a POST route

I'm totally new to Slim 4 but I've successfully managed to create a project and write API endpoint that does some calculation.
It's a POST route and it requires a JSON payload. In Postman I send a POST to http://localhost:8089/api/discounts/calculate with:
{
"order": {
"id": "1",
"customer-id": "1",
"items": [
{
"product-id": "B102",
"quantity": "10",
"unit-price": "4.99",
"total": "49.90"
}
],
"total": "49.90"
},
"discount_strategy": "overall_percentage_from_total"
}
and in a response I get HTTP 200 OK which is what I expect. Everything works perfectly fine, but not in PHPUnit.
I want to create a test for this endpoint so I've created new test class that extends TestCase and it has access to this protected method: https://github.com/slimphp/Slim-Skeleton/blob/master/tests/TestCase.php#L71
So I wrote:
public function testOrder1AgainstOverallPercentageFromTotal()
{
$app = $this->getAppInstance();
$payload = [
'order' => [
'id' => 1,
'customer-id' => 1,
'items' => [
'product-id' => 'B102',
'quantity' => '10',
'unit-price' => '4.99',
'total' => '49.90',
],
'total' => '49.90',
],
'discount_strategy' => 'overall_percentage_from_total',
];
$req = $this->createRequest('POST', '/api/discounts/calculate');
$request = $req->withParsedBody($payload);
$response = $app->handle($request);
//var_dump($response->getBody()->getContents()); die;
$this->assertEquals(200, $response->getStatusCode());
}
but it always gives me HTTP 400 saying that:
Malformed JSON input
When I dump getBody() or getContents() I get either a hollow object or or empty string for contents.
There was 1 failure:
1) Tests\Functional\CalculateDiscountsActionTest::testOrder1AgainstOverallPercentageFromTotal
Failed asserting that 400 matches expected 200.
What am I doing wrong?
My calculation logic is in an Action class that extents App\Application\Actions\Action and I'm able to access the payload I send in Postman with: $input = $this->getFormData();. This is a stdClass but it's enough for me to grab the input and do the job.
Why PHPUnit doesn't see my payload?
Make sure you add the correct HTTP headers and body content to the request object.
$request->getBody()->write((string)json_encode($data));
$request = $request->withHeader('Content-Type', 'application/json');
Full example:
protected function createJsonRequest(string $method, $uri, array $data = null): ServerRequestInterface
{
$request = $this->createRequest($method, $uri);
if ($data !== null) {
$request->getBody()->write((string)json_encode($data));
}
return $request->withHeader('Content-Type', 'application/json');
}
Usage:
$payload = [];
$request = $this->createJsonRequest('POST', '/api/discounts/calculate', $payload);
$response = $app->handle($request);
// Assert the response
// ...
More examples

LinkedIn Share API 'ugcPosts' response 504 gateway timeout from PHP(Wordpress)

I'm using wordpress to shared my post into linkedIn. For this i'm using https://api.linkedin.com/v2/ugcPosts API. But this API response return 504 gateway timeout.
In previous step when i called another API to get access token, its easily got the access token. But when I wanted to create a share using ucPosts POST api request it providing gateway time out.
My requested code here.
Please any one help me.
Tried from localhost apache server(PHP, wordpress)
$params = '{
"author" : "urn:li:person:'.$linkedInAppCredentials->get_user_URN().'",
"lifecycleState" : "PUBLISHED",
"specificContent" : {
"com.linkedin.ugc.ShareContent" : {
"shareCommentary" : {
"text" : "'.$message.'"
},
"shareMediaCategory" : "NONE"
}},
"visibility" :"PUBLIC"
}';
$headers = '{
"Content-Type": "application/json",
"X-Restli-Protocol-Version": "2.0.0",
"x-li-format": "json",
"Connection": "Keep-Alive",
"Authorization": "Bearer '.$linkedInAppCredentials->getAccessToken().'"
}';
$requestedUrl = "https://api.linkedin.com/v2/ugcPosts?oauth2_access_token=".$this->getAccessToken();
$requestBody = array(
'headers' => $header,
'timeout' => 3600,
'body' => $params
);
$result = wp_remote_post($requestedUrl, $requestBody);
Response:
[body] => {"message":"Request timed out","status":504}
[response] => Array
(
[code] => 504
[message] => Gateway Timeout
)
Request timeout may be happening because LinkedIn is not able to parse the request body. So it might be a good idea to convert the requestBody to a JSON string. Giving a proper JSON input worked for me I was having the same problem.
As was happening with another person:
https://stackoverflow.com/a/56786205/12578136

Paypal Adaptivepayments Issue when requesting from cURL

Im creating a simple web application in php that consume the adaptivePayments/Pay Api of paypal, I made some test using POSTMAN and everything works fine, I make the initial request and I get my payKey, also with this payKey I can check the status of the transaction using the /AdaptivePayments/PaymentDetails Api, the problem is when I try to make the request via php code:
$endpoint = 'https://svcs.sandbox.paypal.com/AdaptivePayments/Pay';
$payload['actionType'] = "PAY";
$payload['clientDetails']['applicationId'] = "APP-80W284485P519543T";
$payload['clientDetails']['ipAddress'] = "xxx.xxx.xxx.xxx";
$payload['currencyCode'] = "USD";
$payload['feesPayer'] = "EACHRECEIVER";
$payload['memo'] = "Transaction";
$payload['receiverList']['receiver'] = $receivers;
$payload['requestEnvelope']['errorLanguage'] = "en_US";
$payload['returnUrl'] = "URL";
$payload['cancelUrl'] = "URL";
$json = json_encode($payload);
$ch = curl_init($endpoint);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'X-PAYPAL-SECURITY-USERID: ACCOUNT',
'X-PAYPAL-SECURITY-PASSWORD: PASSWORD',
'X-PAYPAL-SECURITY-SIGNATURE: SIGNATURE',
'X-PAYPAL-REQUEST-DATA-FORMAT: JSON',
'X-PAYPAL-RESPONSE-DATA-FORMAT: JSON',
'X-PAYPAL-APPLICATION-ID: APP-80W284485P519543T',
'Content-Type: application/json',
'Content-Length: ' . strlen($json)
));
$result = curl_exec($ch);
$receivers is a PHP array that contain information about emails and payment amounts, something like this:
Array
(
[0] => Array
(
[amount] => 19.8
[email] => client2-ubs#gmail.com
[primary] =>
)
[1] => Array
(
[amount] => 20.7
[email] => client1-ubs#gmail.com
[primary] =>
)
[2] => Array
(
[amount] => 45
[email] => store-ubs#gmail.com
[primary] => 1
)
)
I dont get any error, I even get the payKey which I use to create the html button so the user can pay for his goods, the problem is when I check the payment status /AdaptivePayments/PaymentDetails, Im getting:
{
"responseEnvelope": {
"timestamp": "2015-08-06T23:59:23.075-07:00",
"ack": "Success",
"correlationId": "bab22ca0bd887",
"build": "17603431"
},
"cancelUrl": "https://23410a33.ngrok.com/universal-bank-of-souls/",
"currencyCode": "USD",
"paymentInfoList": null,
"returnUrl": "https://23410a33.ngrok.com/universal-bank-of-souls/",
"status": "CREATED",
"payKey": "AP-8ML17897XK803351A",
"actionType": "PAY",
"feesPayer": "EACHRECEIVER",
"sender": {
"useCredentials": "false"
}
}
for some strange reason paymentInfoList is null, so the user see an error (transaction error) at the moment of click the paypal button.
As I said before, If i made the transaction using POSTMAN and then check the status I get a correct response:
{
"responseEnvelope": {
"timestamp": "2015-08-07T00:14:08.510-07:00",
"ack": "Success",
"correlationId": "b9049ba0d4cf1",
"build": "17603431"
},
"cancelUrl": "URL",
"currencyCode": "USD",
"memo": "Bank of souls payment",
"paymentInfoList": {
"paymentInfo": [
{
"receiver": {
"amount": "123.30",
"email": "client2-ubs#gmail.com",
"primary": "false",
"paymentType": "SERVICE",
"accountId": "SLKM4ZQ5FMSHG"
},
"pendingRefund": "false"
},
{
"receiver": {
"amount": "510.30",
"email": "client1-ubs#gmail.com",
"primary": "false",
"paymentType": "SERVICE",
"accountId": "8PUDR7LSRS4MJ"
},
"pendingRefund": "false"
},
{
"receiver": {
"amount": "704.00",
"email": "store-ubs#gmail.com",
"primary": "true",
"paymentType": "SERVICE",
"accountId": "E29BAQX7C7P3N"
},
"pendingRefund": "false"
}
]
},
"returnUrl": "URL",
"status": "CREATED",
"payKey": "AP-9MU4806743660523S",
"actionType": "PAY",
"feesPayer": "EACHRECEIVER",
"reverseAllParallelPaymentsOnError": "false",
"sender": {
"useCredentials": "false"
}
}
(paymentInfoList actually contains a json object with the goods, but this is doing the request manually using POSTMAN)
Could this be a PHP issue? some ideas to debug the curl connection will help me a lot.
PD: I have been debuging this the whole day, I even print_r the $json variable (i get the json format) and copy / paste directly in postman and its works, but for some reason the same request using curl is not sending the $receivers information.
Solved, I was making the requests (create the order and the request order information) using two different api credentials, also, it seems that paypal hide the order goods when receiving api credentials different than the originals, however still showing the state of the order (CREATE, COMPLETED, etc)

Facebook PHP Graph API not returning complete data

I'm having an issue with Facebook's PHP SDK version 4.0.
I'm simply trying to retrieve the insights/page_fans_city metric via the Graph API:
$request = new FacebookRequest($session, 'GET',
'/{my object}/insights/page_fans_city',
array('period' => 'lifetime'));
$response = $request->execute();
$client_graph_object = $response->getGraphObject();
print_r($client_graph_object);
However, no data is returned:
Facebook\GraphObject Object
(
[backingData:protected] => Array
(
[data] => Array
(
)
[paging] => stdClass Object
(
[previous] => https://graph.facebook.com/v2.0/...
[next] => https://graph.facebook.com/v2.0/...
)
)
)
I know that I have the Insights data that I'm requesting. I can make the exact same request via the Graph Explorer:
→ /v.2.0/{my object}/insights/page_fans_city?period=lifetime
{
"data": [
{
"id": "{my object}/insights/page_fans_city/lifetime",
"name": "page_fans_city",
"period": "lifetime",
"values": [
{
"value": {
...
},
"end_time": "2014-08-01T07:00:00+0000"
},
{
"value": {
...
},
"end_time": "2014-08-02T07:00:00+0000"
}
],
"title": "Lifetime Likes by City",
"description": "Lifetime: Aggregated Facebook location data, sorted by city, about the people who like your Page. (Unique Users)"
}
],
"paging": {
"previous": "https://graph.facebook.com/v2.0/...,
"next": "https://graph.facebook.com/v2.0/...
}
}
I should note that I am receiving data if I omit the page_fans_city segment. When it's omitted- I can view data for page_fans_country only. Therefore
$request = new FacebookRequest($session, 'GET',
'/{myobject}/insights/page_fans_country',
array('period' => 'lifetime'));
and
$request = new FacebookRequest($session, 'GET',
'/{myobject}/insights',
array('period' => 'lifetime'));
will work for me ...
I suspect it's my Access token- but I'm not sure why that would be the case. The app that I created only requires the read_insights permission.
Any thoughts or suggestions?
Thanks in advance,Mike
It was a permissions issue. If you ever see:
{
"data": [
],
...
}
It's likely your access token does not have sufficient privileges to access the data you're requesting (that or there's simply no data).
My problem was that even though I was the Developer of the app and it was approved by Facebook (with the manage_pages and read_insights permissions)- I could not use an app access token to retrieve the insights data.
I needed a user access token!
I easily generated the user access token by manually creating a login flow per Facebook's documentation. This stackoverflow thread was useful, too.
More info on Facebook tokens here.
Hope this helps anyone who stumbles across this thread!
-Mike

Categories