php rest API POST request returning null - php

I've created a REST API base on this tutorial - note that I am a newbie in php and REST...
Now, I am stuck when calling a POST request. The main return function is as follows:
// Requests from the same server don't have a HTTP_ORIGIN header
if (!array_key_exists('HTTP_ORIGIN', $_SERVER)) {
$_SERVER['HTTP_ORIGIN'] = $_SERVER['SERVER_NAME'];
}
try {
$API = new MyAPI($_REQUEST['request'], $_SERVER['HTTP_ORIGIN']);
$res = $API->processAPI();
echo $res; // contains my json as expected
return $res; // always empty string
} catch (Exception $e) {
echo "Exception: " . json_encode(Array('error' => $e->getMessage()));
}
EDIT
I've just tried something even simpler in the API caller method, namely following:
try {
$res = json_encode(Array('test' => "my message"));
// comment out one or the other to check output...
//echo $res;
return $res;
} catch (Exception $e) {
echo "Exception: " . json_encode(Array('error' => $e->getMessage()));
}
Result with echo is (the way I get responese is below... exact response is between # characters):
#{"test":"my message"}#
Result with return is
##
EDIT 2
Here is how I call the API from C#:
using (HttpClient client = new HttpClient()) {
JObject jo = new JObject();
jo.Add("usr", "username");
jo.Add("pwd", "password");
Uri url = new Uri(string.Format("{0}/{1}", RestUrl, "login"));
StringContent content = new StringContent(jo.ToString(), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, content);
bool isOk = response.StatusCode == System.Net.HttpStatusCode.OK;
// this is where I get the result from...
var res = response.Content.ReadAsStringAsync().Result;
}
I really don't understand this - could someone please explain in non-php expert terms??

Related

Getting a new accesstoken

I am trying to retrieve a new access token with my refresh token. Before I run a script to retrieve a new access token I want to check if my access token is still valid.
I am trying to do this with exceptions:
try
{
// Connect
$session = new SoapClient("../webservices/session.asmx?wsdl", array('trace' => 1));
$result = $session->AccessTokenLogon($accessTokenparams);
}
catch (SoapFault $e)
{
// Check if AcccessToken returns TokenInvalid
if ($result->AccessTokenLogonResult == "TokenInvalid")
{
// AccessToken is not valid anymore
// ..
// Run script to get new access token
// ..
// $_SESSION["access_token"] = $access_token;
}
else
{
// AccessToken is valid
echo "AccessToken is valid";
}
}
finally
{
// Run script with valid AccessToken
global $result, $session;
$cluster = $result->cluster;
$qq = new domDocument();
$qq->loadXML($session->__getLastResponse());
$newurl = $cluster . '/webservices/processxml.asmx?wsdl';
try
{
$client = new SoapClient($newurl);
$header = new SoapHeader('http://www.website.com/', 'Header', array('AccessToken' =>$_SESSION["access_token"]));
}
catch (SoapFault $e)
{
echo $e->getMessage();
}
try
{
echo '<br /><br />XML Result:<br /><br />';
$xml = ""; // XML request
$result = $client->__soapCall('ProcessXmlString', array(array('xmlRequest'=>$xml)), null, $header);
}
catch (SoapFault $e)
{
echo $e->getMessage();
}
}
With a valid access token the script is working. The XML request is posted to the webservice.
The script is not working when the accesstoken is not valid anymore. The script stores the new accesstoken in the session: $_SESSION["access_token"] = $access_token; but is not running the 'finally' part after retrieving a new accesstoken.
Does someone know how I can fix this and run the 'finally' after retrieving a new accesstoken?

Cannot Create Variant with SquareConnect

Using SquareConnect's PHP Sdk, I am trying to create a very basic variant product using their API.
`
require('connect-php-sdk-master/autoload.php');
$access_token="SECRETACCESS TOKEN";
$location_id="LOCATION ID"; //only need the one
// Configure OAuth2 access token for authorization: oauth2
SquareConnect\Configuration::getDefaultConfiguration()->setAccessToken($access_token);
$api_instance = new SquareConnect\Api\CatalogApi();
$object_id = "OBJECTIDTHATWORKS"; // string
$include_related_objects = true; //
//print out the objectid. Works perfectly!
try {
$result = $api_instance->retrieveCatalogObject($object_id,$include_related_objects);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling CatalogApi->retrieveCatalogObject: ', $e->getMessage(), PHP_EOL;
}
//now create the variant and it will fail
$var_api = new \SquareConnect\Api\V1ItemsApi();
$variation = new \SquareConnect\Model\V1Variation(); // \SquareConnect\Model\V1Variation | An object containing the fields to POST for the request. See the corresponding object definition for field details.
$variation->setName("JERSUB");
$variation->setSku("JERSUPPERSKU");
try {
$meresult = $var_api->createVariation($location_id, $object_id, $variation);
print_r($meresult);
} catch (Exception $e) {
echo 'Exception when calling V1ItemsApi->createVariation: ', $e->getMessage(), PHP_EOL;
}
`
No matter what I do I always get a 400 Bad request.
Exception when calling V1ItemsApi->createVariation: [HTTP/1.1 400 Bad Request] {"type":"bad_request","message":"BadRequest"}
I have tried just passing in a blank variation object like the documentation, but it still does not work. How do I get around or diagnose the error?
I was using an older V1 version of the API. I found an OO way of doing it that was actually smarter. Below is a snippet that should hopefully help someone.
require('connect-php-sdk-master/autoload.php');
$access_token="SECRETACCESS TOKEN";
$location_id="LOCATION ID"; //only need the one
// Configure OAuth2 access token for authorization: oauth2
SquareConnect\Configuration::getDefaultConfiguration()->setAccessToken($access_token);
$api_instance = new SquareConnect\Api\CatalogApi();
$object_id = "OBJECTIDTHATWORKS"; // string
$include_related_objects = true; //
try {
$result = $api_instance->retrieveCatalogObject($object_id,$include_related_objects);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling CatalogApi->retrieveCatalogObject: ', $e->getMessage(), PHP_EOL;
}
$clone=$results[0];
$clone->setId("#TEMP123"); //change it to a temp id
$clone->setType("ITEM_VARIATION");
$id=$clone->getId();
$var_data=$clone->getItemVariationData();
//now clear/update the cloned object
$var_data->setName(UPC_FIELD_NAME);
$var_data->setSku("SUPPERSKU_TEST2"); //update sku
$var_data->setPricingType("VARIABLE_PRICING");
$var_data->setTrackInventory(null);
$var_data->setLocationOverrides(null); //got to remove location ovverides or it will track.
$var_data->setPriceMoney(null);
$clone->setItemVariationData($var_data);
//upsert it
$upsert=new \SquareConnect\Model\UpsertCatalogObjectRequest();
//set unique key
$upsert->setIdempotencyKey(md5(time()));
$upsert->setObject($clone);
//fire the update
$update_result=$api_instance->upsertCatalogObject($upsert);

Alibaba cloud - video streaming

I want to use video on demand service of Alibaba cloud for video streaming.
video on demand makes different resolution videos from uploaded videos for data streaming.
For that, I am using https://github.com/aliyun/aliyun-openapi-php-sdk.
Now problem is that I don't know how to upload video in a video on demand panel via code. I have checked in a https://github.com/aliyun/aliyun-openapi-php-sdk/blob/master/aliyun-php-sdk-vod/vod/Request/V20170321/CreateUploadVideoRequest.php but haven't found field or parameter which is used to upload video. If any other SDK or code is there then please let me know. Even any document of a code or snippet is also appreciated.
Sample code snippet could be found here (in Simplified Chinese though): https://help.aliyun.com/document_detail/61069.html
<?php
include_once './aliyun-php-sdk/aliyun-php-sdk-core/Config.php'; //source php and aliyun-php-sdk in same directory
use vod\Request\V20170321 as vod;
function init_vod_client($accessKeyId, $accessKeySecret) {
$regionId = 'cn-shanghai';
$profile = DefaultProfile::getProfile($regionId, $accessKeyId, $accessKeySecret);
return new DefaultAcsClient($profile);
}
function create_upload_video($client) {
$request = new vod\CreateUploadVideoRequest();
$request->setTitle("VideoTitle"); // Video Title (Mandatory)
$request->setFileName("filename.mov"); // Source document file name with file extension (Mandatory)
$request->setDescription("Video Description"); // Video Description (Optional)
$request->setCoverURL("http://img.alicdn.com/tps/XXXXXXXXXXXXXXXXXXXXXXXXXXX-700-700.png"); // Custom video coverpage (Optional)
$request->setTags("Tag1,Tag2"); // Video tags, separated by commas (Optional)
$request->setAcceptFormat('JSON');
return $client->getAcsResponse($request);
}
try {
$client = init_vod_client('<AccessKeyId>', '<AccessKeySecret>');
$uploadInfo = create_upload_video($client);
var_dump($uploadInfo);
} catch (Exception $e) {
print $e->getMessage()."\n";
}
?>
There is also a demo for using OSS SDK to upload video available in https://help.aliyun.com/document_detail/61388.html (also in Simplified Chinese)
Hope this helps.
Please find the code snippet.
<?php
require_once './aliyun-php-sdk/aliyun-php-sdk-core/Config.php';
require_once './aliyun-php-sdk/aliyun-oss-php-sdk-2.2.4/autoload.php';
use vod\Request\V20170321 as vod;
use OSS\OssClient;
use OSS\Core\OssException;
function init_vod_client($accessKeyId, $accessKeySecret) {
$regionId = 'cn-shanghai';
$profile = DefaultProfile::getProfile($regionId, $accessKeyId, $accessKeySecret);
return new DefaultAcsClient($profile);
}
function create_upload_video($vodClient) {
$request = new vod\CreateUploadVideoRequest();
$request->setTitle("Movie");
$request->setFileName("elephant.mov");
$request->setDescription("It is about elephant");
$request->setCoverURL("http://img.alicdn.com/tps/TB1qnJ1PVXXXXXCXXXXXXXXXXXX-700-700.png");
$request->setTags("forest,elephant");
return $vodClient->getAcsResponse($request);
}
function refresh_upload_video($vodClient, $videoId) {
$request = new vod\RefreshUploadVideoRequest();
$request->setVideoId($videoId);
return $vodClient->getAcsResponse($request);
}
function init_oss_client($uploadAuth, $uploadAddress) {
$ossClient = new OssClient($uploadAuth['AccessKeyId'], $uploadAuth['AccessKeySecret'], $uploadAddress['Endpoint'],
false, $uploadAuth['SecurityToken']);
$ossClient->setTimeout(86400*7);
$ossClient->setConnectTimeout(10);
return $ossClient;
}
function upload_local_file($ossClient, $uploadAddress, $localFile) {
return $ossClient->uploadFile($uploadAddress['Bucket'], $uploadAddress['FileName'], $localFile);
}
function multipart_upload_file($ossClient, $uploadAddress, $localFile) {
return $ossClient->multiuploadFile($uploadAddress['Bucket'], $uploadAddress['FileName'], $localFile);
}
$accessKeyId = '<AccessKeyId>';
$accessKeySecret = '<AccessKeySecret>';
$localFile = '/Users/yours/Video/testVideo.flv';
try {
$vodClient = init_vod_client($accessKeyId, $accessKeySecret);
$createRes = create_upload_video($vodClient);
$videoId = $createRes->VideoId;
$uploadAddress = json_decode(base64_decode($createRes->UploadAddress), true);
$uploadAuth = json_decode(base64_decode($createRes->UploadAuth), true);
$ossClient = init_oss_client($uploadAuth, $uploadAddress);
//$result = upload_local_file($ossClient, $uploadAddress, $localFile);
$result = multipart_upload_file($ossClient, $uploadAddress, $localFile);
printf("Succeed, VideoId: %s", $videoId);
} catch (Exception $e) {
// var_dump($e);
printf("Failed, ErrorMessage: %s", $e->getMessage());
}
For more details, Please have a look at the official documentation
Here is the newest code update on 202105 for you.
the guide link as below:
https://www.alibabacloud.com/help/doc-detail/100976.htm?spm=a2c63.p38356.879954.13.330a12fcc5cLMD#task-1995280
<? php
/**
* Created by Aliyun ApsaraVideo VOD.
*/
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'voduploadsdk' . DIRECTORY_SEPARATOR . 'Autoloader.php';
date_default_timezone_set('PRC');
// Test the upload of an on-premises video.
function testUploadLocalVideo($accessKeyId, $accessKeySecret, $filePath)
{
try {
$uploader = new AliyunVodUploader($accessKeyId, $accessKeySecret);
$uploadVideoRequest = new UploadVideoRequest($filePath, 'testUploadLocalVideo via PHP-SDK');
//$uploadVideoRequest->setCateId(1);
//$uploadVideoRequest->setCoverURL("http://xxxx.jpg");
//$uploadVideoRequest->setTags('test1,test2');
//$uploadVideoRequest->setStorageLocation('outin-xx.oss-cn-beijing.aliyuncs.com');
//$uploadVideoRequest->setTemplateGroupId('6ae347b0140181ad371d197ebe289326');
$userData = array(
"MessageCallback"=>array("CallbackURL"=>"https://demo.sample.com/ProcessMessageCallback"),
"Extend"=>array("localId"=>"xxx", "test"=>"www")
);
$uploadVideoRequest->setUserData(json_encode($userData));
$res = $uploader->uploadLocalVideo($uploadVideoRequest);
print_r($res);
} catch (Exception $e) {
printf("testUploadLocalVideo Failed, ErrorMessage: %s\n Location: %s %s\n Trace: %s\n",
$e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString());
}
}
// Tests the upload of an online video.
function testUploadWebVideo($accessKeyId, $accessKeySecret, $fileURL)
{
try {
$uploader = new AliyunVodUploader($accessKeyId, $accessKeySecret);
$uploadVideoRequest = new UploadVideoRequest($fileURL, 'testUploadWebVideo via PHP-SDK');
$res = $uploader->uploadWebVideo($uploadVideoRequest);
print_r($res);
} catch (Exception $e) {
printf("testUploadWebVideo Failed, ErrorMessage: %s\n Location: %s %s\n Trace: %s\n",
$e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString());
}
}
// Test the upload of an on-premises M3U8 video.
function testUploadLocalM3u8($accessKeyId, $accessKeySecret, $m3u8FilePath)
{
try {
$uploader = new AliyunVodUploader($accessKeyId, $accessKeySecret);
$uploadVideoRequest = new UploadVideoRequest($m3u8FilePath, 'testUploadLocalM3u8 via PHP-SDK');
// Call the method for parsing the M3U8 playlist to obtain the URLs of parts. If the parsing result is invalid, manually assemble the URLs of parts. By default, the part files and M3U8 files are stored in the same directory.
$sliceFiles = $uploader->parseM3u8File($m3u8FilePath);
//print_r($sliceFiles);
$res = $uploader->uploadLocalM3u8($uploadVideoRequest, $sliceFiles);
print_r($res);
} catch (Exception $e) {
printf("testUploadLocalM3u8 Failed, ErrorMessage: %s\n Location: %s %s\n Trace: %s\n",
$e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString());
}
}
// Test the upload of an online M3U8 video.
function testUploadWebM3u8($accessKeyId, $accessKeySecret, $m3u8FileUrl)
{
try {
$uploader = new AliyunVodUploader($accessKeyId, $accessKeySecret);
$uploadVideoRequest = new UploadVideoRequest($m3u8FileUrl, 'testUploadWebM3u8 via PHP-SDK');
// Call the method for parsing the M3U8 playlist to obtain the URLs of parts. If the parsing result is invalid, manually assemble the URLs of parts. By default, the part files and M3U8 files are stored in the same directory.
$sliceFileUrls = $uploader->parseM3u8File($m3u8FileUrl);
//print_r($sliceFileUrls);
$res = $uploader->uploadWebM3u8($uploadVideoRequest, $sliceFileUrls);
print_r($res);
} catch (Exception $e) {
printf("testUploadWebM3u8 Failed, ErrorMessage: %s\n Location: %s %s\n Trace: %s\n",
$e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString());
}
}
#### Run the test code. ####
$accessKeyId = '<AccessKeyId>';
$accessKeySecret = '<AccessKeySecret>';
//$localFilePath = 'C:\test\sample.mp4';
$localFilePath = '/opt/video/sample.mp4';
//testUploadLocalVideo($accessKeyId, $accessKeySecret, $localFilePath);
$webFileURL = 'http://vod-test1.cn-shanghai.aliyuncs.com/b55b904bc612463b812990b7c8cc95c8/daa30814c0c340cf8199926f78aa5c0e-a0bc05ba62c3e95cc672e88b828148c9-ld.mp4?auth_key=1608774986-0-0-c56acd302bea0c331370d8ed686502fe';
testUploadWebVideo($accessKeyId, $accessKeySecret, $webFileURL);
$localM3u8FilePath = '/opt/video/m3u8/sample.m3u8';
//testUploadLocalM3u8($accessKeyId, $accessKeySecret, $localM3u8FilePath);
$webM3u8FileURL = 'http://vod-test1.cn-shanghai.aliyuncs.com/b55b904bc612463b812990b7c8cc95c8/daa30814c0c340cf8199926f78aa5c0e-195a25af366b5edae324c47e99a03f04-ld.m3u8?auth_key=1608775606-0-0-9fb038deaecd009dadd86721c5855629';
//testUploadWebM3u8($accessKeyId, $accessKeySecret, $webM3u8FileURL);

stripe webhook test mode response "none"

I am trying to update database.
I have set up the webhook in stripe in test mode and send a "invoice.payment_succeeded" test webhook to file.but it shows response "none" in stripe output.
What have i done wrong, here is the webhook file, please someone help me, i am very stuck at this. any help will be appreciate...
<?php
include '../admin/include/functions.php';
require_once('Stripe/lib/Stripe.php');
require_once 'stripe_secret.php';
// Retrieve the request's body and parse it as JSON
$input = #file_get_contents("php://input");
$event_json = json_decode($input);
$event_id = $event_json->id;
if(isset($event_json->id)) {
try {
Stripe::setApiKey($stripe['secretkey']);
$event = Stripe_Event::retrieve($event_id);
var_dump($event);
$invoice = $event->data->object;
if($event->type == 'invoice.payment_succeeded') {
$customer = Stripe_Customer::retrieve($invoice->customer);
$email = $customer->email;
$customerid = $customer->id;
/*$amount = $invoice->amount / 100;*/
$expiry = $invoice->period->end;
$expiredate = date('Y-d-m', $expiry);
$userup = $obj->run_query("UPDATE users SET Expiry_Date = '$expiredate' WHERE user_stripe_id = '$customerid' ");
if ($userup) {
echo "User Date extended";
}
// send a invoice notice email here
}
if($event->type == 'invoice.payment_failed') {
$obj->run_query("UPDATE users SET Status = '0' WHERE user_stripe_id = '$customerid' ");
echo "User membership expired";
}
}
catch(Stripe_CardError $e) {
}
catch (Stripe_InvalidRequestError $e) {
// Invalid parameters were supplied to Stripe's API
} catch (Stripe_AuthenticationError $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
} catch (Stripe_ApiConnectionError $e) {
// Network communication with Stripe failed
} catch (Stripe_Error $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
} catch (Exception $e) {
// Something else happened, completely unrelated to Stripe
}
}
http_response_code(200);
?>
The test webhooks from the test webhook button sends a webhook with the right format but all the values are null / zero / etc. Thus your line that does $obj->run_query("UPDATE users SET Expiry_Date = '$expiredate' WHERE user_stripe_id = '$customerid' "); will return a falsey result. This means you don't echo anything and just send back an empty 200 response.

PHP SOAP issue feeding in results

I'm trying to create a page that displays current results from CA Lottery using PHP. I've used XML before, but am having issues with SOAP. I found this page, but its not a lot of help.
I've put together the code below, and was able to get it to return an object. But I can't get it to feed in the results I need. Any help would be amazing.
try {
$options = array(
'soap_version'=>SOAP_1_1,
'exceptions'=>true,
'trace'=>1,
'cache_wsdl'=>WSDL_CACHE_NONE
);
$client = new SoapClient('http://services.calottery.com/CALotteryService.asmx?WSDL', $options);
} catch (Exception $e) {
echo "<p>Exception Error!</p>";
echo $e->getMessage();
}
echo '<p>Connection: Success;</p>';
try {
$response = $client->GetCurrentGameInfo();
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
$x = simplexml_load_string("<?xml version=\"1.0\"?>".$response->GetCurrentGameInfoResult->any);
var_dump($x);
Try this
var_dump($response);
$x = simplexml_load_string("<?xml version=\"1.0\"?>".$response->GetCurrentGameInfoResult->any);
var_dump($x);
at the end of your script. Kind of odd, but calottery is returning a fragment of XML in the response that needs to be further processed ( the simplexml_load_string ).

Categories