I'd like to shorten my URL's using the Firebase Dynamic Link shortener. I followed the Rest API reference and the code seems to check out:
const url ="https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=MY_API_KEY";
this.request = new XMLHttpRequest();
this.request.open("GET", url, true);
this.request.setRequestHeader("Content-Type", "application/json");
this.request.setRequestHeader("Access-Control-Allow-Origin", "*");
const parameters = {
"longDynamicLink": encodeURIComponent(window.location)
};
this.request.onreadystatechange = this.updateLink;
this.request.send(parameters);
But when I execute this code, I get a CORS error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at
https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=MY_API_KEY.
(Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
I can't seem to find a setting where I can enable Cross Origin Requests. Anyone who can tell me how to use Firebase Dynamic Links from the browser?
I solved this problem by just creating a PHP script that I can use to delegate the Firebase Rest call from client-side to server-side. This also ensures my users will never get to see my Firebase API key.
<?php
$LongDynamicLink = "MYHOST?" . urlencode($_GET["url"]);
$url = "https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=MY_API_KEY";
$data = '{
"dynamicLinkInfo": {
"dynamicLinkDomain": "MY_LINK_DOMAIN",
"link": "' . $LongDynamicLink . '",
"androidInfo": {
"androidPackageName": "ANDROID_PACKAGE_NAME"
},
"iosInfo": {
"iosBundleId": "IOS_BUNDLE_NAME"
}
}
}';
echo httpPost($url, $data);
function httpPost($url, $data)
{
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
?>
Using this code, you can call the PHP Rest API as such:
let request = new XMLHttpRequest();
request.open("GET", "MY_DOMAIN/?url=URL_I_WANT_TO_SHORTEN", true);
request.onreadystatechange = console.log(request.response);
request.send();
Related
Is there a way to verify that there is an email entered in a registration form (ultimate member) and when registering or writing the email, a function that makes a request to an API with the email and verifies that it exists, if it exists it lets you register but if it does not exist you can not register?
Thank you very much for your support.
use this filter to get a user email after auth:
add_filter('wp_authenticate_user','func_auth_signon',10,2);
function func_auth_signon($user, $password) {
if ( is_a( $user, 'WP_User' ) {
$email = $user->user_email;
//check if email exist in API
if(!is_email_exist($email))
//else logout user
wp_logout();
}
return $user;
}
Check if email of user exist in api
function is_email_exist($email){
$url = 'YOUR API URL'
$ch = curl_init($url);
// Set the result output to be a string.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
if(curl_error($ch)) {
return false;
}
curl_close($ch);
if($data) return true;
return false;
}
I've read a bunch of questions and tried a handful of different methods, so maybe my API service is just different. But this is my first time and I cant get it to work so I figured I'd post here and see if someone can educate me.
My code resulting in a response of error 400 - Bad request (API and other details changes for security)
Dim httpWebRequest = DirectCast(WebRequest.Create("https://api.smtp2go.com/v3/users/smtp/add"), HttpWebRequest)
httpWebRequest.ContentType = "application/json"
httpWebRequest.Method = "POST"
Using streamWriter = New StreamWriter(httpWebRequest.GetRequestStream())
Dim json As String = "{'api_key': ""api-123456123456123456123456"", 'username': ""user#domain.com"", 'description': ""Generated via API"" }"
streamWriter.Write(json)
streamWriter.Close()
End Using
Dim httpResponse = DirectCast(httpWebRequest.GetResponse(), HttpWebResponse)
Using streamReader = New StreamReader(httpResponse.GetResponseStream())
Dim result = streamReader.ReadToEnd()
End Using
Their example in JavaScript
var url = "https://api.smtp2go.com/v3/users/smtp/add";
$.ajax({
url: url,
method: 'POST',
headers: {
'Content-Type': "application/json"
},
data: JSON.stringify({
'api_key': "api-123456123456123456123456",
'username': "user#domain.com",
'description': "Generated via API"
}),
}).done(function(result) {
console.log(result);
}).fail(function(err) {
throw err;
});
Their example in PHP
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json"
));
curl_setopt($curl, CURLOPT_URL,
"https://api.smtp2go.com/v3/users/smtp/add"
);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode(array(
"api_key" => "api-123456123456123456123456",
"username" => "user#domain.com",
"description" => "Generated via API"
)));
$result = curl_exec($curl);
echo $result;
i want to make WordPress plugin or if already exists please tell me
i want if user post 15 post on my WordPress site publish post to his Facebook wall with images and level and more than posts with another level
login to WordPress throw Facebook
save the access token to use it to publish offline
on save posts if equal certain number publish the post to user
time line
i do first step and this images the result
but no thing published to timeline and the code is
<?php
session_start();
require_once 'facebook/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => 'xxxxxx',
'app_secret' => 'xxxxxxxxx',
'default_graph_version' => 'v2.5',
]);
$helper = $fb->getCanvasHelper();
$permissions = ['email', 'publish_actions']; // optional
try {
if (isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
} else {
$accessToken = $helper->getAccessToken();
}
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (isset($accessToken)) {
if (isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
} else {
$_SESSION['facebook_access_token'] = (string) $accessToken;
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// validating the access token
try {
$request = $fb->get('/me');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
if ($e->getCode() == 190) {
unset($_SESSION['facebook_access_token']);
$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl('https://apps.facebook.com/xxxxxxx/', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
exit;
}
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
// posting on user timeline using publish_actins permission
try {
// message must come from the user-end
$data = ['message' => 'testing...'];
$request = $fb->post('/me/feed', $data);
$response = $request->getGraphEdge()->asArray;
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
echo $response['id'];
// Now you can redirect to another page and use the
// access token from $_SESSION['facebook_access_token']
} else {
$helper = $fb->getRedirectLoginHelper();
//$loginUrl = $helper->getLoginUrl('https://apps.facebook.com/xxxxxxxx/', $permissions);
$loginUrl = $helper->getLoginUrl("http://www.xxxxxx.com/facebook/index.php",$permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
}
help :)
i used this tutorial to solve some steps
https://www.youtube.com/watch?v=XYawdJh_mNQ
So I define all parameters on the top of my page:
<?php
session_start();
$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$client->getAccessToken();
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
//get the access token
$myToken = json_decode($client->getAccessToken());
if ($client->getAuth()->isAccessTokenExpired()) {
$token = $myToken->refresh_token;
echo 'token expired';
} else {
$token = $myToken->access_token;
echo 'token not yet expired';
}
?>
Down at the bottom I got java script:
<script>
gapi.analytics.ready(function() {
var CLIENT_ID = 'my-client-id-goes-here';
gapi.analytics.auth.authorize({
'serverAuth': {
'access_token': '<?php echo $token; ?>'
}
});
This works however until access token expires, which is in 60 minutes. After that reports are not showing anymore. What did I do wrong and why it doesn't use a refresh token?
This is actually the expected behavior (unfortunately). The Embed API does not take a refresh token because generally you never want to expose those tokens publicly (which you would be doing if they were in your HTML source).
If you wanted to work around this limitation, you could set a timer on the page that updated the access token every 50 minutes or so (they expire after 60, as you pointed out).
If you had an endpoint on your server that returned a new access token, you could do something like this:
setInterval(function() {
makeRequestToGetNewAccessToken().then(function(access_token) {
gapi.auth.setToken({
access_token: access_token
});
});
}, 1000 * 60 * 50);
Note, the key above is calling setToken with the new access token. That will allow the Embed API to continue to work as normal.
Good day, everyone!
I have a problem with apprequests.
When i use Request Dialog, i have response with request id. Here is the code:
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<body>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<div id="fb-root"></div>
<script>
FB.init({appId:'400884386588720', xfbml:true, cookie:true});
var too = new Array('100003484704320');
function send() {
FB.ui({
method:'apprequests',
message:'http://wasm.ru',
to:too
}, function (response) {
var request = response.request;
var request_id = request + '_' + too[0];
console.log(request_id);
});
}
</script>
</body>
<input type="button" onclick="send(); return true;" value='Request'>
</html>
But user can't see this request! When facebook page refreshing, i can see notification, but after loading it disappears.
When i try use Graph Api, i have an error:
[error] => stdClass Object
(
[message] => (#200) All users in param ids must have accepted TOS
[type] => OAuthException
[code] => 200
)
Here is the code:
$token_url = "https://graph.facebook.com/oauth/access_token?" .
"client_id=" . $this->app_id.
"&client_secret=" . $this->secret .
"&grant_type=client_credentials";
$app_token = $this->request($token_url, 'POST');
$app_token = explode('=', $app_token);
$app_token = $app_token[1];
$message="Message with space and with link - http://wasm.ru";
$message = urlencode($message);
$url = 'https://graph.facebook.com/'.$user.'/apprequests?'.'message='.$message.'&access_token='.$app_token.'&method=post';
$res = $this->request($url, 'POST');
And the request function:
$ch = curl_init();
$options = array();
$options[CURLOPT_URL] = $url;
$options[CURLOPT_SSL_VERIFYPEER] = false;
$options[CURLOPT_RETURNTRANSFER] = true;
if($method == 'get') {
$options[CURLOPT_HTTPGET] = true;
} else {
$options[CURLOPT_CUSTOMREQUEST]= 'POST';
}
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
if($action == 'access_token'){
return $response;
}
$response = json_decode($response);
return $response;
I can't find error... Help!
Thanks.
The error message you receive ("All users in param ids must have accepted TOS") is because you are trying to send an app generated request to a user who is not connected to your app.
See the developer docs here https://developers.facebook.com/docs/requests/#app_to_user.
Requests sent with the request dialog and app generated requests are different and you can't use app generated requests to invite users to your app.