I have a rest service written in Spring MVC. The requirement is to call the particular service from my Codeigniter project. Here is the code I used,
function connection(){
header('Access-Control-Allow-Origin: *');
$endpoint = "http://localhost:8090/{projectName}/{rest_endpoint}";
try
{
// Get cURL resource
$curl = curl_init();
// Set some options
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $endpoint,
CURLOPT_HTTPHEADER => ['Accept:application/json']
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Check HTTP status code
if (!curl_errno($curl)) {
switch ($http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE)) {
case 200: # OK
echo "Server JSON Response:" . $resp;
break;
default:
echo 'Unexpected HTTP code: ', $http_code, "\n";
echo $resp;
}
}
// Close request to clear up some resources
curl_close($curl);
} catch (Exception $ex) {
printf("Error while sending request, reason: %s\n",$ex->getMessage());
}
}
This does not call the Rest endpoint. Both of them are running on localhost.
Related
I am facing issue in Amazon payment gateway while completing checkoutsession.
Error which I am facing:
status=422; response={"reasonCode":"InvalidCheckoutSessionStatus","message":"You tried to call an operation on a Checkout Session that is in a state where that operation is not allowed"}
My code:
public function completeCheckout(Request $request){
$amazonpay_config = array(
'public_key_id' => config('amazonkey.public_key_id'),
'private_key' => config('amazonkey.private_key'),
'region' => 'UK',
'sandbox' => true
);
$payload = array(
"chargeAmount" => array(
"amount" => "100",
"currencyCode"=> "USD"
),
);
$payload = json_encode($payload);
try {
$checkoutSessionId = $request->checkoutSessionId;
// dd($checkoutSessionId);
$client = new ApayAPI($amazonpay_config);
$result = $client->completeCheckoutSession($checkoutSessionId, $payload, $headers = null);
if ($result['status'] === 200) {
// dd($result);
$response = json_decode($result['response'], true);
return $response;
// $response = json_decode($result['response'], true);
// $amazonPayRedirectUrl = $response['webCheckoutDetails']['amazonPayRedirectUrl'];
// echo "amazonPayRedirectUrl=$amazonPayRedirectUrl\n";
} else {
// check the error
echo 'status=' . $result['status'] . '; response=' . $result['response'] . "\n";
}
} catch (\Exception $e) {
// handle the exception
echo $e . "\n";
}
}
Make sure that prior to sending a request to complete checkout session that 1/the buyer has been redirected to checkoutResultReturnUrl (returned in response to update checkout session) and 2/ there are no constraints in the constraint object returned from update checkout session. If both of these conditions have been satisfied, know that complete checkout session must be requested within 24 hours of a buyer's redirect to checkoutResultReturnUrl or the checkout session will automatically cancelled.
I am facing an issue while sending API requests to by HTTP Client. I am getting a Pending Request. How to fulfill the response and get the response data from $response->collect()
here is my code:
public function postMultipleFiles($url, $files, $params)
{
$response = Http::withHeaders([
'Authorization' => auth()->check() ? 'Bearer '.auth()->user()->api_token:''
]);
foreach($files as $k => $file)
{
$response = $response->attach('images['.$k.']', $file);
}
$response->post($this->base_url.$url, $params);
return response()->json($response->collect());
}
The error I am getting
message: "Method Illuminate\\Http\\Client\\PendingRequest::collect does not exist."
I have this code :
$httpParams = [
'textData' => $content,
'xmlFile' => new \CurlFile($params['file']->getPathName())
];
$curlHandle = curl_init('http://url.com');
curl_setopt($curlHandle, CURLOPT_HEADER, false);
curl_setopt($curlHandle, CURLOPT_POST, true);
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $httpParams);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
$curlResponse = curl_exec($curlHandle);
curl_close($curlHandle);
dump($curlResponse);die();
I have the response in $curlResponse with status = 200
But when I tried with Http from laravel :
$http = Http::asForm();
$httpParams = [
'textData' => $content,
'xmlFile' => new \CurlFile($params['file']->getPathName())
];
$response = $http->send('post', 'http://url.com', $httpParams)->body();
dump($response);
Response is empty : "". The status is 200. Can you help me please, why using Http facade I have empty response ? Thx in advance. Please help me !!!
You can write reusable method inside separate class
public function apiCall($url, $method = "get",$data=[])
{
$htppCall = Http::withHeaders([
'Content-Type' => 'application/json',
])->{$method}($url,$data);
if ($htppCall->status() == 401) {
//error handling
}
return $htppCall->object();
}
Then call like this
$httpParams = [
'textData' => $content,
'xmlFile' => new \CurlFile($params['file']->getPathName())
];
$response=$this->apiCall($url,'post',$httpParams);
dd($response);
Import right facade
use Illuminate\Support\Facades\Http;
checking what status code you got
$htppCall->status()
to get data as object
$htppCall->object()
To get data as array
$htppCall->json()
To check client errors
$htppCall->clientError()
to check server errors
$htppCall->serverError()
To Get the body of the response.
$htppCall->body()
If any issues let me know in comment
I have a form integrated with invisible reCaptcha.
Verification is performed on a function within the Controller.
The call to google is made using file_get_content and if no response is obtained, the call is made using curl.
This is the function
public function verify_captcha()
{
$recaptcha_response = $_POST['recaptchaResponse'];
log_message('info', $recaptcha_response);
// Build POST request:
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_secret = 'My KEY';
$recaptcha_response = $_POST['recaptchaResponse'];
$recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response);
$recaptcha = json_decode($recaptcha,true);
if(!$recaptcha)
{
// call curl to POST request
log_message('info', 'Call CURL');
$data = array( 'secret' => $recaptcha_secret, 'response' => $recaptcha_response);
//$curlConfig = array( CURLOPT_URL => $recaptcha_url, CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_POSTFIELDS => $data );
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $recaptcha_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$recaptcha = json_decode($response, true);
ob_start();
var_dump($recaptcha);
$result = ob_get_contents(); //or ob_get_clean()
log_message('info', $result);
if (array_key_exists('error-codes', $recaptcha))
{
log_message('error', 'Error reCaptcha '.$recaptcha['error-codes'][0]);
}
if ($recaptcha["success"] == '1')
{
if ($recaptcha["score"] >= 0.5)
{
}
}
else
{
log_message('error', 'Error reCaptcha no Success');
}
else
{
log_message('info', 'Call file_get_content');
}
}
These are the messages of the log file
ERROR - 2020-03-18 09:54:31 --> Severity: Warning --> file_get_contents(): php_network_getaddresses: getaddrinfo failed: Name or service not known /mysite/application/controllers/captcha.php 1362
ERROR - 2020-03-18 09:54:31 --> Severity: Warning --> file_get_contents(https://www.google.com/recaptcha/api/siteverify?secret=6LfP26QUAAAAAHilJfguEgIcgOBkTg2soD7oCQIh&response=03AERD8XpOL7956DMd7dhiqasH4fK2iNjtBFBJdw3OynXGeAFBMmSqqtjsqXFW97rv-kD_H-y6aLrL1VLMkwg222Y7BoNnaB_zQ7y2NzXVtlIsWYwIw9BSbUdFdSylq4dNjO5j5Jo1xvjPotvMFuddnC5YVRC1wnk7HESqv8hvRU40x9pNpoQ-sIaXcAN8BdBgleXFufmmNoMzuh3PCvgT3RkIj1TsTs-ltM9LyVbLtFnFPbTkHZqpQjppMkHCcw87u3xqbr23EJkusR_U2vFwJTAJU9p-Z27sDuiKmEMsjJ2O1i3Wnxm9yq4HiEI2vnh420VDnPZEYRbXuLLSGhGuPciGQ3mtp07tjn265oyYbcFp2s9GentdUpPWRCxWfySTa6du7dzzSHkqPMKcPf6LmfVtICkTJf4y-w): failed to open stream: php_network_getaddresses: getaddrinfo failed: Name or service not known /mysite/application/controllers/captcha.php 1362
INFO - 2020-03-18 09:54:31 --> Call CURL
INFO - 2020-03-18 09:54:31 --> NULL
The call to file_get_content shows error and returns nothing with curl.
What may be happening?
Thanks
If you totally, absolutely need to use file_get_contents, I'll share with you a helper function I have, which you can adapt to your own needs
function validate_recaptcha_response($recaptcha_response)
{
$api_url = 'https://www.google.com/recaptcha/api/siteverify';
$api_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$remoteip = '';
$data = array('secret' => $api_secret, 'response' => $recaptcha_response);
$options = array(
'http' => array(
'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($api_url, false, $context);
$captcha_response = json_decode($result, true);
$r = array(
'success' => $captcha_response['success'],
'timestamp' => $captcha_response['challenge_ts'],
'hostname' => $captcha_response['hostname'],
'error_codes' => (isset($captcha_response['error-codes'])) ? $captcha_response['error-codes'] : null,
);
return $r;
}
I call this from any controller that gets the recaptcha response (the helper is autoloaded) using something like
$recaptcha_check = validate_recaptcha_response($var_where_you_store_the_recaptcha_response);
Please note that I'm adding the $options array to build a POST, defining a header, the method and use http_build_query() and stream_context_create() before file_get_contents() in order to query the data.
Please Follow the bellow Steps to integrate Recaptcha v3 in Codeigniter versions bellow 4 (3.1.9) or others.
Step #1: Create Recaptcha v3 for your domain and keep the site_key & secret_key.
[https://cloud.google.com/recaptcha-enterprise/docs/create-key][1]
Step #2: Add the bellow Javascirpt codes with replacement of your site_key & secret_key inside Head section of your Form page.
<script type="text/javascript">
var review_recaptcha_widget;
var onloadCallback = function() {
if($('#review_recaptcha').length) {
review_recaptcha_widget = grecaptcha.render('review_recaptcha', {
'sitekey' : 'recaptcha_site_key_v3',
'secretkey' : 'recaptcha_secret_key_v3'
});
}
};
</script>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
Step #3:Browse the page, you will see the new recaptcha in right bottom corner of page, Done, thats it.
I'm tring to return products from my shopify store and dump the expected returned json on to the page. No products return via the code but if I go directly to the url in the form below I get the expected json displayed on the page:
https://API_KEY:PASSWORD#your-store.myshopify.com/admin/products.json
Can anyone help me return the json using this package which I'm using to connect to shopify? I'm also using Laravel 5.
I've noticed that the Input calls return nothing:
Input::get('code');
Input::all();
I added this to app.php:
'Input' => Illuminate\Support\Facades\Input::class,
I'm getting this error:
ERROR #22: The requested URL returned error: 401
in api.php line 309 at API->call(array('METHOD' => 'GET', 'URL' => '/admin/products.json?page=1')) in routes.php line 87
This is my route:
Route::get('/show_products', function() {
$shopify = App::make('ShopifyAPI');
// This creates an instance of the Shopify API wrapper and
// authenticates our app.
$shopify = App::make('ShopifyAPI', [
'API_KEY' => 'api_key',
'API_SECRET' => 'api_secret',
'SHOP_DOMAIN' => 'shop_domain.myshopify.com',
'ACCESS_TOKEN' => 'access_token'
]);
$shopify->installURL(['permissions' => array('read_products', 'write_products'), 'redirect' => 'https://dev.shopify.com/public/']);
try {
$verify = $shopify->verifyRequest(Input::all(), true);
if ($verify)
{
$code = Input::get('code');
echo "code: ".$code; // no code returned
$accessToken = $shopify->getAccessToken($code);
echo "accessToken: ".$accessToken; // no access token
}
else
{
echo "issue with data";
// Issue with data
}
}
catch (Exception $e)
{
echo '<pre> Error: ' . $e->getMessage() . '</pre>';
}
// Gets a list of products
$result = $shopify->call([
'METHOD' => 'GET',
'URL' => '/admin/products.json?page=1'
]);
$products = $result->products;
print_r($products);
exit;
});
I ran into this issue on Android. The accessing the products by the url with key/secret worked fine if I was in a browser, but failed trying to do a basic GET against that URL from the device.
I couldn't figure out why, but I ended up setting the header on the request, and that worked well.
Where you had
https://API_KEY:PASSWORD#your-store.myshopify.com/admin/products.json
Instead, request
https://your-store.myshopify.com/admin/products.json
but set the header x-shopify-access-token to PASSWORD