https connection passing another server - php

I want to do the following scenario but i dont really know if this is possible at all or what techniques i need to use:
So im using an external api to store information of my web application. Now i want to send the api request to my server which sends it to the api server maybe by using curl and wait for the response.. when i receive the response i update something at my server like insert row in mysql and send the response back to the requester
Now the api url is using https and my server is currently using http.. will this be a problem to test or do i need https also?
And how should i implement this using php? Maybe some kind of redirect? Or do i have to rebuild the whole request?
Thanks in advance

There are a lot of unknowns about your question that make it hard to answer, but here goes.
You certainly don't have to offer your own application over HTTPS and you can query an HTTPS API and then deliver your own response via HTTP. I should warn you that you are inherently making the external service less secure by doing this. If you are acting as a proxy for the external service, I would suggest that you either get an SSL certificate and do it the proper way.
The lack of details in your question make it hard to answer a specific question, but here is a small code block that should get you started:
<?php
$url = "https://service/endpoint";
$params = array(
'api_token' => 'mytoken',
'param1' => 'myparam',
);
$url .= http_build_query($params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'received error: ' . curl_error($ch) . ' (code: ' . curl_errno($ch);
} else {
echo 'received response: ' . $result;
}

What nate has said is roughly right, but if you want to post from HTTP to HTTPS with cURL, set this option as well:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
Which stops cURL from verifying the peer’s certificate (I'm guessing you don't care about using SSL between the second server and the API).
Code on the app server:
$data = http_build_query(
// Your parameters go here
);
file_get_contents('http://middleserverurl.com/?' . $data);
Code on the middle server:
$apiurl = "https://apiurl.com/?" . http_build_query($_GET);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
// Decode the result data here
// Insert into your database here
// Send something back to your app server e.g.:
$data = http_build_query(
// What you want to send back form the result
);
file_get_contents('http://appserverurl.com/?' . $data);

Related

API I'm using can't be accessed unless Captcha is completed

I am trying to access API data from CraftingStore Public API.
When I am trying it on localhost, everything works like it should (1st pic, also printing results for to show).
However, when I am trying to view it on the actual website (2nd pic), it is not working but instead saying to enable cookies and to complete captcha.
When on localhost:
When on website:
Also code for accessing the API:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.craftingstore.net/v7/payments?page=1');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'token:'.$cs_token
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
$dononame = $obj->data[0]->inGameName;
$donobuy = $obj->data[0]->packageName;
What can I do?
This is quite usual for API's with Cloudflare. You'll need to make a page rule for the API domain/URI to disable the Browser Integrity Check.
Source: https://support.cloudflare.com/hc/en-us/articles/200504045-Using-Cloudflare-with-your-API

403 response when sending POST data via cURL

I'm trying to send some data to a custom built API that was built by a web development agency. The api is pretty straight forward, and all that I require to do is authorise myself with an authorisation basic header and submit a payload which is just JSON data.
The problem is that the API is responding with 403 every time I send a POST request using cURL. Is there any way that my code could be causing this? or is it an error that is caused by the API/API server? Regardless if the JSON payload is correctly formatted or not, it should still return with a 200 response.
The request is pretty straight forward -
<?php
//I've removed the actual username and password
$headers = array(
'Content-Type: application/json',
'Authorization: Basic '.base64_encode('username:password'));
$empty_array = array();
//Create empty json as an example
$json = json_encode($empty_array);
$url = "https://website.com/import";
//start cURL
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS,
$json);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
If I take out the POST data, then it will return with a 404 response. This is the correct behaviour if there is no POST data submitted to the url. (I get a 404 if I navigate to the url via a browser). So I have a theory that the server must have some kind of restrictions on accepting POST data.
Does my code seem correct or am I missing something glaringly obvious? I wan't to rule out that it's a problem caused by my end due to not being able to access the code/server for the API as that is beyond my control.

Created a response listening service with php and curl just like paypal IPN

I am new to php web services and i have asked this question before but could not get useful solutions so i have tried to rephrase it. i am trying to listen to a response from an API and update my database like what is done by the paypal IPN service. The script that i have so far works well when you run it in the browser and i am a geting my a json response back via POST, but the API later sends another response without the involvement of the browse/client and i want it to communicate to my php script in the server and update the database. The API has a notifyURL field that it requires for it to send these notifications and i have set it to the same file that sends the request. Below is the code that i have so far:
if($ch !== false){
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//Set the content type to application/json
// curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json;odata=verbose',
'Content-length:' . strlen($jsonDataEncoded))
);
}
//Execute the request
$result = curl_exec($ch);
if ($result === false){
curl_close($ch);
echo "Error".curl_errno($ch). "\n";
}else {
curl_close($ch);
$decoded = json_decode($result, true);
// echo '<pre>';
// var_dump($decoded["paymentAmount"]["totalAmountCharged"]);
// die;
$data['unique_id'] = $decoded["clientCorrelator"];
$data['subscriber_number'] = $decoded["endUserId"];
$data['payment_status'] = $decoded["transactionOperationStatus"];
$data['payment_gross'] = $decoded["paymentAmount"]["totalAmountCharged"];
$data['txn_id'] = $decoded["ecocashReference"];
$this->payments->insertTransaction($data);
die;
What do i need to add to the script for me to achieve my goal using curl and php. The API returns the json response below and i am trying to listen for it and update certain fields into the database.
{"id":71109,"version":0,"clientCorrelator":"58ada3aec8615","endTime":null,"startTime":1487774641697,"notifyUrl":"http://website/ecocash_send/transaction","referenceCode":"17589","endUserId":"774705932","serverReferenceCode":"2202201716440169792864","transactionOperationStatus":"PENDING SUBSCRIBER VALIDATION","paymentAmount":{"id":71110,"version":0,"charginginformation":{"id":71112,"version":0,"amount":1,"currency":"USD","description":" Bulk Sms Online payment"},"chargeMetaData":{"id":71111,"version":0,"channel":"WEB","purchaseCategoryCode":"Online Payment","onBeHalfOf":"PAMONMEFT","serviceId":null},"totalAmountCharged":null},"ecocashReference":"MP170222.1644.A00059","merchantCode":"0000","merchantPin":"000","merchantNumber":"771999313","notificationFormat":null,"serviceId":null,"originalServerReferenceCode":null}"
There needs to be nothing special about the script that responds to the PayPal IPN like call.
All it need to do is be there waiting for the other API to launch it, know what parameters to expect, have a robust error reporting mechanism i.e. save the errors somewhere that you can review them later, or email them to an email account you will look at regularly.
Other than that the usual database access code is all that should be necessary.
Of course you cannot get it to throw anything at your browser as there is no browser in the process.

My PHP cURL Script Is Returning 'Couldn't resolve host'

First off, I've read other similar problems and have spoken with my host to confirm cURL is running and configured properly on my server, which it is.
I'm new to cURL so I'm not very confident in my script and I'm guessing the problem is there. I have api access to a service to check the status of and place orders. This script is meant to check the status of orders.
function get_CSA_order_status($pid){
// Get cURL resource
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://domain.com');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, 'Content-Type: application/x-www-form-urlencoded');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(api_token => 'my api token', order_id => '54512'));
// Send the request & save response to $results
$results = curl_exec($ch);
echo curl_getinfo($ch) . '<br/>';
echo curl_errno($ch) . '<br/>';
echo curl_error($ch) . '<br/>';
// Close request to clear up some resources
curl_close($ch);
//return array and dump results
var_dump($results);
}
Script Output
Array
6
Couldn’t resolve host ‘Array’
bool(false)
UPDATE:
Thanks to gofr1 I was able to resolve my issue which was passing the URL through an array. I have edited the code above to reflect my current script, but now for some reason it's not accepting the order id.
Current Output
string(89) “{“code”:400,”payload”:{“messages”:{“order_id”:[“The order_id you provided is invalid”]}}}”
I've changed the url and removed my api key. If anything looks incorrect please let me know.
SOLVED!
Everything is working thank you to everyone who helped and suggested solutions.

Accessing task management API with PHP using cURL

I'm attempting to access an API for a task management system (Nozbe to be exact) that is outlined here: http://www.nozbe.com/api
If I go in my browser and access the URL it returns the correct json response:
{"response":"644a40436"}
However, when I attempt to access this URL with cURL in PHP, it doesn't create the note like it would if I accessed it manually in my browser.
The normal method is outlined below:
http://www.nozbe.com/api/newnote/name-test/body-test/project_id-c4ca1/context_id-c4ca1/key-1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6
$api_key = "INSERTAPIKEYHERE";
$project_id = "73d173457";
$eventtitle = "Testing";
$descrip = "This is a test";
$url = "http://www.nozbe.com/api/newnote/name-$eventtitle/body-$descrip/project_id-$project_id/key-$api_key";
echo "$url<br/><br/>";
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
// grab URL and pass it to the browser
$response = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
Does anyone have any advice or pointers as to why this isn't working? I know it's probably a pretty obscure API I'm attempting to access.
Note that the API says that the body and the like must be URL-encoded. Instead, you have spaces in your URL. Try running urlencode on the arguments before placing them into the URL.

Categories