Problem to convert curl to php, I can't solve it - php

I'm having problems converting curl to php, I need to access data in json and filter this data. I was able to access the data without the filter but I can't access it when I add the filter.
The code below is functional and brings all the data in json...
`
<?php
$apikey = 'myapikey';
$outputType = 'json';
$url = 'https://bling.com.br/Api/v2/contasreceber/' . $outputType;
$retorno = executeGetOrder($url, $apikey);
echo $retorno;
function executeGetOrder($url, $apikey){
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $url . '&apikey=' . $apikey);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($curl_handle);
curl_close($curl_handle);
return $response;
}
?>
`
This was the code I tried to run to apply the filters as the developer described.
As stated in the developer's api manual https://ajuda.bling.com.br/hc/pt-br/articles/360047064873-GET-contasreceber
I would be very grateful if someone could help me my knowledge is limited and I don't know where I'm going wrong.
`
<?php
$apikey = 'myapikey';
$outputType = 'json';
$url = 'https://bling.com.br/Api/v2/contasreceber/' . $outputType;
$retorno = executeGetOrder($url, $apikey);
echo $retorno;
function executeGetOrder($url, $apikey){
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $url . '&apikey=' . $apikey);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, 'filters=dataEmissao[01/01/2022 TO 05/02/2022]; situacao[Aberto]');
$headers = array();
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($curl_handle, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl_handle);
curl_close($curl_handle);
return $response;
}
?>
`

An alternative when making a get request.
<?php
$apikey = 'my api key';
$outputType = 'json';
$filters ="cnpj[21.416.959/0001-82]";
$url = 'https://bling.com.br/Api/v2/contasreceber/' . $outputType;
$retorno = executeGetOrder($url, $apikey, $filters);
echo $retorno;
function executeGetOrder($url, $apikey, $filters){
return file_get_contents( $url.'&apikey=' . $apikey . '&filters=' . $filters`);
}
?>

When I look on your documentation, date does not exist.
You can only have as filters :
dataEmissao * ;
dataVencimento * ;
situacao ;
cnpj ;
dataPagamento *;
The ones I put * are the filters with date inputs so you need, depending of your wanted :
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, 'filters=dataEmissao[01/01/2022 TO 05/02/2022]; situacao[open]');

Related

PHP and Shopify API connection

I'm trying to learn the shopify api for a project. Tried a few pasted codes on their forum, adapting my code to theirs.
The documentation says to do the authentication this way, by providing the following:
https://{username}:{password}#{shop}.myshopify.com/admin/api/{api-version}/{resource}.json
{username} — The API key that you generated
{password} — The API password
{shop} - The name that you entered for your development store
{api-version} — The supported API version you want to use
{resource} — A resource endpoint from the REST admin API
I'm trying to do a GET request on all the orders made on the store.
/ info
$API_KEY = '75c89bf******ea919ce****7702';
$PASSWORD = '2061******82d2802**f***9403';
$STORE_URL = '*****-na-***-c***.myshopify.com';
$AUTHORIZATION = base64_encode($API_KEY . ':' . $PASSWORD);
$url = 'https://' . $API_KEY . ':' . $PASSWORD . '#' . $STORE_URL . '/admin/api/2020-01/orders.json';
$header = array();
$header[] = 'Accept: application/json';
$header[] = 'Content-Type: application/json';
$header[] = 'Authorization: Basic ' . $AUTHORIZATION;
$session = curl_init();
//options
curl_setopt($session, CURLOPT_URL, $url);
curl_setopt($session, CURLOPT_HTTPHEADER, $header);
curl_setopt($session, CURLOPT_GET, 1);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
//exec
$response = curl_exec($session);
curl_close($session);
print_r($response);
// error
if($response === false)
{
print_r('Curl error: ');
}
The code doesn't work at all, without any error code, completly blank, with only the first project echo showing.
I verified my API keys and they are working, I can insert them manually into chrome.
You don't need the header for authorization. Your code should like:
$API_KEY = '75c89bf******ea919ce****7702';
$PASSWORD = '2061******82d2802ff***9403';
$STORE_URL = 'porcao-na-sua-casa.myshopify.com';
$url = 'https://' . $API_KEY . ':' . $PASSWORD . '#' . $STORE_URL . '/admin/api/2020-01/orders.json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
$headers = array();
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE) //can check status code, requst successfully processed if return 200
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
Found the problem when I ran in terminal, did not install php-curl on this machine.
#Kshitij solution worked, just like mine, when curl was properly installed.
// Provide the required parameters like store url , endpoint etc.
function shopifyApiCall($STORE_URL ,$query = [], $endpoint, $API_KEY, $PASSWORD){
//API_Key : your API key, you can get it from your APP setup.
//Password : Your Access Token
$url = 'https://' . $API_KEY . ':' . $PASSWORD . '#' . $STORE_URL . $endpoint;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt ($ch, CURLOPT_POSTFIELDS, json_encode($query));
$headers = array();
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$error_number = curl_errno($ch);
$error_message = curl_error($ch);
curl_close($ch);
// Return an error is cURL has a problem
if ($error_number) {
return $error_message;
} else {
// No error, return Shopify's response by parsing out the body and the headers
$response = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
// Convert headers into an array
$headers = array();
$header_data = explode("\n",$response[0]);
$headers['status'] = $header_data[0]; // Does not contain a key, have to explicitly set
array_shift($header_data); // Remove status, we've already set it above
foreach($header_data as $part) {
$h = explode(":", $part);
$headers[trim($h[0])] = trim($h[1]);
}
// Return headers and Shopify's response
//return array('headers' => $headers, 'response' => $response[1]);changed headers
return array('headers' => $header_data, 'response' => $response[1]);
}
}

Binance REST API - Placing a PHP Order (POST) via Query String

I am struggling using Binance's REST API. I have managed to get working GET request via query string such as pinging the server, ticker information, etc. My challenge now is performing POST request via query string using cURL. I have been scraping code from various places and referring back to the API to get pieces to work but I am unsure as to why I am getting this error returned from the result... {"code":-1102,"msg":"Mandatory parameter 'signature' was not sent, was empty/null, or malformed."}
(ERROR SHOWN ON WEBPAGE). I echo out the signature and its a load of gibberish so I would believe that the hash_hmac performed at the top would be working, but honestly I got pretty lucky making the GET request work. Does anyone have any suggestions as to why this would be broken? Thanks!
$apikey = "MYKEY";
$apisecret = "MYSECRET";
$timestamp = time()*1000; //get current timestamp in milliseconds
$signature = hash_hmac('sha256', "TRXBTC&type=market&side=buy&quantity=100.00&recvWindow=10000000000000000&timestamp=".$timestamp, $apisecret);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.binance.com/api/v3/order/test");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, "symbol=TRXBTC&type=market&side=buy&quantity=100.00&recvWindow=10000000000000000&timestamp=".$timestamp);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded","X-MBX-APIKEY: ".$apikey,"signature: ".$signature));
$response = curl_exec($ch);
curl_close($ch);
echo $response;
As per their API docs:
SIGNED endpoints require an additional parameter, signature, to be sent in the query string or request body.
You are sending the signature via neither of these methods and are instead sending it through the header.
Change this:
curl_setopt($ch, CURLOPT_POSTFIELDS, "symbol=TRXBTC&type=market&side=buy&quantity=100.00&recvWindow=10000000000000000&timestamp=".$timestamp);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded","X-MBX-APIKEY: ".$apikey,"signature: ".$signature));
To this:
curl_setopt($ch, CURLOPT_POSTFIELDS, "symbol=TRXBTC&type=market&side=buy&quantity=100.00&recvWindow=10000000000000000&timestamp=" . $timestamp . "&signature=" . $signature);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded","X-MBX-APIKEY: ".$apikey));
<?php
$secret = "F................";
$key = "D.................";
$s_time = "timestamp=".time()*1000;
$sign=hash_hmac('SHA256', $s_time, $secret);
$url = "https://api.binance.com/api/v3/account?".$s_time.'&signature='.$sign;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-MBX-APIKEY:'.$key));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
$result = json_decode($result, true);
echo '<pre>';
var_dump($result);
echo '</pre>';
?>
Here is an example, using php-curl-class
// Variables
// url, key and secret is on separate file, called using require once
$endPoint = "/api/v3/order/test";
$coin = "BTC";
$fiat = "EUR";
$symbol = $coin . "" . $fiat;
$side = "BUY";
$type = "LIMIT";
$timeInForce = "GTC";
$quantity = 1;
$price = 10000;
$timestamp = time();
// Constructing query arrays
queryArray = array(
"symbol" => $symbol,
"side" => $side,
"type" => $type,
"timeInForce" => $timeInForce,
"quantity" => $quantity,
"price" => $price,
"timestamp" => $timestamp*1000
);
$signature = hash_hmac("sha256", http_build_query($queryArray), $secret);
$signatureArray = array("signature" => $signature);
$curlArray = $queryArray + $signatureArray;
// Curl : setting header and POST
$curl->setHeader("Content-Type","application/x-www-form-urlencoded");
$curl->setHeader("X-MBX-APIKEY",$key);
$curl->post($url . "" . $endPoint, $curlArray);
if ($curl->error) {
echo 'Error: ' . $curl->errorCode . ': ' . $curl->errorMessage . "\n";
}
$order = $curl->response;
print_r($order);
I had the same problem, and nothing of above doesn't helped.
So I finaly figured out how to make order on my way.
So, maybe this helps someone.
function Kupovina($buy_parametri) {
$key = "xxxxxxxxxxxxxxx";
$secret = "xxxxxxxxxxxx";
$s_time = "timestamp=".time()*1000;
$timestamp = time()*1000; //get current timestamp in milliseconds
$sign = hash_hmac('sha256', $buy_parametri."&timestamp=".$timestamp, $secret);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.binance.com/api/v3/order");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $buy_parametri."&".$s_time."&signature=".$sign);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded","X-MBX-APIKEY: ".$key));
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$buy_parametri = "symbol=BTCUSDT&type=market&side=buy&quantity=0.00086";
Call function:
Kupovina($buy_parametri);

Unable to access data from Microsoft Outlook with php

I have set up a Microsoft Outlook account for testing purposes. I have entered a couple of contacts and sent emails to/from that account, so it is clearly active. I have written php code to access that data, but nothing is returned. Everything else seems to be working in that the access tokens and verification all seems OK.
The php code is as follows (the 'xxxx' is obviously replaced with an actual code) with echos for diagnostic purposes, and some lines have been broken for clarity here.
<?php
//***************************************MSN
START********************************
$client_id = 'xxxxxx';
$client_secret = 'xxxxx';
$redirect_uri =
'http://localhost:8000/testcontacts/oauth_hotmail.php';
$urls_ = 'https://login.live.com/oauth20_authorize.srf?
client_id='.$client_id.
'&scope=wl.signin%20wl.basic%20wl.emails%20wl.contacts_emails&
response_type=code&redirect_uri='.$redirect_uri;
$msn_link = '<a href="'.$urls_.'" >MSN Contacts</a>';
echo $msn_link;
//***************************************MSN
ENDS********************************
?>
<?php
//function for parsing the curl request
function curl_file_get_contents($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$client_id = 'xxxxx';
$client_secret = 'xxxxx';
$redirect_uri = http://localhost:8000/testcontacts/oauth_hotmail.php';
$auth_code = $_GET["code"];
echo '<br>' . $auth_code;
$fields=array(
'code'=> urlencode($auth_code),
'client_id'=> urlencode($client_id),
'client_secret'=> urlencode($client_secret),
'redirect_uri'=> urlencode($redirect_uri),
'grant_type'=> urlencode('authorization_code')
);
$post = '';
foreach($fields as $key=>$value) { $post .= $key.'='.$value.'&'; }
$post = rtrim($post,'&');
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,
'https://login.live.com/oauth20_token.srf');
curl_setopt($curl,CURLOPT_POST,5);
curl_setopt($curl,CURLOPT_POSTFIELDS,$post);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0);
$result = curl_exec($curl);
curl_close($curl);
$response = json_decode($result);
$accesstoken = $response->access_token;
echo '<br>' . $accesstoken;
$url = 'https://apis.live.net/v5.0/me/contacts?
access_token='.$accesstoken.'&limit=100';
$xmlresponse = curl_file_get_contents($url);
$xml = json_decode($xmlresponse, true);
echo '<br>' . $url;
echo '<br>' . $xmlresponse;
echo '<br>' . $xml;
$msn_email = "";
foreach($xml['data'] as $emails)
{
// echo $emails['name'];
$email_ids = implode(",",array_unique($emails['emails'])); //will get
more email primary,sec etc with comma separate
$msn_email .= "<div><span>".$emails['name']."</span>
<span>". rtrim($email_ids,",")."</span></div>";
}
echo $msn_email;
?>
I get the following response (... represents long character string):-
MSN Contacts
Md9a1ad3b-d405-5f3f-1b08-10ae540b5669
EwAgA61DBAAUcSSzoTJJs.....
https://apis.live.net/v5.0/me/contacts?access_token=EwAgA61DBAAUcSSzo.....=&limit=100
{ "data": [], "paging": { } }
Array
Please can anyone tell me why nothing is returned. Thank you.
If anyone else comes this way, I have now got this to work. All the code that I have seen on the internet has been much more complicated than I wanted or refused to work at all, so not much use to me. Here I have managed to pare the code down to a minimum in a stand-alone working piece of code. I hope it works for you.
One question still remains. I cannot see how to get the contacts which are in a specific contact list, and not get all the contacts. Any ideas?
Here is the code...
<?php
//***************************************MSN START********************************
$client_id = 'xxxxxxxxxxxxxx';
$client_secret = 'xxxxxxxxxxxxx';
$redirect_uri = 'https://.........php';
$login_uri = 'https://login.live.com/oauth20_authorize.srf';
$scope = '&scope=wl.signin%20wl.basic%20wl.emails%20wl.contacts_emails';
$urls_ = $login_uri;
$urls_ .= '?client_id='.$client_id;
$urls_ .= $scope.'&response_type=code';
$urls_ .= '&redirect_uri='.$redirect_uri;
$msn_link = '<a href="'.$urls_.'" >Get Contacts</a>';
echo $msn_link;
//***************************************MSN ENDS********************************
if(isset($_GET["code"])){
$auth_code = $_GET["code"];
// get contacts
$fields=array(
'code'=> urlencode($auth_code),
'client_id'=> urlencode($client_id),
'client_secret'=> urlencode($client_secret),
'redirect_uri'=> urlencode($redirect_uri),
'grant_type'=> urlencode('authorization_code')
);
$post = '';
foreach($fields as $key=>$value) { $post .= $key.'='.$value.'&'; }
$post = rtrim($post,'&');
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,'https://login.live.com/oauth20_token.srf');
curl_setopt($curl,CURLOPT_POST,5);
curl_setopt($curl,CURLOPT_POSTFIELDS,$post);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,0);
$result = curl_exec($curl);
curl_close($curl);
$response = json_decode($result);
$accesstoken = $response->access_token;
$apiurl = "https://outlook.office.com/api/v2.0";
$headers = array(
"User-Agent: php-tutorial/1.0",
"Authorization: Bearer ".$accesstoken,
"Accept: application/json",
"return-client-request-id: true"
);
$search = array (
// Only return selected fields
"\$select" => "EmailAddresses,GivenName,Surname",
// Sort by GivenName
"\$orderby" => "GivenName ASC"
);
$outlookApiUrl = $apiurl . "/me/contacts?" . http_build_query($search);
$response = runCurl($outlookApiUrl, null, $headers);
$response = explode("\n", trim($response));
$response = $response[count($response) - 1];
$response = json_decode($response, true);
foreach ($response["value"] as $contacts) {
$email = $contacts["EmailAddresses"][0]["Address"];
echo '<br>' . $contacts["GivenName"] . ' ' . $contacts["Surname"] . ' ' . $email;
}
}
function runCurl($url, $post = null, $headers = null) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, $post == null ? 0 : 1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($http_code >= 400) {
echo "Error executing request to Office365 api with error code=$http_code<br/><br/>\n\n";
echo "<pre>"; print_r($response); echo "</pre>";
die();
}
return $response;
}
?>

I cant create an order with kucoin api with php

Hello im using that code to create buy order but it shows me that error "{"code":"UNAUTH","msg":"Signature verification failed","success":false,"timestamp":1517154443105}"
$ku_key = 'KEY';
$ku_secret = 'SECRET';
$host = "https://api.kucoin.com";
$nonce = round(microtime(true) * 1000);
$endpoint = "/v1/order";
$querystring = "symbol=POE-BTC&price=0.00000748&amount=5514.70588235&type=BUY";
$signstring = $endpoint.'/'.$nonce.'/'.$querystring;
$hash = hash_hmac('sha256', base64_encode($signstring) , $ku_secret);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host . $endpoint);
$headers = [ 'KC-API-SIGNATURE:' . $hash, 'KC-API-KEY:' . $ku_key, 'KC-API-NONCE:' . $nonce, 'Content-Type:application/json' ];
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; Kucoin Bot; '.php_uname('a').'; PHP/'.phpversion().')' );
/*
YOU CAN USE THIS SECTION, I USE BOTH OF THEM WITH THIS AND WITHOUT THIS. NOT WORKING WITH BOTH.
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "symbol=POE-BTC&price=0.00000748&amount=5514.70588235&type=BUY");
*/
curl_setopt($ch, CURLOPT_URL, $host . $endpoint);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$data = curl_exec($ch);
var_dump($data);
I was facing the same error message today when I was implementing the KuCoin API in my trader software. However, I got it working. Please find my working solution below:
/**
*
* #see https://kucoinapidocs.docs.apiary.io/#introduction/authentication/signature-calculation
*
*/
private function signedRequest($endpoint, $params = array())
{
$ch = curl_init();
// Must be synced, KuCoin rejects requests > 3s
$nonce = round(microtime(true) * 1000);
// Build the data string.
// Note - According documentation:
// Arrange the parameters in ascending alphabetical order (lower cases first)
$queryString = http_build_query($params, '', '&');
// Splice string for signing
$auth = $endpoint . '/' . $nonce . '/' . $queryString;
// Make a base64 encoding of the completed string
$signedStr = base64_encode($auth);
$signature = hash_hmac('sha256', $signedStr, $this->secret);
$headers = array (
'KC-API-KEY:' . $this->key,
'KC-API-NONCE:' . $nonce,
'KC-API-SIGNATURE:' . $signature,
);
// POST is not allowed so we attach the parameter to the url
$curl = $this->base . $endpoint . "?" . $queryString;
// make the request
curl_setopt($ch, CURLOPT_URL, $curl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// do not print output to screen
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
return $result;
}
Tested with endpoint '/v1/account/balances'
public function getWalletBalance()
{
$params = array(
'limit' => '12',
'page' => '1'
);
$balance = $this->signedRequest("/v1/account/balances", $params);
return $this->_getFormattedBalance($balance);
}
You need to order your params alphabetically in both the query string and post request. Their docs need a little improvement but this is stated in them somewhere.
$querystring = "amount=5514.70588235&price=0.00000748&symbol=POE-BTC&type=BUY";
curl_setopt($ch, CURLOPT_POSTFIELDS, "amount=5514.70588235&price=0.00000748&symbol=POE-BTC&type=BUY");

interswitch quickteller API integration in php

i have to add interswitch payment methods in my web application but i am receiving error
following is my code
function billersCategories()
{
$nonce=$randomNum=substr(str_shuffle("0123456789abcdefghijklmnopqrstvwxyz"), 0, 60);
$date = new DateTime();
$timestamp=$date->getTimestamp();
// Signature
$httpMethod = "GET";
$url='https://sandbox.interswitchng.com/api/v2/quickteller/categorys';
$clientId = "IKIA9D98ABCDEFGHIFAKEID1E09104959B9755C41E1";
$clientSecretKey = "d5uAr+U8QhSv8vQtKPDIUI62327Fsfsfsf65=";
$signatureCipher = $httpMethod."&".$url."&".$timestamp."&".$nonce."&".$clientId."&".$clientSecretKey;
$signature = base64_encode($signatureCipher);
$data = array("TerminalID" => "9APY556261");
$data_string = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type:application/json',
'Authorization:InterswitchAuth SUtJQTUyNTBERkY1NkU5MzM2OUM0RkRBRjMxQTQ3QTg1RkNDODYyRTRDOUU=',
'Signature:'.$signature,
'Nonce:'.$nonce,
'Timestamp:'.$timestamp,
'SignatureMethod:SHA512'
));
$result = curl_exec($ch);
echo curl_getinfo($ch) . '<br/>';
echo curl_errno($ch) . '<br/>';
echo curl_error($ch) . '<br/>';
var_dump($result);
}
But i am receiving following error
"The HTTP method is not supported for this resource", i tried http method POST but same error, i am new on API can someone please help me to solve this .
Use this instead, fill the following
In the variable
- $clientId
- $clientSecretKey
At the header
- TerminalID
<?php
$nonce=$randomNum=substr(str_shuffle("0123456789abcdefghijklmnopqrstvwxyz"), 0, 60);
$date = new DateTime();
$timestamp=$date->getTimestamp();
$httpMethod = "GET";
$clientId = "YOUR_OWN_ID";
$clientSecretKey = "YOUR_OWN_CLIENT_SECRET_KEY";
$resourceUrl='https://sandbox.interswitchng.com/api/v2/quickteller/categorys';
$resourceUrl = strtolower($resourceUrl);
$resourceUrl = str_replace('http://', 'https://', $resourceUrl);
$encodedUrl = urlencode($resourceUrl);
$transactionParams = "1";
$httpMethod = "GET";
$signatureCipher = $httpMethod . '&' . $encodedUrl . '&' . $timestamp . '&' . $nonce . '&' . $clientId . '&' . $clientSecretKey;
if (!empty($transactionParams) && is_array($transactionParams)) {
$parameters = implode("&", $transactionParams);
$signatureCipher = $signatureCipher . $parameters;
}
$signature = base64_encode(sha1($signatureCipher, true));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$resourceUrl);
// curl_setopt($ch, CURLOPT_POST, 1);
// curl_setopt($ch, CURLOPT_POSTFIELDS,$vars); //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = [
'Content-Type:application/json',
'Authorization:InterswitchAuth SUtJQTAzREM3RDY5NUREMzZFQURFNTQxNEE2Nzg1MUJCMUZFQ0Y5MUIxRjg=',
'Signature:'.$signature,
'Nonce:'.$nonce,
'Timestamp:'.$timestamp,
'SignatureMethod:SHA1',
'TerminalID:YOUR_ASSIGNED_TERMINAL_ID'
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$server_output = curl_exec ($ch);
curl_close ($ch);
echo $server_output;
?>
This worked for me, hope it help someone in future

Categories