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
So I'm having troubles learning how to set up a login through discord on my site. I've been browsing for literally hours and haven't been able to find anything I understand...
At the moment, I have created the discord application, giving me a client ID and client secret, as well as a link back to my localhost:
https://discordapp.com/api/oauth2/authorize?client_id=550631359337594881&redirect_uri=http%3A%2F%2Flocalhost&response_type=code&scope=identify
At the moment I have it set up to redirect from a button to that URL, which then sends me to discord to accept. It then returns me to http://localhost?code=CODE_HERE
However, I don't know what I am supposed to do with this code. I am trying to set it up so that it will show the person's username with hashtag thing, and their profile picture.
I am currently using HTML, CSS, JS, and PHP on the site, but I think I might need to use something else, but I don't know how to set that up, or what it is I need. I am running my local server with XAMPP. I'd prefer if it is just PHP, but I'm open to other options.
Does anyone know how I can convert the code to a username + image?
Thanks in advance!
Try this
Credits to: eslachance
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('max_execution_time', 300); //300 seconds = 5 minutes. In case if your CURL is slow and is loading too much (Can be IPv6 problem)
error_reporting(E_ALL);
define('OAUTH2_CLIENT_ID', '1234567890'); //Your client Id
define('OAUTH2_CLIENT_SECRET', 'verysecretclientcode'); //Your secret client code
$authorizeURL = 'https://discordapp.com/api/oauth2/authorize';
$tokenURL = 'https://discordapp.com/api/oauth2/token';
$apiURLBase = 'https://discordapp.com/api/users/#me';
session_start();
// Start the login process by sending the user to Discord's authorization page
if(get('action') == 'login') {
$params = array(
'client_id' => OAUTH2_CLIENT_ID,
'redirect_uri' => 'https://yoursite.location/ifyouneedit',
'response_type' => 'code',
'scope' => 'identify guilds'
);
// Redirect the user to Discord's authorization page
header('Location: https://discordapp.com/api/oauth2/authorize' . '?' . http_build_query($params));
die();
}
// When Discord redirects the user back here, there will be a "code" and "state" parameter in the query string
if(get('code')) {
// Exchange the auth code for a token
$token = apiRequest($tokenURL, array(
"grant_type" => "authorization_code",
'client_id' => OAUTH2_CLIENT_ID,
'client_secret' => OAUTH2_CLIENT_SECRET,
'redirect_uri' => 'https://yoursite.location/ifyouneedit',
'code' => get('code')
));
$logout_token = $token->access_token;
$_SESSION['access_token'] = $token->access_token;
header('Location: ' . $_SERVER['PHP_SELF']);
}
if(session('access_token')) {
$user = apiRequest($apiURLBase);
echo '<h3>Logged In</h3>';
echo '<h4>Welcome, ' . $user->username . '</h4>';
echo '<pre>';
print_r($user);
echo '</pre>';
} else {
echo '<h3>Not logged in</h3>';
echo '<p>Log In</p>';
}
if(get('action') == 'logout') {
// This must to logout you, but it didn't worked(
$params = array(
'access_token' => $logout_token
);
// Redirect the user to Discord's revoke page
header('Location: https://discordapp.com/api/oauth2/token/revoke' . '?' . http_build_query($params));
die();
}
function apiRequest($url, $post=FALSE, $headers=array()) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);
if($post)
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$headers[] = 'Accept: application/json';
if(session('access_token'))
$headers[] = 'Authorization: Bearer ' . session('access_token');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
return json_decode($response);
}
function get($key, $default=NULL) {
return array_key_exists($key, $_GET) ? $_GET[$key] : $default;
}
function session($key, $default=NULL) {
return array_key_exists($key, $_SESSION) ? $_SESSION[$key] : $default;
}
?>
You have the code which is used to authenticate with many endpoints of the discord API. You need the http://discordapp.com/api/users/#me Endpoint. You authenticate with the Authorization Header. Take a look at the Developer Portal to find out more about your endpoint
with this simple code I manage to get Google's access tokens.
See the code:
public function authenticate($code = null) {
if (!$code) {
if ($this->log)
error_log(__CLASS__ . '::authenticate() error: $code is null.');
return false;
}
$client_id = $this->token->get('client_id');
$client_secret = $this->token->get('client_secret');
$redirect_uri = $this->token->get('redirect_uri');
$url = $this->token->get('token_endpoint');
$curlPost = 'client_id=' . $client_id . '&client_secret=' . $client_secret . '&redirect_uri=' . $redirect_uri . '&code='. $code . '&grant_type=authorization_code';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
$buffer = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$data = \json_decode($buffer, true);
if ($http_code != 200) {
$log = __CLASS__ . '::authenticate() error: http code not 200. Responded: '.print_r($data, true);
$return = false;
} else {
$this->auth = $data;
$return = true;
$log = __CLASS__ . '::authenticate() returns '.$return.' and sets this->auth='.print_r($data, true);
}
if ($this->log)
error_log($log);
return $return;
}
you can see my project there with a test file.
My question is about the verify() function.
When I want to verify Google's access token by typing in the browser sth like https://www.googleapis.com/oauth2/v2/tokeninfo?access_token=.... I get immediately a response from Google but when I try the following function with cURL it fails miserably:
public function verify($access_token = null) {
if (!$access_token) {
if ($this->log)
error_log(__CLASS__ . '::verify() error: $access_token is null.');
return false;
}
$url = $this->token->get('verify_endpoint');
$curlPost = 'access_token='. $access_token;
//$curlPost = \http_build_query(array('access_token' => $access_token));
//$curlPost = array('access_token' => $access_token);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url.'?'.$curlPost);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
//curl_setopt($ch, CURLOPT_VERBOSE, true);
$buffer = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$data = \json_decode($buffer, true);
if ($http_code != 200) {
$log = __CLASS__ . '::verify() error: http code not 200. Responded: '.print_r($data, true);
$return = false;
} else {
$this->verify = $data;
$log = __CLASS__ . '::verify() sets this->verify='.print_r($data, true);
$return = true;
}
if ($this->log)
error_log($log);
return $return;
}
Has this sth to do with cURL? Any answer is welcomed.
Just to clarify: browser request https://www.googleapis.com/oauth2/v2/tokeninfo?access_token=... or with ?id_token=... always succeeds BUT not cURL with the proper tokens in the query part of course.
From your source code here
$this->set('verify_endpoint', 'https://www.googleapis.com/oauth2/v2/tokeninfo');
is calling googles token info end point documentation is used for validating an id token you appear to be passing it an access token. This is not going to work.
TBH i dont understand why you would bother validating an access token. The best way to test if an access token is working is to make the call to the API in question if it doesnt work you will get an error back. Why would you want to make a call to test if it works then use it if it does work your doubling your requests.
Problems solved!
After a 2 month searching at last there is an update version of my project wirh cUrl problems solved immediately after started to investigate errors sent by the curl environment.
The browser success ringed a bell that probably there was a DNS issue as these threads repeatedly showcase this:
https://curl.haxx.se/mail/curlphp-2016-10/0000.html
https://forums.rancher.com/t/dns-caching-issues/1566/8 #vincent
https://github.com/GoogleCloudPlatform/google-cloud-php/issues/405
https://github.com/google/google-api-php-client/issues/1184
This discussion from #sanmai about CURLOPT_RESOLVE actually made it working! Also see php manual; The same is proposed here by Luc van Donkersgoed and there by John Hart.
The tricky parts of response headers on GET requests that contain Google's response are discussed here and in other places.
Curl certificates are downloaded from there.
A discussion for certificates is there.
A discussion for debugging cUrl here and there.
For a discussion of Expect header and it's implications you can read this and that.
Now cUrl is lightning fast when it connects to google. See my project.
My deepest gratitude to all the users who patiently and kindly support the community. You guys are awesome! many thanks!
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.
I am trying to figure out how to POST a like for Instagram. Click here to view my website for testing this API.
http://ewands.no-ip.biz/Intern/guangjian/instagram/
This is my first time trying the Instagram API. Google it but no tutorial is found on this topic. Below are my PHP code.
Getting the media id:
$api = file_get_contents("http://api.instagram.com/oembed?url=http://instagram.com/p/n5DyHnKWoo");
$apiObj = json_decode($api,true);
$media_id = $apiObj['media_id'];
After the like button is clicked, the URL becomes http://ewands.no-ip.biz/Intern/guangjian/instagram?api=like, so from PHP we run the code below:
if($_GET['api'] == 'like'){
header('location:https://api.instagram.com/oauth/authorize/?client_id=3548d38f15b54dbfb744bf0705fa8198&redirect_uri=http://ewands.no-ip.biz/intern/guangjian/instagram?function=like&response_type=code');
The above will redirect the page to http://ewands.no-ip.biz/intern/guangjian/instagram/?function=like&code=3b50fdbcd0184f979b31f5b0d12354c4 <-- Instagram server added a random code, next, use curl to get the access token:
}
if($_GET['function'] == 'like') {
$code = $_GET['code'];
$url = "https://api.instagram.com/oauth/access_token";
$access_token_parameters = array(
'client_id' => '3548d38f15b54dbfb744bf0705fa8198',
'client_secret' => '97e12a30416d4436a52107d0d1820e91',
'grant_type' => 'authorization_code',
'redirect_uri' => 'http://ewands.no-ip.biz/intern/guangjian/instagram?function=like',
'code' => $code
);
$curl = curl_init($url);
curl_setopt($curl,CURLOPT_POST,true);
curl_setopt($curl,CURLOPT_POSTFIELDS,$access_token_parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($curl);
curl_close($curl);
$arr = json_decode($result,true);
$token = $arr['access_token'];
I have tested that I am able to get the token, so far so good, then the next part does not work, I am just trying my luck, since I am not familiar with curl and there are no tutorial out there from Googling for Instagram API tutorial.
$url = 'https://api.instagram.com/v1/media/'.$media_id.'/likes';
$curl = curl_init($url);
curl_setopt($curl,CURLOPT_POST,true);
curl_setopt($curl,CURLOPT_POSTFIELDS,'access_token='.$token);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($curl);
}
Instagram returns a # in the token return which renders it useless for $_GET.
The token is only supposed to be used one.
You manually copy it from the URI and then use it accordingly in your code.
It is HIGHLY insecure.
You're over thinking it.