Magento 2 oauth 1 get request token - magento

Am not able to get request token in magento app. Signature is always invalid.
This is the code i use to generate the signature. The consumer key is the one is i get from localhost:8000 (magento shop) request to localhost:3000.
I tried changing the url both to localhost 8000 and 3000.
Followed these instructions: Magento instructions
function getSignature($consumerKey)
{
$params = array(
'oauth_nonce' => uniqid(mt_rand(1, 1000)),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => time(),
'oauth_version' => '1.0',
'oauth_consumer_key' => $consumerKey,
);
ksort($params);
$baseString = strtoupper('POST') . '&';
$baseString .= rawurlencode('http://localhost:8000') . '&';
$baseString .= rawurlencode(buildSignatureDataString($params));
$signature = hash_hmac('SHA1', $baseString, getSigningKey(), true);
return base64_encode($signature);
}
function getSigningKey()
{
return rawurlencode('magento_private_key') . '&';
}
function buildSignatureDataString(array $signatureData)
{
$signatureString = '';
$delimiter = '';
foreach ($signatureData as $key => $value) {
$signatureString .= $delimiter . $key . '=' . $value;
$delimiter = '&';
}
return $signatureString;
}

Related

Laravel base64 image Api

I am developing API in Laravel. I will receive the image in base64 format. How can I convert the base64 to image in Laravel?
public function profile_image_upload(User $user, Request $request)
{
$request->validate([
'picture' => 'required|image|mimes:jpeg,png,jpg|max:2048',
], []);
if ($user->picture !== null)
Storage::delete($user->picture);
$res_upload = uploadService::store_image($request->file('picture'), config('upload.user_profile_picture_storage_path'));
if ($res_upload)
return $user->update([
'picture' => $res_upload,
]);
return false;
you can create this helper function
in Helper.php ref link https://laravel-news.com/creating-helpers
function base64ImageUpload($path, $file)
{
$image = $file; // your base64 encoded
if (preg_match('/base64/', $file)) {
$imageInfo = explode(";base64,", $image);
$imgExt = str_replace('data:image/', '', $imageInfo[0]);
$image = substr($image, strpos($image, ",") + 1);
$name = \Str::random(40) . '.' . $imgExt;
$filePath = $path . '/' . $name;
\Storage::put($filePath, base64_decode($image));
return $filePath;
} else {
return null;
}
}
then whenever u need to upload u can just call this function like
$imageLocation = base64ImageUpload(config('upload.user_profile_picture_storage_path'),$request->picture);

Adding multiple Middlewares to Laravel routes using LaravelCollective/Annotations

The current version of LaravelCollective Annotations doesn't give support for multiple annotations.
As I request in this pull request:
https://github.com/LaravelCollective/annotations/pull/89
Just modify the file:
vendor/laravelcollective/annotations/src/Routing/Annotations/Annotations/Middleware.php
and add these lines to the method "modifyCollection" as showed bellow:
public function modifyCollection(EndpointCollection $endpoints, ReflectionClass $class)
{
foreach ($endpoints as $endpoint) {
foreach ((array) $this->value as $middleware) {
//Fix start
if($multipleMiddlewares = explode(',', $middleware)){
$middleware = '';
$nbMiddlewares = count($multipleMiddlewares)-1;
for($i=0; $i<=$nbMiddlewares; ++$i) {
$middleware .= $i > 0 ? "'" : '';
$middleware .= str_replace(' ', '', $multipleMiddlewares[$i]);
$middleware .= $i < $nbMiddlewares ? "', " : '';
}
}
//End of fix
$endpoint->classMiddleware[] = [
'name' => $middleware, 'only' => (array) $this->only, 'except' => (array) $this->except,
];
}
}
}
Then, in your controller, just add the annotations separated by coma like this:
/**
* #Middleware("web, auth, role:super-admin|admin")
*/

Bing API related searches

How does one get related searches to be included in response from Bing search API?
I am trying to apply responseFilter with value RelatedSearches as per the documentation here: https://learn.microsoft.com/en-us/rest/api/cognitiveservices/bing-web-api-v7-reference#relatedsearchanswer
Below is my code based on sample from Bing. I have added "&responseFilter=RelatedSearches" to the URL that is fetched by file_get_contents().
The error I get back is:
PHP Warning: file_get_contents(https://api.cognitive.microsoft.com/bing/v7.0/search?responseFilter=RelatedSearches&q=iphone+case): failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden
Clearly I am applying it wrong. What can I change to be making it working?
<?php
$accessKey = 'abc123';
$endpoint = 'https://api.cognitive.microsoft.com/bing/v7.0/search';
$term = 'burrito recipe';
function BingWebSearch ($url, $key, $query) {
$headers = "Ocp-Apim-Subscription-Key: $key\r\n";
$options = array ('http' => array (
'header' => $headers,
'method' => 'GET'));
$context = stream_context_create($options);
$result = file_get_contents($url . "?q=" . urlencode($query) . "&responseFilter=RelatedSearches", false, $context);
$headers = array();
foreach ($http_response_header as $k => $v) {
$h = explode(":", $v, 2);
if (isset($h[1]))
if (preg_match("/^BingAPIs-/", $h[0]) || preg_match("/^X-MSEdge-/", $h[0]))
$headers[trim($h[0])] = trim($h[1]);
}
return array($headers, $result);
}
if (strlen($accessKey) == 32) {
print "Searching the Web for: " . $term . "\n";
list($headers, $json) = BingWebSearch($endpoint, $accessKey, $term);
print "\nRelevant Headers:\n\n";
foreach ($headers as $k => $v) {
print $k . ": " . $v . "\n";
}
print "\nJSON Response:\n\n";
echo json_encode(json_decode($json), JSON_PRETTY_PRINT);
} else {
print("Invalid Bing Search API subscription key!\n");
print("Please paste yours into the source code.\n");
}
?>
The "403 Forbidden" is the hint. You don't have permission to request RelatedSearches unless you are on the S1 instance as per here: https://azure.microsoft.com/en-us/pricing/details/cognitive-services/search-api/

How to use Ajax pager in Drupal7

I want to use ajax_pager in my block.
I've installed Libraries API and Ajax Pager API (as it described on the AP API page). But it's still not working.
When I use 'pager' instead of 'ajax_pager' it works.
What I'm doing wrong?
<?php
function latest_news_block_info() {
$blocks['latest_news_block'] = array(
// info: The name of the block.
'info' => t('Latest News'),
);
return $blocks;
}
function latest_news_block_view($delta = '') {
// The $delta parameter tells us which block is being requested.
switch ($delta) {
case 'latest_news_block':
// Create your block content here
$block['subject'] = t('Last news');
$query = new EntityFieldQuery();
//change news by the name of your content type
$entities = $query->entityCondition('entity_type', 'node')
->pager(5, 0)
->entityCondition('bundle', 'news')
->propertyOrderBy("created", "DESC")
->execute();
$content = "";
foreach($entities['node'] as $obj) {
$node = node_load($obj->nid);
$content .= "<img src='" .file_create_url($node->field_image['und'][0]['uri']) . "' width='200px' height='200px'>" . l($node->title, "node/" . $node->nid) . truncate_utf8($node->body['und'][0]['value'], 200, true, true) . '<br><hr>';
$block['content'] = $content;
}
break;
}
$pager = theme('ajax_pager', array('parameters' => array('selector' => 'block-system-main')));
$block['content'] .= $pager;
return $block;
}

facebook app losing session values after redirection

I am using Facebook PHP SDK 3.1.1
This page is supposed to collect value from header and later use it for uploading images.
Problem: $_SESSION['file'] becomes null after user logs in to Facebook.
<?php
require 'facebook.php';
include('connect.php');
$facebook = new Facebook(array('appId' => "XXXXXX",'secret' => "XXXXX","cookie" => true,'fileUpload' => true));
session_start();
$user_id = $facebook->getUser();
if(isset($_REQUEST["src"]))
{
echo "<center><img src='loader.gif'/></center>";
echo "<center><div id='msg'>Exporting Image..</div></center>";
$_SESSION['file'] = $_REQUEST["src"];
$_SESSION['club'] = $_REQUEST["club"];
}
$code = $_REQUEST["code"];
if(empty($code))
{
$_SESSION['state'] = md5(uniqid(rand(), TRUE));
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id=". $app_id . "&redirect_uri=" . urlencode($my_url) . "&state=". $_SESSION['state'];
echo("<script> top.location.href='" . $dialog_url . "'</script>");
exit();
}
$token_url = "https://graph.facebook.com/oauth/access_token?". "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url). "&client_secret=" . $app_secret . "&scope=user_photos,email,read_stream,publish_stream&code=".$code;
function url_get_contents ($Url) {
if (!function_exists('curl_init')){
die('CURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
$response = url_get_contents($token_url);
$params = null;
parse_str($response, $params);
$graph_url = "https://graph.facebook.com/me?access_token=". $params['access_token'];
$user = json_decode(url_get_contents('https://graph.facebook.com/me/albums?access_token='.$params['access_token']),true);
foreach($user as $key=>$value)
{
foreach($user[$key] as $key1=>$value1)
{
if($value1['name'] == "Photos")
{
$album_uid = $value1['id'];
}
}
}
if(!isset($album_uid))
{
echo 'Create an album';
$album_details = array(
'message'=> 'Uploaded via XXX',
'name'=> 'Photos'
);
$create_album = $facebook->api('/me/albums', 'post', $album_details);
$album_uid = $create_album['id'];
}
$photo_details = array('message'=>$_SESSION["club"]);
try{
$file = NULL;
$file="../Photos/".$_SESSION['file'].".jpeg";
echo '<script>document.getElementById("msg").innerHTML = "Uploading Image"</script>';
$photo_details['image'] = '#' . realpath($file);
$upload_photo = $facebook->api('/'.$album_uid.'/photos', 'post', $photo_details);
}catch(Exception $e){
echo "<script type='text/javascript'>top.location.href = 'http://www.facebook.com/PAGE_URL/';</script>";
exit();
}
$_SESSION['file'] is null
Am I doing it right ? or something is wrong with my web hosting ?
The problem is that your app is running inside of an IFRAME and the session cookies are not being preserved. Please see here:
Facebook Iframe App with multiple pages in Safari Session Variables not persisting

Resources