Error Paypal REST API (sandbox) 404:"The requested URL /cgi-bin/ppapi was not found on this server." - paypal

I'm using PHP curl and it is communicating with the server. I'm trying to get a token. I get the following unhelpful response from the paypal sandbox:
Not Found
The requested URL /cgi-bin/ppapi was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
Apache Server at api.sandbox.paypal.com Port 443
I'm running the code (below) from localhost on my laptop.
/gettoken.php
<?php
//header('Content-Type:application/javascript');
$url = "https://api.sandbox.paypal.com/token";
$client_id = "xxx";
$secret = "xxx";
// Initiate curl
$ch = curl_init();
// set basic auth
curl_setopt($ch,CURLOPT_HTTPAUTH,CURLAUTH_BASIC);
// set user/password
curl_setopt($ch,CURLOPT_USERPWD,$client_id.":".$secret);
// set header accept
$headers = array('Accept:application/json','Accept-Language:en_US');
curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
// set mode to POST
curl_setopt($ch,CURLOPT_POST,1);
// add post fields (1)
$fields_string = "grant_type=client_credentials";
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
// Disable SSL verification
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
if($result === false)
{
echo 'Curl error: ' . curl_error($ch);
}
// close curl
curl_close($ch);
// decode result
//var json = json_decode($result, true);
echo('<pre>'.$result.'</pre>');
?>

My apologies, the url to the REST service was wrong.. should have been:
https://api.sandbox.paypal.com/v1/oauth2/token
At least we know that if you get this error that it is likely the REST endpoint url is probably wrong.

Related

Error code 500: Internal server error (ReactPHP)

I tried to make a server file for my ReactPHP app following this video but when I started up the server, it ran successfully, but when I made a simple http GET the response was "Error code
500: Internal server error", when in theory it should've returned a JSON {"message": "Hello"}.
Here is the code for the server.php file:
use React\Http\Server;
use React\Http\Response;
use Psr\Http\Message\ServerRequestInterface;
use \React\EventLoop\Factory;
require 'vendor/autoload.php';
$loop = Factory::create();
$server = new Server(function (ServerRequestInterface $request) {
return new Response(
200, ['Content-Type' => 'application/json'], json_encode(['message' => 'Hello'])
);
});
$socket = new \React\Socket\Server('127.0.0.1:8000', $loop);
$server->listen($socket);
echo "Listening on ".str_replace('tcp', 'http', $socket->getAddress()). PHP_EOL;
$loop->run();
request.http file:
GET 127.0.0.1:8000
What the request has returned:
HTTP/1.1 500 Internal Server Error
Content-Type: text/plain
Server: ReactPHP/1
Date: Fri, 20 Aug 2021 09:03:19 GMT
Content-Length: 32
Connection: close
Error 500: Internal Server Error
Can someone say to me what the problem is? I think I miswrote something in the server.php file but I am not the one to tell
Code you use from a video is a bit outdated.
If you need a quickfix - just replace one line and it will work:
--- use React\Http\Response;
+++ use React\Http\Message\Response;
Working code for this example (as for react/http-1.5.0) would be
use Psr\Http\Message\ServerRequestInterface;
use React\EventLoop\Loop;
use React\Http\HttpServer;
use React\Http\Message\Response;
use React\Socket\SocketServer;
require_once __DIR__ . '/vendor/autoload.php';
$loop = Loop::get();
$server = new HttpServer(function (ServerRequestInterface $request) {
return new Response(
200, ['Content-Type' => 'application/json'], json_encode(['message' => 'Hello'])
);
});
$socket = new SocketServer('127.0.0.1:8000');
$server->listen($socket);
echo 'Listening on ' . str_replace('tcp', 'http', $socket->getAddress()) . PHP_EOL;
$loop->run();
List of changes:
Response class location (actual fix)
loop factory changed, deprecation upFactory::create() -> Loop::get
http-server changed React\Http\Server -> React\Http\HttpServer
socket-server changed React\Socket\Server -> React\Socket\SocketServer
The answer provided by Ilya Urvachev is the right one, basically react evolved and the Response class is not located in the same location anymore.
Overall after instantiating your server I recommend you to use this line of code so you get error messages in your command line interface:
$server->on('error', function (Exception $exception) {
echo $exception->getMessage() . PHP_EOL;
});
All in all, It's been very difficult for me to move from regular PHP to reactphp, which completely destroy the verbosity of error messages. Ie. You've got exception telling you that the format of the answer is not the expected one, while, what really fucks up your code is that have an error in the syntax of one of your MySQL queries, which sends back a message that is not respecting the expecting answer's format. If someone wants to provide additional way to improve the reactphp verbosity, feel free :)

problems with paypal module

is anyone ever tried this module NET::PayPal
because i tried it and i was getting this error
Authorization failed : 401 Unauthorized, {"error":"invalid_client","error_description":"Client Authentication failed"}
and am using valid client id and secret id
use Net::PayPal;
$client_id = 'asdasdasdasdsadasdasd';
$client_secret = 'sadasdasdsadasdsad';
my $p = Net::PayPal->new($client_id, $client_secret);
my $payment = $p->get_payment( 'PAY-9D023728F47376036KE5OTKY' );
According to the documentation, Net::PayPal always starts out in sandbox mode. You have to switch it to live mode in order to use your production credentials.
Net::PayPal->live( 1 );
my $pp = Net::PayPal->new($client_id, $secret);

Test a Symfony REST API using Behat / Mink : prb with POST request

My challenge here is to find the best way to test a Symfony (3.4) API application using Behat/Mink for functionnal test, in my CICD platform.
Because my testing processes must be called in a shell script, all the tests must be very linear. I have no way to start a standalone webserver like Apache or the PHP/Symfony webserver. Also, Docker is not an option.
For the moment, I can successfully test the GET verbs of the API using the Mink syntax :
-- file test.feature
#function1
Scenario Outline: Test my api
When I go to "/api/v1/hello"
Then the response is JSON
The "I go to" instruction is implemented by Mink (http://docs.behat.org/en/v2.5/cookbook/behat_and_mink.html) and it emulates a GET request only. When this instruction is called by BeHat, the app Symfony kernel is "spawned" and the "api/v1/hello" method is called internally : there is no network trafic, no TCP connection, there is no need for a dedicated webserver (apache, or the symfony standalone server). It looks like Behat is emulating a webserver and start by itself the Symfony app it its own user space.
Now I want to test the POST verbs of my API, with a json payload, but unfortunally Mink do not have other verbs than GET.
I have read some articles over the web (keyword : behat test post api) but all I have seen is based on a Guzzl/Curl client. So a real client-to-server connection is made to http://localhost and a real webserver have to respond to the request.
I want the Symfony API to be called internally without using an other webserver.
Is there a way to do that ? How to test a Symfony REST API and specially the POST verb without needing a standalone server to reply ?
Thank you.
Here is how I do a functional test of a POST API, with BeHat, without a local running webserver :
test.feature :
#function1
Scenario Outline: Test my api
Given I have the payload
"""
{ "data":"object"}
"""
When I request "POST /api/v1/post"
Then the response is JSON
The featureContext file implement two functions :
"I Have The Payload" : See here https://github.com/philsturgeon/build-apis-you-wont-hate/blob/master/chapter8/app/tests/behat/features/bootstrap/FeatureContext.php
"I request" : based on code provided by philsturgeon just above, I modify it to have something like that :
/**
* #When /^I request "(GET|PUT|POST|DELETE|PATCH) ([^"]*)"$/
*/
public function iRequest($httpMethod, $resource)
{
$this->lastResponse = $this->lastRequest = null;
$this->iAmOnHomepage();
$method = strtoupper($httpMethod);
$components = parse_url($this->getSession()->getCurrentUrl());
$baseUrl = $components['scheme'].'://'.$components['host'];
$this->requestUrl = $baseUrl.$resource;
$formParams = json_decode($this->requestPayload, true);
$formParamsList = [];
foreach($formParams as $param => $value) {
$formParamsList[$param] = json_encode($value);
}
// Construct request
$headers = [
'Accept'=>'application/json',
'Content-Type'=>'application/x-www-form-urlencoded'
];
try {
// Magic is here : allow to simulate any HTTP verb
$client = $this->getSession()->getDriver()->getClient();
$client->request(
$method,
$this->requestUrl,
$formParamsList,
[],
$headers,
null);
} catch (BadResponseException $e) {
$response = $e->getResponse();
// Sometimes the request will fail, at which point we have
// no response at all. Let Guzzle give an error here, it's
// pretty self-explanatory.
if (null === $response) {
throw $e;
}
$this->lastResponse = $e->getResponse();
throw new \Exception('Bad response.');
}
}
If you use Mink then it is quite easy
class FeatureContext extends RawMinkContext
{
/**
* #When make POST request to some Uri
*/
public function makePostRequestToSomeUri(): void
{
$uri = '/some-end-point';
/** #var \Symfony\Component\BrowserKit\Client $client */
$client = $this->getSession()->getDriver()->getClient();
$postParams = [];
$files = [];
$serverParams = [];
$rawContent = '';
$client->request(
\Symfony\Component\HttpFoundation\Request::METHOD_POST,
$uri,
$postParams,
$files,
$serverParams,
$rawContent
);
/** #var \Symfony\Component\HttpFoundation\Response $response */
$response = $client->getResponse();
//...
}
}

Powershell - Querying URL with login and returning HTTP Status

I'm using a standard [System.Net.WebRequest] class to return the HTTP response code of a given URL.
The URL points to an internal web application server, which returns a "401 Unauthorised" error. This is actually OK as the service account running the script doesn't have a valid account to the application. However, I am more interested that the website is responding. However, I assumed that this is a HTTP Response in itself so I could manage this, but instead it returned as a null value.
$HTTP_Request = [System.Net.WebRequest]::Create('http://google.com')
$HTTP_Response = $HTTP_Request.GetResponse()
$HTTP_Status = [int]$HTTP_Response.StatusCode
Exception calling "GetResponse" with "0" argument(s): "The remote
server returned an error: (407) Proxy Authentication Required."
(I'm using Google in this example, which our servers are blocked from accessing external sites).
So I can't get as far as $HTTP_Status = [int]$HTTP_Response.StatusCode in the code because it won't accept 400 errors as a code.
How can I accept a 401 (or 407 in this example) in the query?
Thanks
Got it!
try{
$request = $null
$request = Invoke-WebRequest -Uri "<URL>"
}
catch
{
$request = $_.Exception.Response
}
$StatusCode = [int] $request.StatusCode;
$StatusDescription = $request.StatusDescription;
You could've done:
$HTTP_Request = [System.Net.WebRequest]::Create('http://google.com')
$HTTP_Request.Method = "GET"
$HTTP_Request.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
[System.Net.HttpWebResponse]$HTTP_Response = $HTTP_Request.GetResponse()
Try {
$HTTP_Status = [int]$HTTP_Response.StatusCode
}
Catch {
#handle the error if you like, or not...
}
If ($HTTP_Status -eq 200) {
Write-Host "Good Response"
} Else {
Write-Host "Site Down or Access Denied"
}
# If you got a 404 Not Found, the response will be null so can't be closed
If ($HTTP_Response -eq $null) { } Else { $HTTP_Response.Close() }
You were missing the authentication piece:
$HTTP_Request.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
I re-read your post and because your service account did not have access to the URL you are hitting (which was not actually google.com... you should've put myserver.com...grr), you would never actually get a 200, but always will get an exception. This is a bad practice, because instead of looking for the 200, you would have to always look for the 401 or 407 Unauthorized exception status code specifically, and if the code/response changed to something else, only then is it considered a failure - but technically it always had been a failure, because it never reached the site! It masks potential issues if you intend to go on deliberately using a site your service account doesn't have access to reach. And if your service account was ever granted access, your code would have to be updated.

How to use crocdoc in php

I am using crocdoc in php
https://github.com/crocodoc/crocodoc-php
i downloaded the files in my local i had my API TOKEN so i pasted it there but it doesnt seems to work and throws error shown below for all 15 examples
can any one help me here
This is the error here which i am getting on using above github code with my Token
Example #1 - Upload Form W4 from the IRS by URL.
Uploading... failed :(
Error Code: curl_exception
Error Message: Crocodoc: [curl_exception] Crocodoc::_request
{"curl_errno":60,"curl_error":"SSL certificate problem, verify that the CA cert is OK. Details:\nerror:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed"}
Example #15 - Delete the second file we uploaded.
Deleting... failed :(
Error Code: curl_exception
Error Message: Crocodoc: [curl_exception] Crocodoc::_request
{"curl_errno":60,"curl_error":"SSL certificate problem, verify that the CA cert is OK. Details:\nerror:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed"}
To check i am using the crocodoc API properly i wrote my own code
this is the error i am getting in my own code
::::OUTPUT::::
{"uuid": "300dc39d-e82b-4d92-a701-b1f376600b96"}
checking status of : {"uuid": "300dc39d-e82b-4d92-a701-b1f376600b96"}
Curl error: SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
Curl error: SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
Curl error no: 60
out put for docurlGet is :
bool(false) status is :
Viewing the Document : {"uuid": "300dc39d-e82b-4d92-a701-b1f376600b96"}
this is my code (i am sorry if i am not suppose to paste the whole code but could not understand the whole issue so i am just giving whole code )
<?php
$myToken='gSqV0PpEZhvJfLxQTcuMmoty';
$frameUrl='https://crocodoc.com/api/v2/document/upload';
$api_url = 'https://crocodoc.com/api/v2/';
//curl "https://crocodoc.com/api/v2/document/upload" --data "token=${API_TOKEN}&url=http://web.crocodoc.com/files/test-simple.pdf"
$param='token='.$myToken.'&url=http://web.crocodoc.com/files/test-simple.pdf';
//curl command
$ch = curl_init();
#curl_setopt($ch, CURLOPT_HEADER, 0);
#curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'X-HTTP-Method-Override: POST'));
#curl_setopt($ch, CURLOPT_POST, 1);
#curl_setopt($ch, CURLOPT_URL, $frameUrl);
#curl_setopt($ch, CURLOPT_POSTFIELDS,$param);
#curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
#curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
$uuids = curl_exec($ch);
echo $uuids;
echo "<br>";
echo " checking status of : ", $uuids."<br>";
$status =getStatus($uuids,$api_url,$myToken);
//curl 'https://crocodoc.com/api/v2/document/status?token=F6JOdArWGKmDRlfPQcZna71x&uuids=d5ea0542-baaf-46a1-835c-685a86e70e14'
echo " status is : ", $status."<br>";
echo " Viewing the Document : ", $uuids."<br>";
function getStatus($uuids,$api_url,$myToken){
$isSingleUuid = is_string($uuids);
$obj = json_decode($uuids);
$my_uuid= $obj->uuid;
$url = $api_url.'document/status';
$token = $myToken;
$dataStr = '?token='.$token.'&uuids='.$my_uuid;
$output = my_doCurlGet($url, $dataStr);
var_dump($output);
return $output;
}
function my_doCurlGet($url, $dataStr) {
//var_dump($url.$dataStr);
// var_dump($dataStr);exit;
//
$ch1 = curl_init();
#curl_setopt($ch1, CURLOPT_HEADER, 0);
#curl_setopt($ch1, CURLOPT_HTTPHEADER, array('Accept: application/json', 'X-HTTP-Method-Override: POST'));
#curl_setopt($ch1, CURLOPT_POST, 1);
#curl_setopt($ch1, CURLOPT_URL, $url.$dataStr);
#curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch1);
if(curl_exec($ch1) === false)
{
echo "<br>".'Curl error: ' . curl_error($ch1);
}
else
{
echo "<br>".'Operation completed without any errors'."<br>";
}
//var err_no=curl_errno()
if(curl_errno($ch1))
{
echo "<br>".'Curl error: ' . curl_error($ch1);
echo "<br>".'Curl error no: ' . curl_errno($ch1);
}
echo "<br>". "out put for docurlGet is : $output"."<br>";
return $output;
}
if (curl_errno($ch)) {
print 'An curl error has occurred.';
exit;
}
//var_dump($uuids);
curl_close($ch);
return $uuids;
?>
Thanks for all your help
Curl probably isn't properly configured with a CA bundle, or the configured CA bundle does not include Crocodoc's CA cert.
Check out this answer for more info.
Found the answer
First of all i did enable curl and SSL for beginning but it was not working
i even changed my Localhost name to myHost but it still did not work
so I made few changes in crocodoc.php file which i downloaded from crocodoc api library
CROCODOC PHP LIBRARY
I added this lines and IT WORKED :):):) Thank you all, hope this helps someone else as well.
if(($_SERVER['SERVER_NAME'] == 'myHost') && ($_SERVER['SERVER_ADDR'] == '127.0.0.1') && ($_SERVER['HTTP_HOST'] == 'myHost')) {
$options[CURLOPT_SSL_VERIFYPEER]=false;
}