RSSBus Connect could not able to create file - rss

I am integrating my code for creating file in RSSBus | Connect.
Below is my Javascript Code:
<?php
$header = base64_encode(USERNAME. ":" . USERPASS);
$content = base64_encode('Welcome');
?>
<div id="result">
Content will loading here...
</div>
<script src="../../../js/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
var surl = 'http://xxxxxxx/api.rsc/files?x-rssbus-uthtoken='+token+'&#jsonp';
var postdata = {
PortId: "xxxxxxxxx",
Folder: "Send",
Filename: "testfile.xml",
Content: "<?php echo $content; ?>"
};
$.ajax({
type: "POST",
url: surl,
processData: false,
contentType: 'application/json',
data: JSON.stringify(postdata),
dataType: 'jsonp',
crossDomain: true,
}).done(function(data){
var data = JSON.stringify(data);
$("#result").html("<pre>"+data+"</pre>");
}).fail(function(data){
console.log('fail');
});
});
</script>
I have run this javascript in php. All code works perfectly but the file could not be created in "Send" folder. i am also getting proper response but it converts into GET parameter and error gives like "405 Method Not Allowed" comes in all response. when successfully response comes but the file is not creating in folder.
Please provide me solutions ASAP.

Please try with below code. I was success to crate file.
$url = 'xxxxxxxxxxxxxxxx/api.rsc/files';
$portid = 'PORT';
$folder = 'Send or Receiver Folder name';
$filename = 'mytest.xml';
$content = base64_encode('file content');
$fields = array( 'PortId' => $portid, 'Filename' => $filename, 'Folder' => $folder, 'Content' => $content);
$data_string = json_encode($fields);
$header = array('Authorization: Basic '.base64_encode(AS2_USERNAME. ":" . AS2_USERPASS)
,'Content-Type: application/json'
,'Content-Length: '.strlen($data_string)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_VERBOSE, true);
$result = curl_exec($ch);
if(!curl_errno($ch)){
$info = curl_getinfo($ch);
_printr($info);
echo "<br /><br />";
}else{
echo 'Curl error: ' . curl_error($ch);
}
curl_close($ch);
var_dump( $result );

Related

OpenAI API null response [duplicate]

I am getting an error for the following PHP code:
$curl = curl_init("https://api.openai.com/v1/engines/davinci/completions");
$data = array(
'prompt' => 'how many sundays in 2023',
'max_tokens' => 256,
'temperature' => 0.7,
'model' => 'text-davinci-003'
);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Authorization: Bearer sk-MY-API-KEY']);
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
$result = curl_exec($curl);
curl_close($curl);
$result = json_decode($result);
print $result->choices[0]->text;
I correctly provided the API Key, but getting this error:
Error message: You didn't provide an API key. You need to provide your API key in an Authorization header using Bearer auth (i.e. Authorization: Bearer YOUR_KEY)
All Engines endpoints are deprecated.
This is the correct Completions endpoint:
https://api.openai.com/v1/completions
Working example
If you run php test.php in CMD, the OpenAI API will return the following completion:
string(23) "
This is indeed a test"
test.php
<?php
$ch = curl_init();
$url = 'https://api.openai.com/v1/completions';
$api_key = 'sk-xxxxxxxxxxxxxxxxxxxx';
$post_fields = '{
"model": "text-davinci-003",
"prompt": "Say this is a test",
"max_tokens": 7,
"temperature": 0
}';
$header = [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error: ' . curl_error($ch);
}
curl_close($ch);
$response = json_decode($result);
var_dump($response->choices[0]->text);
?>

Contact form 7 loading infinitely after connecting it to our CRM API

Contact form 7 loading infinitely after connecting it to our CRM API though the email is being sent and data getting submitted and saved the user feels that the data has not yet been submitted since the loader keeps moving.
Here's my code added in functions.php
add_action('wpcf7_mail_sent', function ($cf7) {
if(isset($_POST['your-name']) && isset($_POST['your-email']) && isset($_POST['mobile_no'])){
$name = $_POST['your-name'];
$email = $_POST['your-email'];
$phone = $_POST['mobile_no'];
$data = array(
"name"=>"$name",
"email"=>"$email",
"mobile"=>"$phone",
"secret_key"=>"{secret_key}",
);
leadToNoPaperFormAPI($data);
}
});
function leadToNoPaperFormAPI($data=array())
{
if(is_array($data) && !empty($data))
{
$data_string = json_encode($data);
$ch = curl_init('{API_URL}');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
$array = json_decode($result);
}
}
Any help will be highly appreciated. :)
Please note the code gets executed and the form gets submitted & email sent, however, the user on the browser doesn't see the success message just sees the loader.

How to delete a page using wordpress rest api through curl

I have done all pages listed in core PHP application using wordpress REST API with CURL but I can't delete that pages with CURL.I got message "{code: "rest_cannot_delete", message: "Sorry, you are not allowed to delete this post.}" every time.
Here is my code.
$url = 'http://localhost/wordpress/wp-json/wp/v2/pages/37';
$postdata = 37; //pageID
function callrestapi_curlDelete($url, $postdata) {
$postdata_json = json_encode($postdata);
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
));
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata_json);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
echo json_decode($resp, TRUE);
}
Or if I tried via this code than I am getting the same error.
$.ajax({
url: 'http://localhost/wordpress/wp-json/wp/v2/pages/15 ',
method: 'DELETE',
crossDomain: true,
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'Authorization', 'Basic ' + Base64.encode('admin:admin#123'));
},
success: function( data, txtStatus, xhr ) {
console.log( data );
console.log( xhr.status );
}
});
There is no need to post any data to delete a page/post. The URL is enough as you have already included the ID you want to delete. See example below:
$postid = 108;
$rest_api_url = "http://www.example.com/wp-json/wp/v2/post/".$postid;
$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_URL, $rest_api_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer '.$token,
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
Notice the variable $token for Authorization which i'm assuming you already know how to generate through basic auth.
This will put the post into trash, if you want to delete permanently then add the following to the end of your URL.
?force=true
add this line to your cURL code
curl_setopt($ch, CURLOPT_USERPWD, "username" . ":" . "password");
don't forget to install and activated basic auth master plugin

LinkedIn API - how to post company update using Oauth2 & PHP

I am trying to modify LinkedIn's sample authorization code to post a company update.
Have the original code example working, meaning I can login to my user profile. So the next step would be posting the update.
Have found some info on the Internet and here at stackoverflow.com, and the result is the function PostUpdate() found in the code below. The rest of the code pretty much comes straight from the Linkedin code sample.
So this code seems to run, I get no errors reported, but I also get no update on the company page. There is one issue I notice, after successfully logging-in, the code prints "Hello $user->firstName $user->lastName." but my name does NOT show up on the screen. The "Hello" does, so perhaps this indicates where a problem might be found.
<?php
//config.php contains the API KEY, SECRET, AND COMPANY ID
//define('API_KEY', 'your key');
//define('API_SECRET', 'your secret');
//define('COMPANY_ID', 'your company id');
require_once('config.php');
// You must pre-register your redirect_uri at https://www.linkedin.com/secure/developer
define('REDIRECT_URI', 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME']);
define('SCOPE', 'r_basicprofile r_emailaddress w_share rw_company_admin');
// You'll probably use a database
session_name('linkedin');
session_start();
// OAuth 2 Control Flow
if (isset($_GET['error'])) {
// LinkedIn returned an error
print $_GET['error'] . ': ' . $_GET['error_description'];
exit;
} elseif (isset($_GET['code'])) {
// User authorized your application
if ($_SESSION['state'] == $_GET['state']) {
// Get token so you can make API calls
getAccessToken();
} else {
// CSRF attack? Or did you mix up your states?
exit;
}
} else {
if ((empty($_SESSION['expires_at'])) || (time() > $_SESSION['expires_at'])) {
// Token has expired, clear the state
$_SESSION = array();
}
if (empty($_SESSION['access_token'])) {
// Start authorization process
getAuthorizationCode();
}
}
// Congratulations! You have a valid token. Now fetch your profile
$user = fetch('GET', '/v1/people/~:(firstName,lastName)');
print "Hello $user->firstName $user->lastName.";
// temporary message content for test purposes
$xml_txt = "<?xml version='1.0' encoding='UTF-8'?>
<share>
<visibility>
<code>anyone</code>
</visibility>
<comment>Testing a full company share!!!!!</comment>
<content>
<submitted­-url>https://www.example.com/test-2.html</submitted-­url>
<title>Test Share with Content</title>
<description>content description</description>
<submitted-image-­url>https://www.example.com/img/internet.jpg</submitted­-image-­url>
</content>
</share>";
//Post the message
$result = PostUpdate($xml_txt);
//Done
exit;
function PostUpdate($message) {
print $_SESSION['access_token'];
$url = 'https://api.linkedin.com/v1/companies/'. COMPANY_ID . '/shares';
// build your message
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $message );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/xml', 'Authorization: Bearer ' . $this->access_token));
$response = curl_exec($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
print_r($response);
echo $http_status;
}
function getAuthorizationCode() {
$params = array(
'response_type' => 'code',
'client_id' => API_KEY,
'scope' => SCOPE,
'state' => uniqid('', true), // unique long string
'redirect_uri' => REDIRECT_URI,
);
// Authentication request
$url = 'https://www.linkedin.com/uas/oauth2/authorization?' . http_build_query($params);
// Needed to identify request when it returns to us
$_SESSION['state'] = $params['state'];
// Redirect user to authenticate
header("Location: $url");
exit;
}
function getAccessToken() {
$params = array(
'grant_type' => 'authorization_code',
'client_id' => API_KEY,
'client_secret' => API_SECRET,
'code' => $_GET['code'],
'redirect_uri' => REDIRECT_URI,
);
// Access Token request
$url = 'https://www.linkedin.com/uas/oauth2/accessToken?' . http_build_query($params);
// Tell streams to make a POST request
$context = stream_context_create(
array('http' =>
array('method' => 'POST',
)
)
);
// Retrieve access token information
$response = file_get_contents($url, false, $context);
// Native PHP object, please
$token = json_decode($response);
// Store access token and expiration time
$_SESSION['access_token'] = $token->access_token; // guard this!
$_SESSION['expires_in'] = $token->expires_in; // relative time (in seconds)
$_SESSION['expires_at'] = time() + $_SESSION['expires_in']; // absolute time
return true;
}
function fetch($method, $resource, $body = '') {
print $_SESSION['access_token'];
$opts = array(
'http'=>array(
'method' => $method,
'header' => "Authorization: Bearer " . $_SESSION['access_token'] . "\r\n" . "x-li-format: json\r\n"
)
);
// Need to use HTTPS
$url = 'https://api.linkedin.com' . $resource;
// Append query parameters (if there are any)
if (count($params)) { $url .= '?' . http_build_query($params); }
// Tell streams to make a (GET, POST, PUT, or DELETE) request
// And use OAuth 2 access token as Authorization
$context = stream_context_create($opts);
// Hocus Pocus
$response = file_get_contents($url, false, $context);
// Native PHP object, please
return json_decode($response);
}
Finally posted a company update (share) successfully.
One issue that made the LinkedIn code sample (https://developer-programs.linkedin.com/documents/code-samples) non-functional was that file_get_contents() was not working, and this was because allow_url_fopen was not enabled in PHP.ini. I believe allow_url_fopen is not enabled by default, as it is a security issue. I found a work-around online use cUrl. See the code below.
//First, in getAccessToken() replace:
$response = file_get_contents($url, false, $context)
with
$response = curl_get_contents($url);
And here is the code added to the LinkedIn code sample, after the
'print "Hello $user->firstName $user->lastName.";'
// temporary message content for test purposes
$xml_txt = "<?xml version='1.0' encoding='UTF-8'?>
<share>
<visibility>
<code>anyone</code>
</visibility>
<comment>There are a lot of great career opportunities here!</comment>
</share>";
//Post the message
$result = PostUpdate($xml_txt);
//Done
exit;
function PostUpdate($message) {
print 'here in PostUpdate <br />';
print '$message = ' . $message .' <br />';
$url = 'https://api.linkedin.com/v1/companies/'. COMPANY_ID . '/shares';
// build your message
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $message );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/xml', 'Authorization: Bearer ' . $_SESSION['access_token']));
$response = curl_exec($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
print_r($response);
echo '$http_status = '. $http_status;
}
function curl_get_contents($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
Maybe it aint pretty, but after a couple of days struggling with it, I feel surprisingly elated. And thank you LinkedIn for providing a lets-all-reinvent the-wheel code sample with a built-in "issue". If you folks wipe your tail-ends the same half-arsed way you provide code samples, yer walking around with three inches of dried skidmarks in yer undies. Crusty, you know whut I'm sayin.

Rcurl not working with redirect [duplicate]

I'm using curl to fill a form. After completion of the post the other script which handles the form is redirecting to another URL. I want to get this redirect URL into a variable.
Easy way to find the redirected url (if you don't want to know in advance)
$last_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
You would use
curl_setopt($CURL, CURLOPT_HEADER, TRUE);
And parse the headers for the location header
Here I get the resource http headers then I parse the headers out into an array $retVal. I got the code for parsing the headers from here (http://www.bhootnath.in/blog/2010/10/parse-http-headers-in-php/) You could also use http://php.net/manual/en/function.http-parse-headers.php if you have (PECL pecl_http >= 0.10.0)
$ch = curl_init();
$timeout = 0;
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
// Getting binary data
$header = curl_exec($ch);
$retVal = array();
$fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header));
foreach( $fields as $field ) {
if( preg_match('/([^:]+): (.+)/m', $field, $match) ) {
$match[1] = preg_replace('/(?<=^|[\x09\x20\x2D])./e', 'strtoupper("\0")', strtolower(trim($match[1])));
if( isset($retVal[$match[1]]) ) {
$retVal[$match[1]] = array($retVal[$match[1]], $match[2]);
} else {
$retVal[$match[1]] = trim($match[2]);
}
}
}
//here is the header info parsed out
echo '<pre>';
print_r($retVal);
echo '</pre>';
//here is the redirect
if (isset($retVal['Location'])){
echo $retVal['Location'];
} else {
//keep in mind that if it is a direct link to the image the location header will be missing
echo $_GET[$urlKey];
}
curl_close($ch);
You may want to set the CURLOPT_FOLLOWLOCATION to true.
Or set the CURLOPT_HEADER to true and then use regexp to get the Location header.

Resources