I'm trying to connect my account with PHONEGAP REST API by implementing CURL with laravel framework. Somehow I could do things with GET but never done with POST and PUT. Is there anything wrong with my code? here's my example for uploading:
App\Http\Controllers\BuildApiController#testBuild:
use...
public function testBuild(Request $request)
{
$build = new PgBuild('myemail#test.us','mypassword');
$title = $request->title;
$file = $request->file;
$method = 'file';
$data = $build->uploadApp($file, $title, $method);
return response()->json($data);
}
App\PgBuild#uploadApp:
public function uploadApp($file, $title, $createMethod) {
$link = "https://build.phonegap.com/api/v1/apps";
CURL_SETOPT($this->ch, CURLOPT_POST, 1);
CURL_SETOPT($this->ch, CURLOPT_URL, $link);
$post = array(
"data" => array('create_method' => $createMethod, 'title' => $title),
"file" => $file
);
CURL_SETOPT($this->ch, CURLOPT_POSTFIELDS, $post);
$output = curl_exec($this->ch);
$obj = json_decode($output);
if (is_object($obj) && isset($obj->id)) {
return json_encode($obj->id);
} else {
return false;
}
}
Thank you,
Related
I've been trying to select values (students data) from mysql database table and looping through database to send to an API using PHP CURL Post request but it's not working.
This is the API body:
{
"students":[
{
"admissionNumber": "2010",
"class":"js one"
},
{
"admissionNumber": "2020",
"class":"ss one"
}
],
"appDomain":"www.schooldomain.com"
}
Parameters I want to send are "admissionNumber" and "class" parameters while "appDomain" is same for all. Here's my code:
if(isset($_POST['submit'])){
$body = "success";
$info = "yes";
class SendDATA
{
private $url = 'https://url-of-the-endpoint';
private $username = '';
private $appDomain = 'http://schooldomain.com/';
// public function to commit the send
public function send($admNo,$class)
{
$url_array= array('admissionNumber'=>$admNo,'class'=>$class,'appDomain'=>$this-> appDomain);
$url_string = $data = http_build_query($url_array);
// using the curl library to make the request
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, $this->url);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $url_string);
curl_setopt($curlHandle, CURLOPT_POST, 1);
$responseBody = curl_exec($curlHandle);
$responseInfo = curl_getinfo($curlHandle);
curl_close($curlHandle);
return $this->handleResponse($responseBody,$responseInfo);
}
private function handleResponse($body,$info)
{
if ($info['http_code']==200){ // successful submission
$xml_obj = simplexml_load_string($body);
// extract
return true;
}
else{
// error handling
return false;
}
}
}
$sms = new SendDATA();
$result = mysqli_query( $mysqli, "SELECT * FROM school_kids");
while ($row = mysqli_fetch_array($result)) {
$admNo = $row['admNo'];
$class = $row['class'];
$sms->send($admNo,$class,"header");
echo $admNo. " ".$class;
}
}
The question is rather unclear; when you say "this is the API body", I presume this JSON fragment is what the REST API at https://url-of-the-endpoint expects. If so, you are building your request body wrong. http_build_query creates an URL-encoded form data block (like key=value&anotherKey=another_value), not a JSON. For a JSON, here's what you want:
$data = array('students' => array
(
array('admissionNumber' => $admNo, 'class' => $class)
),
'appDomain':$this->appDomain
);
$url_string = $data = json_encode($data);
Also, you probably want to remove the HTTP headers from the response:
curl_setopt($curlHandle, CURLOPT_HEADER, false);
I want to create function which will execute other url (this url generate file on server) and get responce and then send message to user, but I want not to use ajax, I try to user Reqeust object but it don't work.
public function testCreateFile() {
$uri = 'http://someuri/somefuncition';
$method = 'POST';
$paramaters = array(
'csv' => '20190102212655-product-test.csv',
'type' => '5',
);
$request = new Request();
$request->create($uri,$method,$paramaters);
return new Response("Message to user") ;
}
How I should do coreectly?
Thanks for help in advance.
What you need is curl.
The best way is to use bellow code as Service, so I'll give the complete Class
The Service class
<?php
App\Services;
class PostRequest
{
static function get_data(String $url, Array $post_parameters)
{
//url-ify the data for the POST
$parameters_string = "";
foreach($post_parameters as $key=>$value) {
$parameters .= $key.'='.$value.'&';
}
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_POST, count($post_parameters));
curl_setopt($ch,CURLOPT_POSTFIELDS, $parameters);
//execute post
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
}
?>
So after including use App\Services\PostRequest; inside your Controller, you can do this
public function testCreateFile() {
$uri = 'http://someuri/somefuncition';
$paramaters = [
'csv' => '20190102212655-product-test.csv',
'type' => '5',
];
$request = PostRequest::get_data($uri, $paramaters);
return new Response("Message to user") ;
}
I am trying to search (filter) for files in a Dropbox folder, but no files are being found when there are files that match the filter. I am not using the PHP library provided by Dropbox.
Here is an extract of the code:
class Dropbox {
private $headers = array();
private $authQueryString = "";
public $SubFolders = array();
public $Files = array();
function __construct() {
$this->headers = array('Authorization: OAuth oauth_version="1.0", oauth_signature_method="PLAINTEXT", oauth_consumer_key="'.DROPBOX_APP_KEY.'", oauth_token="'.DROPBOX_OAUTH_ACCESS_TOKEN.'", oauth_signature="'.DROPBOX_APP_SECRET.'&'.DROPBOX_OAUTH_ACCESS_SECRET.'"');
$this->authQueryString = "oauth_consumer_key=".DROPBOX_APP_KEY."&oauth_token=".DROPBOX_OAUTH_ACCESS_TOKEN."&oauth_signature_method=PLAINTEXT&oauth_signature=".DROPBOX_APP_SECRET."%26".DROPBOX_OAUTH_ACCESS_SECRET."&oauth_version=1.0";
}
public function GetFolder($folder, $fileFilter = "") {
//Add the required folder to the end of the base path for folder call
if ($fileFilter == "")
$subPath = "metadata/sandbox";
else
$subPath = "search/sandbox";
if (strlen($folder) > 1) {
$subPath .= (substr($folder, 0, 1) != "/" ? "/" : "")
.$folder;
}
//Set up the post parameters for the call
$params = null;
if ($fileFilter != "") {
$params = array(
"query" => $fileFilter
);
}
//Clear the sub folders and files logged
$this->SubFolders = array();
$this->Files = array();
//Make the call
$content = $this->doCall($subPath, $params);
//Log the files and folders
for ($i = 0; $i < sizeof($content->contents); $i++) {
$f = $content->contents[$i];
if ($f->is_dir == "1") {
array_push($this->SubFolders, $f->path);
} else {
array_push($this->Files, $f->path);
}
}
//Return the content
return $content;
}
private function doCall($urlSubPath, $params = null, $filePathName = null, $useAPIContentPath = false) {
//Create the full URL for the call
$url = "https://api".($useAPIContentPath ? "-content" : "").".dropbox.com/1/".$urlSubPath;
//Initialise the curl call
$ch = curl_init();
//Set up the curl call
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($params != null)
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$fh = null;
if ($filePathName != null) {
$fh = fopen($filePathName, "rb");
curl_setopt($context, CURLOPT_BINARYTRANSFER, true);
curl_setopt($context, CURLOPT_INFILE, $fh);
curl_setopt($context, CURLOPT_INFILESIZE, filesize($filePathName));
}
//Excecute and get the response
$api_response = curl_exec($ch);
if ($fh != null)
fclose($fh);
//Process the response into an array
$json_response = json_decode($api_response);
//Has there been an error
if (isset($json_response->error )) {
throw new Exception($json_response["error"]);
}
//Send the response back
return $json_response;
}
}
I then call the GetFolder method of Dropbox as such:
$dbx = new Dropbox();
$filter = "MyFilter";
$dbx->GetFolder("MyFolder", $filter);
print "Num files: ".sizeof($dbx->Files);
As I am passing $filter into GetFolder, it uses the search/sandbox path and creates a parameter array ($params) with the required query parameter in it.
The process works fine if I don't provide the $fileFilter parameter to GetFolder and all files in the folder are returned (uses the metadata/sandbox path).
Other methods (that are not in the extract for brevity) of the Dropbox class use the $params feature and they to work fine.
I have been using the Dropbpox API reference for guidance (https://www.dropbox.com/developers/core/docs#search)
At first glance, it looks like you're making a GET request to /search but passing parameters via CURLOPT_POSTFIELDS. Try using a POST or encoding the search query as a query string parameter.
EDIT
Below is some code that works for me (usage: php search.php <term>). Note that I'm using OAuth 2 instead of OAuth 1, so my Authorization header looks different from yours.
<?php
$access_token = '<REDACTED>';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.dropbox.com/1/search/auto');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization:Bearer ' . $access_token));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('query' => $argv[1]));
$api_response = curl_exec($ch);
echo "Matching files:\n\t" . join("\n\t",
array_map(function ($file) {
return $file['path'];
}, json_decode($api_response, true)))."\n";
?>
I have this ZF controller which is a very basic DB query and reading the user status as true or false. If i use in browser the direct URL it works instantly.
Server 1:
public function getstatusAction() {
$this->_response->setHeader('Access-Control-Allow-Origin', '*');
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$post = $this->getRequest()->getQuery();
//$data = (object) $post;
$this->db = Application_Model_Db::db_load();
$sql = "select id from users where
status='online'
limit 1";
$result = $this->db->fetchAll($sql);
$json = '';
if (count($result) > 0) {
$json = array(
'result' =>true,
);
} else {
$json = array(
'result' =>false,
);
}
$this->getResponse()
->setHeader('Content-Type', 'application/json')
->setBody(Zend_Json::encode($json))
->sendResponse();
exit;
}
But when i from Server 2 reading that url using following, its taking forever and not even getting success
$section = file_get_contents("http://server1.domain.com/ajax/getstatus");
How can i fix it? (also do not see any error logs)
Make sure allow_url_fopen is set to "1" on the server2.
Alternatively you can use this function:
function get_content($URL){
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $URL);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
I want to create an app with ios platform set up from the .p12 file. How do I do that?
This is the method for creating app:
class AppHandler
{
public $USER_AUTH_KEY = 'Insert your key here';
public function create($name, $apns_p12 = null, $apns_p12_password = null, $gcm_key = null, $android_gcm_sender_id = null)
{
$fields = array(
'name' => $name,
'apns_p12' => $apns_p12,
'apns_p12_password' => $apns_p12_password,
'gcm_key' => $gcm_key,
'android_gcm_sender_id' => $android_gcm_sender_id
);
$fields = json_encode($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/apps");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
"Authorization: Basic " . $this->USER_AUTH_KEY));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
try {
$response = curl_exec($ch);
if (!$response) {
throw new Exception("App wasn't created");
}
} catch (Exception $e) {
echo 'Error: ', $e->getMessage(), "\n";
} finally {
curl_close($ch);
}
$response = json_decode($response, true);
$return = array(
'id' => $response['id'],
'basic_auth_key' => $response['basic_auth_key']
);
return $return;
}
...
And this is the method with 2 ways of getting the insides of .p12 file:
public function getP12($pkcs12, $password = NULL): string
{
/*
// Way 1:
$pkcs12 = file_get_contents($pkcs12);
$encoded = base64_encode($pkcs12);
return $encoded;
*/
// Way 2:
$cert_store = file_get_contents($pkcs12);
if (!$cert_store) {
echo "Error: can't read file.\n";
exit;
}
$pkcs12Read = openssl_pkcs12_read($cert_store, $cert_info, $password);
if ($pkcs12Read) {
$result = base64_encode($cert_info['cert']);
return $result;
} else {
echo "Error: can't read cert.\n";
exit;
}
}
According to onesignal's doc I have to send apns_p12 as my apple push notification p12 certificate file, converted to a string and Base64 encoded.
And I do that this way:
$obj = new AppHandler();
$response = $obj->create('TestName', $obj->getP12('cert.p12', 'password'), 'password')
It creates an app with given name, however, the platform is not set up.
What do you mean by "the platform is not set up"? What error are you getting and where?
By the way, I finally gave up trying code the intricacies of APNS programming and instead went with AWS' Simple Notification Service: https://aws.amazon.com/sns. It handles both Apple and Google notifications by using the API to set up topics and subscribers, plus you can send up to 1 million notifications per month free.
Ok, I got it. I simply needed to add apns_env parameter:
$fields = array(
'name' => $name,
'apns_env' => $apns_env,
'apns_p12' => $apns_p12,
'apns_p12_password' => $apns_p12_password,
'gcm_key' => $gcm_key,
'android_gcm_sender_id' => $android_gcm_sender_id
);
And I should've taken insides of the file and converted them to a string and Base64 encoded like that:
public function getP12($pkcs12): string
{
$apns_12 = base64_encode(file_get_contents($pkcs12));
return $apns_12;
}