I'm building an application where users can click a button to show all of their Instagram images on a page, but in order to do that I need userId and accessToken. How do I get these?
NOTE: If it makes any difference: I'm not trying to get just my own images, but anyone who uses my app to log into their account.
I have this code:
<script>
var feed = new Instafeed ({
get: "user",
userId: ,
accessToken: ""
});
feed.run();
</script>
<div id="instafeed"></div>
And I get a verification code by clicking on a link (note I removed cliend_id and redirect_uri):
Get Instagram images
Then this returns a code like '1251251...' which I grab with GET, but after that what do I do? How do I get userId and accesToken from this?
I'm not sure if I'm on the right track, but any help would be appreciated!
Answering my own question, as I figured it out:
$url = 'https://api.instagram.com/oauth/access_token';
$data = array(
'client_id' => $clientId,
'client_secret' => $clientSecret,
'grant_type' => 'authorization_code',
'redirect_uri' => $redirectUri,
'code' => $code
);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$clientId, $clientSecret and $redirectUri are taken from: https://instagram.com/developer/clients/manage/
$code is the code from your url and $result contains the userId and accessToken if successful.
Thanks to: How do I send a POST request with PHP?
Related
I'm using Laravel 7. I got the code in uploading an image without the plugin but my problem now is adding an id (variable) passed together with the 3 variable defaults from CKeditor 4.
CKEditor=editor1&CKEditorFuncNum=1&langCode=en
These are the variables being passed in the "Query String Parameters":
_token: PcQGTkcFguEY4dJeguWsaNo (sample token)
CKEditor: pDescription
CKEditorFuncNum: 1
langCode: en
What I want to happen is to for the url to become like this with the "id" variable
Sample:
CKEditor=editor1&CKEditorFuncNum=1&langCode=en&id=1
These are the variables that I want to be passed in the "Query String Parameters":
with the "id" variable
_token: PcQGTkcFguEY4dJeguWsaNo (sample token)
CKEditor: pDescription
CKEditorFuncNum: 1
langCode: en
id:1
The id (variable) is the id of the product that the photo I want to associate with (foreign key).
How can I achieve this or any idea where should I start?
Here is my code:
Controller:
public function upload(Request $request)
{
if($request->hasFile('upload')) {
$originName = $request->file('upload')->getClientOriginalName();
$fileName = pathinfo($originName, PATHINFO_FILENAME);
$extension = $request->file('upload')->getClientOriginalExtension();
$fileName = $fileName.'_'.time().'.'.$extension;
$request->file('upload')->move(public_path('uploaded_productpictures'), $fileName);
$CKEditorFuncNum = $request->input('CKEditorFuncNum');
$url = asset('uploaded_productpictures/'.$fileName);
$msg = 'Image uploaded successfully';
$response = "<script>window.parent.CKEDITOR.tools.callFunction($CKEditorFuncNum, '$url', '$msg')</script>";
#header('Content-type: text/html; charset=utf-8');
echo $response;
// return response()->json([ 'fileName' => $filename, 'uploaded' => true, 'url' => $url, ]);
}
Here is code in javascript
<script src="{{ asset('ckeditor/ckeditor.js') }}"></script>
<script>
CKEDITOR.replace('pDescription', {
fileTools_requestHeaders: {
'X-CSRFToken': '{{ csrf_token() }}',
},
filebrowserUploadUrl: "{{route('save-ckeditorproductphoto', ['_token' => csrf_token() ])}}",
filebrowserUploadMethod: 'form'
});
</script>
And this is my route: I have tried this one but the id is not passing
Route::post('/products/save-ckeditorproductphoto', 'ProductphotosController#upload')->name('save-ckeditorproductphoto');
I don't know about the ckfinder but all I know is that when I use the upload name as the function to received the $request from fileBrowserUrl.
if you just need the id why not pass it in the route
filebrowserUploadUrl: "{{route('save-ckeditorproductphoto', [$some_id,'_token' => csrf_token())}}"
the docs said route helper can take any parameter on the array
Route::post('/products/save-ckeditorproductphoto/{product}', 'ProductphotosController#upload')->name('save-ckeditorproductphoto');
and modify your upload controller like
public function upload(Request $request, Product $product){ ... }
I'm trying to develop my own notification system on my website but I have a problem. I use firebase and his keys (I'm not using VapidKeys). One thing : every works on Firefox but not on Google Chrome.
For my application I followed this link.
and others tutorial on how does firebase works...
<?php
include_once (getenv('DOCUMENT_ROOT') . '/lib/include.php');
...
use Minishlink\WebPush\WebPush;
use Minishlink\WebPush\Subscription;
use Minishlink\WebPush\VAPID;
array of notifications
$notifications = array(
array(
'subscription' => Subscription::create(array(
'endpoint' => 'https://updates.push.services.mozilla.com/wpush/v1/gAAAAABcyExVQOIq3T0hJlKO6awqMrGwo0kcjjqi5mYKLddIfKcvva-2AcIMY1f1X32Zpdo3IlOqKb00eOhgUI_TTYMdmSwA6VxUjsQPgZwFmDQuvWjYnvax6yuV-WraBE9MclHMou6G', // Firefox 43+,
'publicKey' => 'BKVJQAkW1OFebroeetQBX1gVsDXQIs8TRYOk0b7ENCK3NBhOCxqCN2uAAZ5wQq7lqS0AqTu5qkKzNHH2oMQAJes', // base 64 encoded, should be 88 chars
'authToken' => 'PTYrPzIoW96SnYjjmSPvrg', // base 64 encoded, should be 24 chars
)
),
'payload' => 'hello !',
),
array(
'subscription' => Subscription::create(array(
'endpoint' => 'https://fcm.googleapis.com/fcm/send/dgSeLeTBqQs:APA91bGWVsUbkd5R9jOyqjDx5PMzuDtse1X9jGtJ3D_G_1wPehNFCq9-aEkyVSdqnzkuv5pbetE8k0rU_XrSGNvZ6WVG-7zZQJha_WvVK8zvUkGUxBsKzF6kPYMIDGZ6Qx2VjrWIbePS',
)
),
'payload' => null,
)
);
$webPush = new WebPush();
// send multiple notifications with payload
foreach ($notifications as $notification) {
$webPush->sendNotification(
$notification['subscription'],
$notification['payload'] // optional (defaults null)
);
}
foreach ($webPush->flush() as $report) {
$endpoint = $report->getRequest()->getUri()->__toString();
if ($report->isSuccess()) {
echo "[v] Message sent successfully for subscription {$endpoint}.";
} else {
echo "[x] Message failed to sent for subscription {$endpoint}: {$report->getReason()}";
}
}
I am trying to use mailgun.com for sending emails. But it happened that I need to send it with js (cause sometimes I built websites with rubyonrails, sometimes with python. And now I need to built a simple landing page with mail sending.
And hosting (which is free ad suits me only supports php which I don't know)
So I decided to use js and obfuscate this code and paste it somewhere in somelibrary.So no one will ever find my secret key)
Can someone help with translating some of this examples into js code?
This is python example:
def send_simple_message():
return requests.post(
"https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages",
auth=("api", "YOUR_API_KEY"),
data={"from": "Excited User <mailgun#YOUR_DOMAIN_NAME>",
"to": ["bar#example.com", "YOU#YOUR_DOMAIN_NAME"],
"subject": "Hello",
"text": "Testing some Mailgun awesomness!"})
This is c# example
public static IRestResponse SendSimpleMessage() {
RestClient client = new RestClient();
client.BaseUrl = new Uri("https://api.mailgun.net/v3");
client.Authenticator =
new HttpBasicAuthenticator("api",
"YOUR_API_KEY");
RestRequest request = new RestRequest();
request.AddParameter("domain",
"YOUR_DOMAIN_NAME", ParameterType.UrlSegment);
request.Resource = "{domain}/messages";
request.AddParameter("from", "Excited User <mailgun#YOUR_DOMAIN_NAME>");
request.AddParameter("to", "bar#example.com");
request.AddParameter("to", "YOU#YOUR_DOMAIN_NAME");
request.AddParameter("subject", "Hello");
request.AddParameter("text", "Testing some Mailgun awesomness!");
request.Method = Method.POST;
return client.Execute(request);
}
This is php example
# Include the Autoloader (see "Libraries" for install instructions)
require 'vendor/autoload.php';
use Mailgun\Mailgun;
# Instantiate the client.
$mgClient = new Mailgun('YOUR_API_KEY');
$domain = "YOUR_DOMAIN_NAME";
# Make the call to the client.
$result = $mgClient->sendMessage($domain, array(
'from' => 'Excited User <mailgun#YOUR_DOMAIN_NAME>',
'to' => 'Baz <YOU#YOUR_DOMAIN_NAME>',
'subject' => 'Hello',
'text' => 'Testing some Mailgun awesomness!'
));
This is rails example:
def send_simple_message
RestClient.post "https://api:YOUR_API_KEY"\
"#api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages",
:from => "Excited User <mailgun#YOUR_DOMAIN_NAME>",
:to => "bar#example.com, YOU#YOUR_DOMAIN_NAME",
:subject => "Hello",
:text => "Testing some Mailgun awesomness!"
end
Obfuscated code just slows down the naughty coder who is trying to mess up, its not a perfect layer of security. Since you say your host supports php use the php code. all you have to do is send a post request to the php script
example code considering you are sending using jQuery library for javascript
<?php
require 'vendor/autoload.php';
use Mailgun\Mailgun;
if(isset($_POST['variable1']) && isset($_POST['variable2']))
{
$msg = $_POST['variable1']." ".$_POST['variable1'];
$mgClient = new Mailgun('key');
$domain = "your domain";
$result = $mgClient->sendMessage($domain, array(
'from' => 'from adress',
'to' => 'to adress',
'subject' => 'some subject',
'html' => $msg
));
$result = objectToArray($result);
echo json_encode($result);
}
?>
jquery code to send post request
$("button").click(function(){
$.post("mailer.php",
{
variable1: "Donald Duck",
variable2: "Duckburg"
},
function(data, status){
console.log(data);
});
});
The above code sends a post request to your php file, where the php file validates if it contains the variables 1 and 2 and continues with the execution
In my Wordpress website Users can upload video files directly to a Amazon S3 bucket (So the files don't go through my webserver.) How i should keep track of the added objects (i.e: where and how i should add a data entry in my Wordpress Database )
With the limited information provided you could post the image data using ajax. The below is simple ajax with placeholder data for the image.
var imgData = {author: 'the-author-id', img_url: 'the-url', img_type: 'the-img-type'}
$.ajax({
data : JSON.stringify(imgData),
contentType : 'application/json',
type : 'POST',
url: 'your-wordpress-post-url',
success: function () {
// do something with the success result from backend
}
});
And within WordPress you would use wp_insert_attachment()
<?php
// Prepare an array of post data for the attachment.
$attachment = array(
'post_author' => $_POST['author'],
'post_date' => current_time('mysql'),
'guid' => $_POST['img_url'],
'post_mime_type' => $_POST['img_type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', $_POST['img_url'] ),
'post_content' => '',
'post_status' => 'inherit',
'comment_status' => 'closed',
'ping_status' => 'closed',
);
// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment );
// if fail $attach_id is 0
echo json_encode(array('attach_id' => $attach_id));
?>
I am trying to replicate the functionality to share a story on a Facebook wall similar to what this site has.
When you click on the share it should ask you to authenticate to facebook, if you are already authenticated it should show you the story to post to facebook.
I got the authentication part to work using the JavaScript SDK . I am not sure how to show the content to post to the wall.
Could anyone please provide an example.
Thanks!
<?php
# We require the library
require("facebook.php");
# Creating the facebook object
$facebook = new Facebook(array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
'cookie' => true
));
# Let's see if we have an active session
$session = $facebook->getSession();
if(!empty($session)) {
# Active session, let's try getting the user id (getUser()) and user info (api->('/me'))
try{
$uid = $facebook->getUser();
# let's check if the user has granted access to posting in the wall
$api_call = array(
'method' => 'users.hasAppPermission',
'uid' => $uid,
'ext_perm' => 'publish_stream'
);
$can_post = $facebook->api($api_call);
if($can_post){
# post it!
# $facebook->api('/'.$uid.'/feed', 'post', array('message' => 'Saying hello from my Facebook app!'));
# using all the arguments
$facebook->api('/'.$uid.'/feed', 'post', array(
'message' => 'The message',
'name' => 'The name',
'description' => 'The description',
'caption' => 'The caption',
'picture' => 'http://i.imgur.com/yx3q2.png',
'link' => 'http://net.tutsplus.com/'
));
echo 'Posted!';
} else {
die('Permissions required!');
}
} catch (Exception $e){}
} else {
# There's no active session, let's generate one
$login_url = $facebook->getLoginUrl();
header("Location: ".$login_url);
}
?>
http://developers.facebook.com/docs/reference/api/post/