Wowza Cloud API: curl requests - php

I can't make it work.. :( I have this function (for create passthrough transcoder), when I run I see NULL in the web. If I test directly from the browser with the url, it does notify me that there is a problem an auth (apikey and acceskey)
function createPassthrough($name, $source_url, $recording = null)
{
$url = "https://sandbox.cloud.wowza.com/api/v1/transcoders";
$json = '{
"transcoder":{
"billing_mode":"pay_as_you_go",
"broadcast_location":"eu_belgium",
"delivery_method":"pull",
"name":"prueba",
"protocol":"rtsp",
"source_url":"url_camara",
"transcoder_Type":"passthrough",
"low_latency":true,
"buffer_size":0,
"play_maximum_connections":100,
"stream_smoother":false
}
}';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept:application/json; charset=utf-8',
'Content-Type: application/json; charset=utf-8',
'wsc-api-key:' . $apiKey,
'wsc-access-key:' . $accessKey,
));
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
var_dump($obj);
}
What am I doing wrong? Thanks in advance.

You should check for curl errors after $result = curl_exec($ch);.
// Check for errors and display the error message
if($errno = curl_errno($ch)) {
$error_message = curl_strerror($errno);
echo "cURL error ({$errno}):\n {$error_message}";
}

Related

file_get_content return null for some url

why some url with json content return null on php function get page content?
i used these ways :
file_get_content
curl
http_get
but return null . but when page open with browser json content show on browser ?? anyone can help me?
$url = 'https://pardakht.cafebazaar.ir/devapi/v2/api/validate/com.pdgroup.insta/inapp/coin_follow_1/purchases/324234235/?access_token=9IaRpdmQzFppJMabLHbHyzBaQnm8bM';
$result = file_get_content($url);
return null but in browser show
{"error_description": "Access token has expired.", "error": "invalid_credentials"}
It returns the following:
failed to open stream: HTTP request failed! HTTP/1.1 401 UNAUTHORIZED
So, you have to be authorized.
You ca play with this code snippet (I can't test since token expired again):
<?php
$access_token = "s9spZax2Xrj5g5bFZMJZShbMrEVjIo"; // use your actual token
$url = "https://pardakht.cafebazaar.ir/devapi/v2/api/validate/com.pdgroup.insta/inapp/coin_follow_1/purchases/324234235/";
// Solution with file_get_contents
// $content = file_get_contents($url . "?access_token=" . $access_token);
// echo $content;
// Solution with CURL
$headers = array(
"Accept: application/json",
"Content-Type: application/json",
"Authorization: Basic " . $access_token
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url); // . $params - if you need some params
curl_setopt($ch, CURLOPT_POST, false);
// curl_setopt($ch, CURLOPT_USERPWD, $userPwd);
$result = curl_exec($ch);
$ch_error = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($ch_error) {
throw new Exception("cURL Error: " . $ch_error);
}
if ($info["http_code"] !== 200) {
throw new Exception("HTTP/1.1 " . $info["http_code"]);
}
echo $result;

Issuing with making a post request with php curl

I'm trying to make a post request with php using curl however the json is not getting delivered to the REST API. Here is my code. In the webservice all I get is null value. I'm not sure where I'm going wrong.
$email_json_data = json_encode($email_data);
$header[] = "Content-type: application/json";
$ch = curl_init($api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $email_json_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
return $response;
Webservice code:
$email_json_data = $this->post('email_json_data');
$email_data = json_decode($email_json_data);
Check PHP: curl_errno
There's probably a problem connecting to the server, and it's probably in one of your $header. To find out more, you need to show (in production, LOG it) the curl error.
In the future, please try to include a complete code sample, rather than just snippets
Code added from PHP: curl_strerror
class CurlAdapter
{
private $api_url = 'www.somewhere.com/api/server.php';
private $error = "";
private function jsonPost($data)
{
// init curl
$ch = curl_init($this->api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl header
$header[] = "Content-type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
// build post data
$post_data = json_encode($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
// execute
if (empty($response = curl_exec($ch)) {
// Check for errors and display the error message
if($errno = curl_errno($ch)) {
$error_message = curl_strerror($errno);
$this->error = "cURL error ({$errno}):\n {$error_message}";
// #todo log curl error
}
}
// Close the handle
curl_close($ch);
return $response;
}
public function post( mixed $data )
{
if (empty($this->jsonPost($data))) {
return $this->error;
}
return $response;
}
}
$ca = new CurlAdapter();
echo $ca->post(['data' => 'testdata']);
Figured out a way to make this work.
Replaced $email_json_data = $this->post('email_json_data');
with $email_json_data = file_get_contents("php://input");

Getting error while sending http request via curl

I want to send charging request through php which I have sent via postman and it worked, but when I try this with php I m getting error response.
I have tried to send the request using curl and used function to send the request. But, after hitting the php I m getting the response that "invalid request" .
Here is the code snippet:
<?php
define('TML_CHARGE_URL2', 'http://sandbox-apigw.mytelenor.com.mm/v1/mm/en/customers/products/vas');
$client_id="MDq0MdGtZUGZWfanE8k2fva7GsLvwS0I";
$client_secret="GEzAxTE6YYSfLEAD";
$accessToken="ytSxhvjSUfNEurD5M6SOJPm6XAfu";
/* CP & Product Codes */
$cpid="15";
$login="apigwtest";
$password="apigwtestpwd";
$client_id="175612092873562378";
$msisdn="9791000601";
$prod_code = "APIGW_TEST";
$requestParamList = array("cpID" => $cpid,
"clientTransactionId" => $client_id,
"loginName" => $login,
"password" => $password,
"id" => array (
"type" => "MSISDN",
"value" => $msisdn
),
"productCode" => $prod_code
);
function callAPI($apiURL, $requestParamList) {
$jsonResponse = "";
$responseParamList = array();
$JsonData =json_encode($requestParamList);
$postData = 'JsonData='.urlencode($JsonData);
$ch = curl_init($apiURL);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
echo $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); //get status code
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($postData),
'Authorization: Bearer ytSxhvjSUfNEurD5M6SOJPm6XAfu'
)
);
echo $jsonResponse = curl_exec($ch);
$responseParamList = json_decode($jsonResponse,true);
return $responseParamList;
}
function oneshotpayment($requestParamList) {
return callAPI(TML_CHARGE_URL, $requestParamList);
}
function subscription_payment($requestParamList) {
return callAPI(TML_CHARGE_URL2, $requestParamList);
}
echo subscription_payment($requestParamList);
?>
The error response is like below:
{
"transactionId": "",
"timestamp": "2017-08-13T17:28:24+06:30",
"recipientMsisdn": "",
"code": "500.023.003",
"error": "Internal Server Error",
"message": "Request input is malformed or invalid"
}
You need to change your callAPI method.
1) You dont need to do urlencode after you have done json_encode
2) Remove unnecessory concatination of 'JsonData='. in string.
change you method like below
function callAPI($apiURL, $requestParamList) {
$postData = "";
$responseParamList = array();
$postData =json_encode($requestParamList);
$ch = curl_init($apiURL);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
echo $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); //get status code
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($postData),
'Authorization: Bearer ytSxhvjSUfNEurD5M6SOJPm6XAfu'
)
);
echo $jsonResponse = curl_exec($ch);
$responseParamList = json_decode($jsonResponse,true);
return $responseParamList;
}

Basic Authorization PHP with Server related

I have some problem that related to HTTP_HEADERS in curl php in opencart. The code below is caller.
$ch = curl_init();
$url = 'http://aaa.com/index.php?route=common/home/getTotalCustomer';
$url2 = 'http://bbb.com/index.php?route=common/home/getTotalCustomer';
$url3 = 'http://ccc.com/index.php?route=common/home/getTotalCustomer';
$header = array('Authorization:Basic ' . base64_encode('user:password'));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$results = curl_exec($ch);
echo '<pre>';
print_r(json_decode($results, true));
echo '</pre>';
The receiver code like below:
public function getTotalCustomer(){
$json = array();
$this->load->model('account/customer');
if(isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])){
if(($_SERVER['PHP_AUTH_PW'] == 'password') && ($_SERVER['PHP_AUTH_USER'] == 'user')){
$json['total_customer'] = $this->model_account_customer->getTotalCustomer();
}
} else{
$json['message'] = 'failed';
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
I had tried in multiple domain with different servers. Some server can return the data but some server cannot return the data. Why?
Your header that you're sending is incorrect.
You're passing
Authorization:Basic <username:password>
it should be
Authorization: Basic <username:password>
note the space.

Yammer - How to post via api to activity stream? (php)

I am able to "GET" the activity stream but not "POST" to it. It seems its a technical error.
This is the code which works for getting the activity stream:
function getActivityStream()
{
$as=$this->request('https://www.yammer.com/api/v1/streams/activities.json');
var_dump($as);
}
function request($url, $data = array())
{
if (empty($this->oatoken)) $this->getAccessToken();
$headers = array();
$headers[] = "Authorization: Bearer " . $this->oatoken['token'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . '?' . http_build_query($data) );
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
return json_decode($output);
}
ok so that works fine...
the code below, returns a Yammer "oops this page could not be found" message:
function putActivityStream()
{
$data=array('type'=>'text', 'text'=>'hello from api test call');
$json=json_encode($data);
$res=$this->post('streams/activites.json',$json);
}
function post($resource, $data)
{
if (empty($this->oatoken)) $this->getAccessToken();
$ch = curl_init();
$headers = array();
$headers[] = "Authorization: Bearer " . $this->oatoken['token'];
$headers[]='Content-Type: application/json';
$url = 'https://www.yammer.com/api/v1/' . $resource;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
return $response;
}
One of the examples from:
http://developer.yammer.com/api/streams.html
POST https://www.yammer.com/api/v1/streams/activities.json
Requests must be content-type: application/json.
{
"type": "text",
"text": "The build is broken."
}
You're going to kick yourself. You have a typo in your code. :)
Change:
$res=$this->post('streams/activites.json',$json);
to
$res=$this->post('streams/activities.json',$json);
Simples.

Categories