When using install_ssl of the cPanel UAPI, I am experiencing "The certificate text was not valid." - ssl

I am using the cPanel UAPI to call the install_ssl function. I have followed the tutorial [here][1]: https://documentation.cpanel.net/display/SDK/Tutorial+-+Call+UAPI%27s+SSL%3A%3Ainstall_ssl+Function+in+Custom+Code#4ba262da2a5b4308828c17a2156d5dc9
However, I am getting a parse error when it is attempting to read the certificate. I have copied the certificate from my cPanel SSL Manage UI and placed it in a file. I know that this file is being read correctly. However, I get the following error when it is sent via the API.
"The system could not parse the certificate because of an error: The certificate text was not valid."
I have tried url encoding the certificate and key, which did nothing. Here is the code I used. (I am doing this in Drupal, hence the use of dpm)
function _bh_site_configure_multi_add_ssl($fulldomain) {
// Declare your username and password for authentication.
$username = "myusername";
$password = "mypassword";
// Define the API call.
$cpanel_host = "myserver";
$request_uri = "https://$cpanel_host:2083/execute/SSL/install_ssl";
// Define the SSL certificate and key files.
$cert_file = realpath("/path/to/file/cert.crt");
$key_file = realpath("/path/to/file/key.key");
// Set up the payload to send to the server.
$payload = array(
'domain' => $fulldomain,
'cert' => file_get_contents($cert_file),
'key' => file_get_contents($key_file)
);
// Set up the cURL request object.
$ch = curl_init( $request_uri );
curl_setopt( $ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC );
curl_setopt( $ch, CURLOPT_USERPWD, $username . ':' . $password );
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
// Set up a POST request with the payload.
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
// Make the call, and then terminate the cURL caller object.
$curl_response = curl_exec( $ch );
curl_close( $ch );
// Decode and validate output.
$response = json_decode( $curl_response );
if( empty( $response ) ) {
dpm("The cURL call did not return valid JSON:\n");
} elseif ( !$response->status ) {
dpm("The cURL call returned valid JSON, but reported errors:\n");
dpm($response->errors[0] . "\n") ;
}
dpm ($response);

I found out that my particular cert needed to have the cabundle. When I went back to the installation instructions for my cert that I got from the Certificate Authority, it included a cabundle. After I included that, it worked.

Related

to push notifications using java or python [duplicate]

I'm starting with the new Google service for the notifications, Firebase Cloud Messaging.
Thanks to this code https://github.com/firebase/quickstart-android/tree/master/messaging I was able to send notifications from my Firebase User Console to my Android device.
Is there any API or way to send a notification without use the Firebase console? I mean, for example, a PHP API or something like that, to create notifications from my own server directly.
Firebase Cloud Messaging has a server-side APIs that you can call to send messages. See https://firebase.google.com/docs/cloud-messaging/server.
Sending a message can be as simple as using curl to call a HTTP end-point. See https://firebase.google.com/docs/cloud-messaging/server#implementing-http-connection-server-protocol
curl -X POST --header "Authorization: key=<API_ACCESS_KEY>" \
--Header "Content-Type: application/json" \
https://fcm.googleapis.com/fcm/send \
-d "{\"to\":\"<YOUR_DEVICE_ID_TOKEN>\",\"notification\":{\"title\":\"Hello\",\"body\":\"Yellow\"}}"
You can all this REST API from within any environment, but there are dedicated so-called Admin SDKs for many platforms listed here.
This works using CURL
function sendGCM($message, $id) {
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array (
'registration_ids' => array (
$id
),
'data' => array (
"message" => $message
)
);
$fields = json_encode ( $fields );
$headers = array (
'Authorization: key=' . "YOUR_KEY_HERE",
'Content-Type: application/json'
);
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );
$result = curl_exec ( $ch );
echo $result;
curl_close ( $ch );
}
?>
$message is your message to send to the device
$id is the devices registration token
YOUR_KEY_HERE is your Server API Key (or Legacy Server API Key)
Use a service api.
URL: https://fcm.googleapis.com/fcm/send
Method Type: POST
Headers:
Content-Type: application/json
Authorization: key=your api key
Body/Payload:
{
"notification": {
"title": "Your Title",
"text": "Your Text",
"click_action": "OPEN_ACTIVITY_1"
},
"data": {
"<some_key>": "<some_value>"
},
"to": "<device_token>"
}
And with this in your app you can add below code in your activity to be called:
<intent-filter>
<action android:name="OPEN_ACTIVITY_1" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
Also check the answer on Firebase onMessageReceived not called when app in background
Examples using curl
Send messages to specific devices
To send messages to specific devices, set the to the registration token for the specific app instance
curl -H "Content-type: application/json" -H "Authorization:key=<Your Api key>" -X POST -d '{ "data": { "score": "5x1","time": "15:10"},"to" : "<registration token>"}' https://fcm.googleapis.com/fcm/send
Send messages to topics
here the topic is : /topics/foo-bar
curl -H "Content-type: application/json" -H "Authorization:key=<Your Api key>" -X POST -d '{ "to": "/topics/foo-bar","data": { "message": "This is a Firebase Cloud Messaging Topic Message!"}}' https://fcm.googleapis.com/fcm/send
Send messages to device groups
Sending messages to a device group is very similar to sending messages to an individual device. Set the to parameter to the unique notification key for the device group
curl -H "Content-type: application/json" -H "Authorization:key=<Your Api key>" -X POST -d '{"to": "<aUniqueKey>","data": {"hello": "This is a Firebase Cloud Messaging Device Group Message!"}}' https://fcm.googleapis.com/fcm/send
Examples using Service API
API URL : https://fcm.googleapis.com/fcm/send
Headers
Content-type: application/json
Authorization:key=<Your Api key>
Request Method : POST
Request Body
Messages to specific devices
{
"data": {
"score": "5x1",
"time": "15:10"
},
"to": "<registration token>"
}
Messages to topics
{
"to": "/topics/foo-bar",
"data": {
"message": "This is a Firebase Cloud Messaging Topic Message!"
}
}
Messages to device groups
{
"to": "<aUniqueKey>",
"data": {
"hello": "This is a Firebase Cloud Messaging Device Group Message!"
}
}
As mentioned by Frank, you can use Firebase Cloud Messaging (FCM) HTTP API to trigger push notification from your own back-end. But you won't be able to
send notifications to a Firebase User Identifier (UID) and
send notifications to user segments (targeting properties & events like you can on the user console).
Meaning: you'll have to store FCM/GCM registration ids (push tokens) yourself or use FCM topics to subscribe users. Keep also in mind that FCM is not an API for Firebase Notifications, it's a lower-level API without scheduling or open-rate analytics. Firebase Notifications is build on top on FCM.
Introduction
I compiled most of the answers above and updated the variables based on the FCM HTTP Connection Docs to curate a solution that works with FCM in 2021. Credit to Hamzah Malik for his very insightful answer above.
Prerequisites
First, ensure that you have connected your project with Firebase and that you have set up all dependencies on your app. If you haven't, first head over to the FCM Config docs
If that is done, you will also need to copy your project's server response key from the API. Head over to your Firebase Console, click on the project you're working on and then navigate to;
Project Settings(Setting wheel on upper left corner) -> Cloud Messaging Tab -> Copy the Server key
Configuring your PHP Backend
I compiled Hamzah's answer with Ankit Adlakha's API call structure and the FCM Docs to come up with the PHP function below:
function sendGCM() {
// FCM API Url
$url = 'https://fcm.googleapis.com/fcm/send';
// Put your Server Response Key here
$apiKey = "YOUR SERVER RESPONSE KEY HERE";
// Compile headers in one variable
$headers = array (
'Authorization:key=' . $apiKey,
'Content-Type:application/json'
);
// Add notification content to a variable for easy reference
$notifData = [
'title' => "Test Title",
'body' => "Test notification body",
'click_action' => "android.intent.action.MAIN"
];
// Create the api body
$apiBody = [
'notification' => $notifData,
'data' => $notifData,
"time_to_live" => "600" // Optional
'to' => '/topics/mytargettopic' // Replace 'mytargettopic' with your intended notification audience
];
// Initialize curl with the prepared headers and body
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url );
curl_setopt ($ch, CURLOPT_POST, true );
curl_setopt ($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ($ch, CURLOPT_POSTFIELDS, json_encode($apiBody));
// Execute call and save result
$result = curl_exec ( $ch );
// Close curl after call
curl_close ( $ch );
return $result;
}
Customizing your notification push
To submit the notifications via tokens, use 'to' => 'registration token'
What to expect
I set up the function in my website back-end and tested it on Postman. If your configuration was successful, you should expect a response similar to the one below;
{"message":"{"message_id":3061657653031348530}"}
this solution from this link helped me a lot. you can check it out.
The curl.php file with those line of instruction can work.
<?php
// Server key from Firebase Console define( 'API_ACCESS_KEY', 'AAAA----FE6F' );
$data = array("to" => "cNf2---6Vs9", "notification" => array( "title" => "Shareurcodes.com", "body" => "A Code Sharing Blog!","icon" => "icon.png", "click_action" => "http://shareurcodes.com"));
$data_string = json_encode($data);
echo "The Json Data : ".$data_string;
$headers = array ( 'Authorization: key=' . API_ACCESS_KEY, 'Content-Type: application/json' );
$ch = curl_init(); curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_POSTFIELDS, $data_string);
$result = curl_exec($ch);
curl_close ($ch);
echo "<p> </p>";
echo "The Result : ".$result;
Remember you need to execute curl.php file using another browser ie not from the browser that is used to get the user token. You can see notification only if you are browsing another website.
First you need to get a token from android and then you can call this php code and you can even send data for further actions in your app.
<?php
// Call .php?Action=M&t=title&m=message&r=token
$action=$_GET["Action"];
switch ($action) {
Case "M":
$r=$_GET["r"];
$t=$_GET["t"];
$m=$_GET["m"];
$j=json_decode(notify($r, $t, $m));
$succ=0;
$fail=0;
$succ=$j->{'success'};
$fail=$j->{'failure'};
print "Success: " . $succ . "<br>";
print "Fail : " . $fail . "<br>";
break;
default:
print json_encode ("Error: Function not defined ->" . $action);
}
function notify ($r, $t, $m)
{
// API access key from Google API's Console
if (!defined('API_ACCESS_KEY')) define( 'API_ACCESS_KEY', 'Insert here' );
$tokenarray = array($r);
// prep the bundle
$msg = array
(
'title' => $t,
'message' => $m,
'MyKey1' => 'MyData1',
'MyKey2' => 'MyData2',
);
$fields = array
(
'registration_ids' => $tokenarray,
'data' => $msg
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'fcm.googleapis.com/fcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
return $result;
}
?>
Works in 2020
$response = Http::withHeaders([
'Content-Type' => 'application/json',
'Authorization'=> 'key='. $token,
])->post($url, [
'notification' => [
'body' => $request->summary,
'title' => $request->title,
'image' => 'http://'.request()->getHttpHost().$path,
],
'priority'=> 'high',
'data' => [
'click_action'=> 'FLUTTER_NOTIFICATION_CLICK',
'status'=> 'done',
],
'to' => '/topics/all'
]);
Here is the working code in my project using CURL.
<?PHP
//Avoid keys confusions!
//firebase Cloud Messaging have 3 different keys:
//API_KEY, SERVER_KEY and PUSH_KEY ... here we need SERVER_KEY
// SERVER access key from Google firebase Console
define( 'SERVER_ACCESS_KEY', 'YOUR-SERVER-ACCESS-KEY-GOES-HERE' );
$registrationIds = array( $_GET['id'] );
// prep the bundle
$msg = array
(
'message' => 'here is a message. message',
'title' => 'This is a title. title',
'subtitle' => 'This is a subtitle. subtitle',
'tickerText' => 'Ticker text here...Ticker text here...Ticker text here',
'vibrate' => 1,
'sound' => 1,
'largeIcon' => 'large_icon',
'smallIcon' => 'small_icon'
);
$fields = array
(
// use this to method if want to send to topics
// 'to' => 'topics/all'
'registration_ids' => $registrationIds,
'notification' => $msg
);
$headers = array
(
'Authorization: key=' . SERVER_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
echo $result;
You can use for example a PHP script for Google Cloud Messaging (GCM). Firebase, and its console, is just on top of GCM.
I found this one on github:
https://gist.github.com/prime31/5675017
Hint: This PHP script results in a android notification.
Therefore: Read this answer from Koot if you want to receive and show the notification in Android.
Notification or data message can be sent to firebase base cloud messaging server using FCM HTTP v1 API endpoint.
https://fcm.googleapis.com/v1/projects/zoftino-stores/messages:send.
You need to generate and download private key of service account using Firebase console and generate access key using google api client library. Use any http library to post message to above end point, below code shows posting message using OkHTTP. You can find complete server side and client side code at firebase cloud messaging and sending messages to multiple clients using fcm topic example
If a specific client message needs to sent, you need to get firebase registration key of the client, see sending client or device specific messages to FCM server example
String SCOPE = "https://www.googleapis.com/auth/firebase.messaging";
String FCM_ENDPOINT
= "https://fcm.googleapis.com/v1/projects/zoftino-stores/messages:send";
GoogleCredential googleCredential = GoogleCredential
.fromStream(new FileInputStream("firebase-private-key.json"))
.createScoped(Arrays.asList(SCOPE));
googleCredential.refreshToken();
String token = googleCredential.getAccessToken();
final MediaType mediaType = MediaType.parse("application/json");
OkHttpClient httpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(FCM_ENDPOINT)
.addHeader("Content-Type", "application/json; UTF-8")
.addHeader("Authorization", "Bearer " + token)
.post(RequestBody.create(mediaType, jsonMessage))
.build();
Response response = httpClient.newCall(request).execute();
if (response.isSuccessful()) {
log.info("Message sent to FCM server");
}
Go to cloud Messaging select: Server key
function sendGCM($message, $deviceToken) {
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array (
'registration_ids' => array (
$id
),
'data' => array (
"title" => "Notification title",
"body" => $message,
)
);
$fields = json_encode ( $fields );
$headers = array (
'Authorization: key=' . "YOUR_SERVER_KEY",
'Content-Type: application/json'
);
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );
$result = curl_exec ( $ch );
echo $result;
curl_close ($ch);
}
Or you can use Firebase cloud functions, which is for me the easier way to implement your push notifications.
firebase/functions-samples
If you're using PHP, I recommend using the PHP SDK for Firebase: Firebase Admin SDK. For an easy configuration you can follow these steps:
Get the project credentials json file from Firebase (Initialize the sdk) and include it in your project.
Install the SDK in your project. I use composer:
composer require kreait/firebase-php ^4.35
Try any example from the Cloud Messaging session in the SDK documentation:
use Kreait\Firebase;
use Kreait\Firebase\Messaging\CloudMessage;
$messaging = (new Firebase\Factory())
->withServiceAccount('/path/to/firebase_credentials.json')
->createMessaging();
$message = CloudMessage::withTarget(/* see sections below */)
->withNotification(Notification::create('Title', 'Body'))
->withData(['key' => 'value']);
$messaging->send($message);
If you want to send push notifications from android check out my blog post
Send Push Notifications from 1 android phone to another with out server.
sending push notification is nothing but a post request to https://fcm.googleapis.com/fcm/send
code snippet using volley:
JSONObject json = new JSONObject();
try {
JSONObject userData=new JSONObject();
userData.put("title","your title");
userData.put("body","your body");
json.put("data",userData);
json.put("to", receiverFirebaseToken);
}
catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("https://fcm.googleapis.com/fcm/send", json, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i("onResponse", "" + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorizationey=" + SERVER_API_KEY);
params.put("Content-Typepplication/json");
return params;
}
};
MySingleton.getInstance(context).addToRequestQueue(jsonObjectRequest);
I suggest you all to check out my blog post for complete details.
Using Firebase Console you can send message to all users based on application package.But with CURL or PHP API its not possible.
Through API You can send notification to specific device ID or subscribed users to selected topic or subscribed topic users.
Get a view on following link. It will help you.
https://firebase.google.com/docs/cloud-messaging/send-message

cURL post with PHP failing

Using Postman, I have been able to successfully create an API call to retrieve information from the webserver.
However, I have been unsuccessful in doing the same with PHP. Following are a few screenshots from Postman which I am trying to replicate in PHP.
This is my PHP code -
$filters = array("1234", "28");
$selectors = array("Brand", "Name");
$body = array('Filter' => array('SKU'=>$filters, 'OutputSelector' => $selectors));
$url = "https://xyz.neto.com.au/do/WS/NetoAPI";
$method = "POST";
$headers = array(
"NETOAPI_ACTION: GetItem",
"NETOAPI_KEY: xxxxxxx",
"Accept: application/json",
"NETOAPI_USERNAME: puneeth"
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
P.S I have deliberately fudged the url and key.
I am trying to follow instructions as outlined here - https://developers.neto.com.au/documentation/engineers/api-documentation/products/getitem
Few things that might be preventing your code from working:
1. Array to string conversion
You have declared the body of the request as an array in $body. You need to JSON-encode it before passing it to cURL:
$body = array('Filter' => array('SKU'=>$filters, 'OutputSelector' => $selectors));
$bodyJSON = json_encode($body);
[...]
curl_setopt($ch, CURLOPT_POSTFIELDS, $bodyJSON);
2. HTTPS request
If you're getting an empty response, you'll also need to configure cURL for SSL communication. A quick fix for this is to ignore the remote server certificate validity:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
Although this works, see this answer for a better solution.
3. Missing Content-Type
When sending raw postfields, some servers need to know what type of data you're sending. This is done by setting a Content-Type header:
$headers = array(
"Content-Type: application/json",
[...]
);

Warning: DOMDocument::load(): Peer certificate CN, Failed to enable crypto, I/O warning, failed to open stream,

In Wordpress php5, everything is fine
now with PHP7 I am getting these warnings:
Warning: DOMDocument::load(): Peer certificate CN=getalongwithgod.com' did not match expected CN=www.readmk.com' in /home/readmk11/staging/1/wp-content/themes/Shulamite/includes/readmk-feed.php on line 21
Warning: DOMDocument::load(): Failed to enable crypto in /home/readmk11/staging/1/wp-content/themes/Shulamite/includes/readmk-feed.php on line 21
Warning: DOMDocument::load(https://www.readmk.com/devotionals/feed): failed to open stream: operation failed in /home/readmk11/staging/1/wp-content/themes/Shulamite/includes/readmk-feed.php on line 21
Warning: DOMDocument::load(): I/O warning : failed to load external entity "https://www.readmk.com/devotionals/feed" in /home/readmk11/staging/1/wp-content/themes/Shulamite/includes/readmk-feed.php on line 21
my class-wp-http-streams.php
says this:
$context = stream_context_create( array(
'ssl' => array(
'verify_peer' => $ssl_verify,
//'CN_match' => $arrURL['host'], // This is handled by self::verify_ssl_certificate()
'capture_peer_cert' => $ssl_verify,
'SNI_enabled' => true,
'cafile' => $r['sslcertificates'],
'allow_self_signed' => ! $ssl_verify,
)
) );
ALSO, my class-wp-http-curl.php
says this:
/*
* CURLOPT_TIMEOUT and CURLOPT_CONNECTTIMEOUT expect integers. Have to use ceil since.
* a value of 0 will allow an unlimited timeout.
*/
$timeout = (int) ceil( $r['timeout'] );
curl_setopt( $handle, CURLOPT_CONNECTTIMEOUT, $timeout );
curl_setopt( $handle, CURLOPT_TIMEOUT, $timeout );
curl_setopt( $handle, CURLOPT_URL, $url);
curl_setopt( $handle, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $handle, CURLOPT_SSL_VERIFYHOST, ( $ssl_verify === true ) ? 2 : false );
curl_setopt( $handle, CURLOPT_SSL_VERIFYPEER, $ssl_verify );
if ( $ssl_verify ) {
curl_setopt( $handle, CURLOPT_CAINFO, $r['sslcertificates'] );
}
curl_setopt( $handle, CURLOPT_USERAGENT, $r['user-agent'] );
I am getting four errors on the site where I think these codes are affecting:
Does anyone know what needs to be changed to my code to make these Warnings go away and the site grab information again in PHP7?

Twilio cURL result in Authentication Error - No credentials provided

I'm struggling with sending a msg from your twilio api, I tested your demos that exists on the twilio website on my local server with the following features:
host : (i686-pc-linux-gnu)
libcurl php version: 7.35.0
ssl version: OpenSSL/1.0.1f.
It works my local server but on this server with the following features :
host : x86_64-redhat-linux-gnu
libcurl php version : 7.19.7
ssl version: NSS/3.19.1 Basic ECC
it didn't work.
Here's the output of the curl request to the twilio api:
{"code": 20003, "detail": "Your AccountSid or AuthToken was incorrect.", "message": "Authentication Error - No credentials provided", "more_info": "https://www.twilio.com/docs/errors/20003", "status": 401}1
the code:
<?php
//my trial account sid, and token
$sid = "XXXXXXXXXXXX"; // Your Account SID from www.twilio.com/user/account
$token = "XXXXXXXXXXXXX"; // Your Auth Token from www.twilio.com/user/account
function send_sms( $sid, $token, $to, $from, $body ) {
// resource url & authentication
$uri = 'https://api.twilio.com/2010-04-01/Accounts/' . $sid . '/SMS/Messages.json';
$auth = $sid . ':' . $token;
// post string (phone number format= +15554443333 ), case matters
$fields =
'&To=' . urlencode( $to ) .
'&From=' . urlencode( $from ) .
'&Body=' . urlencode( $body );
// start cURL
$res = curl_init($uri);
// set cURL options
curl_setopt( $res, CURLOPT_POST, TRUE );
curl_setopt( $res, CURLOPT_RETURNTRANSFER, TRUE ); // don't echo
curl_setopt( $res, CURLOPT_SSL_VERIFYPEER, FALSE );
curl_setopt( $res, CURLOPT_HTTPAUTH, CURLAUTH_BASIC );
curl_setopt( $res, CURLOPT_USERPWD, $auth ); // authenticate
curl_setopt( $res, CURLOPT_POSTFIELDS, $fields );
// send cURL
$result = curl_exec( $res );
curl_close($res);
return $result;
}
echo send_sms($sid,$token,"+XXXXXXXX","+XXXXXXXXXXXXXX","TESTING");
?>
I hope you know what is the problem but I think it's related to the ssl version, that included with the php curl extention on the server.
PS: I have no access to the second server so that I cannot upgrade the libcurl extention to the latest version, which I think the reason of the problem.
The & separates fields in the POST-DATA, so you do not want the initial one.
Change:
$fields =
'&To=' . urlencode( $to ) .
to:
$fields =
'To=' . urlencode( $to ) .
[EDIT]
One additional difference I see between what you are doing at what I am doing, is I am including the sid and auth directly in the URL:
$uri = "https://" . $sid . ":" + $auth . "#api.twilio.com/2010...";
rather than using:
curl_setopt( $res, CURLOPT_HTTPAUTH, CURLAUTH_BASIC );
curl_setopt( $res, CURLOPT_USERPWD, $auth );
but I don't know if that is important or not.

Unable to upload a file to foldergrid using API

Trying to use folder grid api to upload a file. There are 2 steps.
Calling provision a file to get a location with a guid.
Uploading the actual file using a PUT.
I am able to do the first call and get a location of the type https://files.foldergrid.com/upload/xxx. I then try to upload the file using this as my location and keep getting
< HTTP/1.1 100 Continue
* Empty reply from server
* Connection #0 to host files.foldergrid.com left intact
* Closing connection #0
from the server not sure what I am missing?
Here is the code I am using:
After calling the provision api I get back a url which I store in
$url = 'https://files.foldergrid.com/upload/xxx'
and I have the path to the file I want to upload in file
$file = 'some path to file'
then I have call the following method:
public function putFile($file,$url) {
$headers = array(
'fg-eap: false',
'fg-md5:'.md5_file($file),
);
$fh = fopen($file, "rb");
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_setopt($curl,CURLOPT_PUT,true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_INFILE, $fh);
curl_setopt($curl, CURLOPT_INFILESIZE, filesize($file));
curl_setopt( $curl, CURLOPT_VERBOSE, true );
$result = curl_exec($curl);
fclose($fg);
curl_close($curl);
return $result;
}
The code you've posted looks to have everything needed except the Content-Type header. Try setting your headers array as:
$headers = array(
'fg-eap: false',
'fg-md5:'.md5_file($file),
'Content-Type: binary/octet-stream'
);
Also, in response to your query here we've posted an updated PHP client sample under our API documentation here.