How to add an object parameter into a string post api curl? - php

Can someone help me to fix this issue, i need to provide an object type parameter to my code to fetch data using shopee API.
here is my code
$partner_key = "c423d22ccf4a8f1ca3cf9f49d7995f7d2a11e58b6a57036bd8385e8d978b4db2";
$partner_id = 2003151;
$shop_id = 30334567;
$ordersn = "";
$username = "info#pollandhopia.com";
$password = "101382qpqeiw";
$datenow = time();
$parcel->item_id = 455371271;
$parcel->variation_id = 0;
$parcel->order_item_id = 455371271;
$parcel->promotion_group_id = 0;
$object = json_encode($parcel);
$post = '{
"shopid": '.$shop_id.',
"ordersn": "220506EWDX3UXW",
"partner_id": '.$partner_id.',
"timestamp": '.$datenow.',
"parcels": '.$parcel.'
}';
$url = "https://partner.shopeemobile.com/api/v1/orders/split";
//Generate a signature base string for POST
$base_string = $url."|".$post;
//Generate a unique signature
$signature = hash_hmac('sha256', $base_string, $partner_key);
#echo $signature.'----'.$datenow.'-'.$object;exit;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization:".$signature, "Content-Type: application/json"));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
$result = json_decode($result);
curl_close($ch);
Then the documentation params is here
Here is my error:
An uncaught Exception was encountered
Type: Error
Message: Object of class stdClass could not be converted to string

Related

How to upload a photo using the Flickr API?

I'm unable to upload an image to Flickr using the Flickr API. I'm trying to do this in a web-based application running PHP.
I've tried DPZFlickr, which returns this, when trying to upload:
Array ( [stat] => fail [err] => Array ( ) )
Inspecting the Flickr API's response, it's the same as what is returned when trying Dantsu's version of phpFlickr, which returns this:
oauth_problem=signature_invalid&debug_sbs=...
I've rolled my own CURL, which returns this:
Upload result: HTTP/1.1 200 OK Date: Wed, 23 Jan 2019 16:09:39 GMT Content-Type: text/xml; charset=utf-8 Content-Length: 109 P3P: policyref="https://policies.yahoo.com/w3c/p3p.xml", CP="CAO...
Here's the full code I use for creating my CURL request (edited to use CurlFile):
$consumerSecret = $flickrApiSecret;
$ap_url = "https://up.flickr.com/services/upload/";
$apiKey = $flickrApiKey;
$oauth_nonce = time();
$oauthToken = $_SESSION["FlickrSessionOauthData"]["oauth_request_token"];
$oauthTokenSecret = $_SESSION["FlickrSessionOauthData"]["oauth_request_token_secret"];
$text = "Test";
$signatureMethod = "HMAC-SHA1";
$oauthVersion = "1.0";
$timestamp = time();
$parms = "description=".$text."&format=json&oauth_consumer_key=".$apiKey."&oauth_nonce=".$oauth_nonce;
$parms .= "&oauth_signature_method=".$signatureMethod."&oauth_timestamp=".$timestamp."&oauth_token=".$oauthToken;
$parms .= "&oauth_version=".$oauthVersion."&title=".$text;
$baseString = "";
$baseString .= "POST&".urlencode($ap_url)."&".urlencode($parms);
$hashkey = $consumerSecret."&".$oauthTokenSecret;
$apiSignature = base64_encode(hash_hmac('sha1', $baseString, $hashkey, true));
$filePath = "/path_to_file/0.jpg";
$postFields["description"] = $text;
$postFields["format"] = "json";
$postFields["photo"] = new \CurlFile($filePath, mime_content_type ( $filePath ), 'photo');
$postFields["title"] = $text;
print_r ($postFields);
print "<br />";
$url = "https://up.flickr.com/services/upload/";
$oauth_header = "oauth_consumer_key=".$apiKey.",oauth_nonce=".$oauth_nonce.",oauth_signature_method=".$signatureMethod.",oauth_timestamp=".$timestamp.",oauth_token=".$oauthToken.",oauth_version=".$oauthVersion.",oauth_signature=".$apiSignature;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Authorization: OAuth ".$oauth_header));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_VERBOSE, 0);
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
$response = curl_exec ($curl);
curl_close ($curl);
echo $response;
I'm at a loss. How to make this work?
This question and answer got me going in the right direction.
I still was unable to get my own CURL up and running, but I managed to hack a few lines of code in DPZFlickr's library to get that working.
I updated the httprequest function to this:
private function httpRequest($url, $parameters)
{
if (isset($parameters["photo"])) {
$p = $parameters["photo"];
$pf = substr($p, 1);
$parameters["photo"] = new \CurlFile($pf, mime_content_type ( $pf ), 'photo');
}
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_TIMEOUT, $this->httpTimeout);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
if ($this->method == 'POST')
{
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $parameters);
}
else
{
// Assume GET
curl_setopt($curl, CURLOPT_URL, "$url?" . $this->joinParameters($parameters));
}
$response = curl_exec($curl);
$headers = curl_getinfo($curl);
curl_close($curl);
$this->lastHttpResponseCode = $headers['http_code'];
return $response;
}
This includes one change:
Changing how the photo is included. Now through CurlFile.
I'm doing this on PHP 7.2. Apparently, the CURLOPT_SAFE_UPLOAD underwent some changes in PHP 5.x, while CurlFile became a requirement in PHP 7.1.

How to create local post on google my business page using php

I need to create a local host using google client api . I wrote following code to crate local post.
$service = new Google_Service_MyBusiness($client);
$callToAction = new Google_Service_MyBusiness_CallToAction();
$callToAction->setActionType('LEARN_MORE');
$callToAction->setUrl('localhost.com');
$mediaItem = new Google_Service_MyBusiness_MediaItem();
$mediaItem->setMediaFormat('PHOTO');
$mediaItem->setSourceUrl('https://www.theanthem.com/images/usps_eddm_postcards.jpg');
$localPost = new Google_Service_MyBusiness_LocalPost();
$localPost->setLanguageCode('en-US');
$localPost->setSummary('Just a summary');
$localPost->setCallToAction($callToAction);
$localPost->setMedia($mediaItem);
$parent = sprintf('accounts/%d/locations/%d',
'116633170334837786295',
'8830395735149945322'
);
$service->accounts_locations_localPosts->create($parent, $localPost);
But Unfortunately I got following error.
My Error: Message: Error calling POST
https://mybusiness.googleapis.com/v4/accounts/9223372036854775807/locations/8830395735149945322/localPosts:
(400) Request contains an invalid argument.
How can i fix this?
I found the answer:
create refresh token
$request_url = "https://www.googleapis.com/oauth2/v4/token";
$refresh_token = "*** Refresf Token ***";
$params = [
'client_id' => "***your client id***",
'client_secret' => "***your clinet secret id***",
'refresh_token' => $refresh_token,
'grant_type' => "refresh_token"
];
$curl = curl_init($request_url);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HEADER,'Content-Type: application/x-www-form-urlencoded');
$postData = "";
//This is needed to properly form post the credentials object
foreach($params as $k => $v) {
$postData .= $k . '='.urlencode($v).'&';
}
$postData = rtrim($postData, '&');
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
$json_response = curl_exec($curl);
$response = (array) json_decode( $json_response );
$myaccess_token = $response['access_token'];
And create Post
$location = 'accounts/accoutid/locations/location id';
$api_end_point_url = 'https://mybusiness.googleapis.com/v4/'.$location.'/localPosts';
$postfields = array(
'topicType' => "STANDARD",
'languageCode' => "en_US",
'summary' => 'test post 123',
);
$data_string = json_encode($postfields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_end_point_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $myaccess_token,'Content-Type: application/json'));
$data1 = json_decode(curl_exec($ch), true);
$http_code1 = curl_getinfo($ch, CURLINFO_HTTP_CODE);

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);

JSON RPC 2.0 API Call using CURL in PHP - Changelly API

I am trying to call changelly API with below codes but it is returning "Unauthorized" in response.
Appreciate if someone can help in identifying the mistake I am making in below code.
$API_URL = 'https://api.changelly.com';
$API_KEY = 'XXXXX';
$API_SECRET = 'XXXXX';
$message = array();
$message['jsonrpc'] = '2.0';
$message['method'] = 'getMinAmount';
$message['params'] = array('from' => 'BTC', 'to' => 'LTC');
$message['id'] ='12345';
$data = json_encode($message);
$sign = hash_hmac('SHA512', $data, $API_SECRET);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $API_URL);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_GET, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Accept: application/json",'Authorization:api-key: '.$API_KEY.':sign: '.$sign));
$final_result = curl_exec($ch);
curl_close($ch);
echo '<pre>';
print_r($final_result);
Changelly API guide is at https://changelly.com/developers
Thanks
in your code you have wrong set of headers.
please check this example: https://github.com/changelly/changelly-examples/blob/master/php/example.php, hope it helps.

How to use the WHMCS API without actually displaying WHMCS?

Is there any way in which i can use the WHMCS API without displaying WHMCS to the clients and users.
I want my PHP scripts to first create a WHMCS client, add an order for the client and then copy some files to the client's directory.
But i don't want my clients to be able to login to their WHMCS panel or even be able to see the WHMCS
WHMCS has something called External API that will help you.
Here is the documentation. But for what you need yo should do this:
Connect to the API
$url = "http://www.yourdomain.com/includes/api.php"; # URL to WHMCS API file goes here
$username = "Admin"; # Admin username goes here
$password = "demoxyz"; # Admin password goes here
Add the Client
$postfields = array();
$postfields["username"] = $username;
$postfields["password"] = md5($password);
$postfields["action"] = "addclient";
$postfields["firstname"] = "Test";
$postfields["lastname"] = "User";
$postfields["companyname"] = "WHMCS";
$postfields["email"] = "demo#whmcs.com";
$postfields["address1"] = "123 Demo Street";
$postfields["city"] = "Demo";
$postfields["state"] = "Florida";
$postfields["postcode"] = "AB123";
$postfields["country"] = "US";
$postfields["phonenumber"] = "123456789";
$postfields["password2"] = "demo";
$postfields["customfields"] = base64_encode(serialize(array("1"=>"Google")));
$postfields["currency"] = "1";
$query_string = "";
foreach ($postfields AS $k=>$v) $query_string .= "$k=".urlencode($v)."&";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$jsondata = curl_exec($ch);
if (curl_error($ch)) die("Connection Error: ".curl_errno($ch).' - '.curl_error($ch));
curl_close($ch);
$arr = json_decode($jsondata); # Decode JSON String
print_r($arr); # Output XML Response as Array
Add the Order
$postfields = array();
$postfields["username"] = $username;
$postfields["password"] = md5($password);
$postfields["action"] = "addorder";
$postfields["clientid"] = "1";
$postfields["pid"] = "1";
$postfields["domain"] = "whmcs.com";
$postfields["billingcycle"] = "monthly";
$postfields["addons"] = "1,3,9";
$postfields["customfields"] = base64_encode(serialize(array("1"=>"Google")));
$postfields["domaintype"] = "register";
$postfields["regperiod"] = "1";
$postfields["paymentmethod"] = "mailin";
$query_string = "";
foreach ($postfields AS $k=>$v) $query_string .= "$k=".urlencode($v)."&";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$jsondata = curl_exec($ch);
if (curl_error($ch)) die("Connection Error: ".curl_errno($ch).' - '.curl_error($ch));
curl_close($ch);
$arr = json_decode($jsondata); # Decode JSON String
print_r($arr); # Output XML Response as Array
Then you can copy the files to the client's directory. Hope it helps!

Categories