Get product details in JSON format using REST API - json

How to get the product details in JSON format using REST API in Magento2? When I search I found the following code.
$url = 'magentohost url';
$callbackUrl = $url . "oauth_admin.php";
$temporaryCredentialsRequestUrl = $url . "oauth/initiate?oauth_callback=" . urlencode($callbackUrl);
$adminAuthorizationUrl = $url . 'admin/oauth_authorize';
$accessTokenRequestUrl = $url . 'oauth/token';
$apiUrl = $url . 'api/rest';
$consumerKey = 'consumer_key';
$consumerSecret = 'consumer_secret';
$token = 'token';
$secret = 'token_secret';
try {
$oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION);
$oauthClient->setToken($token, $secret);
$resourceUrl = "$apiUrl/products";
$oauthClient->fetch($resourceUrl, array(), 'GET', array('Content-Type' => 'application/json', 'Accept' => 'application/json'));
$productsList = json_decode($oauthClient->getLastResponse());
echo '<pre>';
print_r($productsList);
}
catch(Exception $e) {
echo '<pre>';
print_r($e);
}
But where I need to put this query... And also I am confusing with the URL...
And also it returns error Class OAuth not found

First, we need to create Web Service Role and Web Service User in Magento 2
Create Web Service Role:
Login Admin Panel> System> User Roles> Add New Role
Add the Role Name and your current password of Admin in Your Password field
Tap Role Resources
Choose what are required for service of your web in Resource Access
Tap Save Role
Create Web Service User in Magento 2
This user is used for the role you’ve created
Go to System> All Users> Add New User
Fill in all the necessary information
Tap User Role then choose which you’ve created
Tap Save User
The user above will used to REST API web service in Magento 2.
Next, we will get starting with Magento 2 REST API. Create a php file called my_magento2_rest_apt.php or whatever you want to make it. and place it in the magneto root directory.
Add this code into the file.
define('BASEURL','http://yourdomin.com/magento2location/');
$apiUser = 'username';
$apiPass = 'password';
$apiUrl = BASEURL.'index.php/rest/V1/integration/admin/token';
/*
Magento 2 REST API Authentication
*/
$data = array("username" => $apiUser, "password" => $apiPass);
$data_string = json_encode($data);
try{
$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$token = curl_exec($ch);
$token = json_decode($token);
if(isset($token->message)){
echo $token->message;
}else{
$key = $token;
}
}catch(Exception $e){
echo 'Error: '.$e->getMessage();
}
/*
Get Product By SKU REST API Magento 2
Use above key into header
*/
$headers = array("Authorization: Bearer $key");
//$requestUrl = BASEURL.'index.php/rest/V1/products/24-MB01';//24-MB01 is the sku.
//$requestUrl = BASEURL.'index.php/rest/V1/products?searchCriteria[page_size]=10';// get total 10 products
//$requestUrl = BASEURL.'index.php/rest/V1/categories/24/products';// 24 category id
//$requestUrl = BASEURL.'index.php/rest/V1/products?searchCriteria=';//get all products
$requestUrl = BASEURL.'index.php/rest/V1/products?searchCriteria[filter_groups][0][filters][0][field]=category_id&searchCriteria[filter_groups][0][filters][0][value]=24&searchCriteria[filter_groups][0][filters][0][condition_type]=eq';
$ch = curl_init();
try{
$ch = curl_init($requestUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$result = json_decode($result);
if(isset($result->message)){
echo $result->message;
}else{
print_r($result);
}
}catch(Exception $e){
echo 'Error: '.$e->getMessage();
}
now to get to your API just type. http://yourdomin.com/magento2location/my_magento2_rest_apt.php

Related

Need help to get JSON data from a website

I need to get JSON data from this website : https://shopee.co.id/search?keyword=western%20digital
I've tried and get this result: https://shopee.co.id/api/v2/search_items/?by=relevancy&keyword=western%20digital&limit=50&newest=0&order=desc&page_type=search
That's fine until I noticed the price is null and I need that price value
Any other method? Maybe I'm doing it wrong
Code so far:
<?php
function http_request($url){
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, $url);
// set user agent
curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
// return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
//close curl
curl_close($ch);
echo $output;
// return output
return $output;
}
if (isset($_POST['find']))
{
$search = $_POST['text_value'];
$search = str_replace(' ', '%20', $search);
$url = "https://shopee.co.id/api/v2/search_items/?by=relevancy&keyword=western%20digital&limit=50&newest=0&order=desc&page_type=search";
$profile = http_request($url);
// JSON to Array
$profile = json_decode($profile, TRUE);
$i = 0;
foreach($profile["data"] as $profil){
//add name, price from json
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Curl Data JSON</title>
</head>
<body>
<form action = "index2.php" method = "POST">
<input type = "text" name="text_value"><input type = "submit" value = "search" name = "find">
</form>
</body>
</html>

Print data via GET https://api.groovehq.com/v1/tickets

I'm trying to get data trough a JSON API from Groove.
https://www.groovehq.com/docs/tickets#listing-tickets
and https://www.groovehq.com/docs
This is the code I made:
<?php
function timjson_front($atts, $content) {
global $wpdb;
$access_token = ""; //insert token
$user_email = ""; // insert customers email
$json = getJSON($access_token, $user_email);
$html = "";
foreach($json as $key => $waarde) {
$html .= $key . ' = ' . $waarde;
}
return html_entity_decode($html);
}
function getJSON($access_token, $user_email) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'https://api.groovehq.com/v1/tickets?acces_token=' . $access_token . '&customer=' . $user_email);
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
return $obj;
}
?>
The code runs on a wordpress page and is part of a self made plugin. The idea is that the tickets from a customer gets printed on a page.
Wordpress gives a error at foreach(). Does anyone know what i'm doing wrong? Or has some advice?
First
You're iterating on $obj but $obj = json_decode($result); will returns an object. You need to iterate through an array so use json_decode($result, true)
Second
Based on the API, the first key is tickets and has multiple tickets
So you want to start with tickets in the foreach:
foreach($json['tickets'] as $ticket){
foreach($ticket as $key => $waarde) {
$html .= $key . ' = ' . $waarde;
}
}
Third
You're concatenating strings with $html .= $key . ' = ' . $waarde;
But based on the API, the values are not ALWAYS strings.
foreach($json['tickets'] as $ticket){
foreach($ticket as $key => $waarde) {
if(!in_array($key, ['tags','links'])){ // ignore the keys "tags" and "links" because they are array
$html .= $key . ' = ' . $waarde;
}
}
}
Edit: POC https://3v4l.org/dblmj

Validate Json - Laravel

Hello I'm new in laravel and have some strange situation:
in laravel api.php I have route
Route::get('/blog', function() {
$url_query_string = "format=json";
$request_url = 'https://www.squarespace.com/templates/?' . $url_query_string;
$ch = curl_init($request_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
curl_setopt($ch, CURLOPT_USERAGENT, 'H.H\'s PHP CURL script');
$response_body = curl_exec($ch);
curl_close($ch);
$res = json_decode($response_body,true);
echo json_encode($res);
});
so it is working but not gives me validated json it is not correct look at picture
not sure where is a problem?
I fixed this adding header('Content-Type: application/json');
$res = json_decode($response_body,true);
header('Content-Type: application/json');
echo json_encode($res);
Just add this small piece of code
if($request->isJson()) {
if(empty($request->json()->all())) {
echo "Invalid Json"
//Put invalid JSON handling functions here
} else {
echo "Valid JSON"
//Put you regular functions here because the input JSON is valid
// Even if you don't put the else clause it is ok the code will continue executing further
}
}

creating action with paypal ipn

This is my first time attempting to use paypal ipn. I am an amateur coder for sure. I have developed a user/subscriber site and I am wanting to finalize the paypal subscriber payments.
I have a number of questions but I know I should narrow it down to 1.
I understand ipn as sending a message to a page on my site. (I may be wrong). I am going to assume that would be the IPN handler URL. (?)
Does the IPN actually hit the page and create an action?
I would like that message (or loading of the page) to call a function which inserts in my database.
Here is my Listener...ipnverify.php
<?php require(Config::get('URL').'/paypalipn/PaypalIPN.php');
use PaypalIPN;
$ipn = new PayPalIPN();
$ipn->useSandbox();$verified = $ipn->verifyIPN();$name = $_POST['custom'];
if ($name==1) {
function updatePaypalTest()
{
$database = DatabaseFactory::getFactory()->getConnection();
$sql = "INSERT INTO paypal_test (name) VALUES('1')";
$query = $database->prepare($sql);
$query->execute();
}
updatePaypalTest();
header("HTTP/1.1 200 OK");
?>
And then the other file from github...PaypalIPN.php
<?php
class PaypalIPN
{
private $use_sandbox = true;
private $use_local_certs = false;
/*
* PayPal IPN postback endpoints
*/
const VERIFY_URI = 'https://ipnpb.paypal.com/cgi-bin/webscr';
const SANDBOX_VERIFY_URI = 'https://ipnpb.sandbox.paypal.com/cgi-bin/webscr';
/*
* Possible responses from PayPal after the request is issued.
*/
const VALID = 'VERIFIED';
const INVALID = 'INVALID';
/**
* Sets the IPN verification to sandbox mode (for use when testing,
* should not be enabled in production).
* #return void
*/
public function useSandbox()
{
$this->use_sandbox = true;
}
/**
* Determine endpoint to post the verification data to.
* #return string
*/
public function getPaypalUri()
{
if ($this->use_sandbox) {
return self::SANDBOX_VERIFY_URI;
} else {
return self::VERIFY_URI;
}
}
/**
* Verification Function
* Sends the incoming post data back to paypal using the cURL library.
*
* #return bool
* #throws Exception
*/
public function verifyIPN()
{
if ( ! count($_POST)) {
throw new Exception("Missing POST Data");
}
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = [];
foreach ($raw_post_array as $keyval) {
$keyval = explode('=', $keyval);
if (count($keyval) == 2) {
// Since we do not want the plus in the datetime string to be encoded to a space, we manually encode it.
if ($keyval[0] === 'payment_date') {
if (substr_count($keyval[1], '+') === 1) {
$keyval[1] = str_replace('+', '%2B', $keyval[1]);
}
}
$myPost[$keyval[0]] = urldecode($keyval[1]);
}
}
// Build the body of the verification post request, adding the _notify-validate command.
$req = 'cmd=_notify-validate';
$get_magic_quotes_exists = false;
if (function_exists('get_magic_quotes_gpc')) {
$get_magic_quotes_exists = true;
}
foreach ($myPost as $key => $value) {
if ($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
$value = urlencode(stripslashes($value));
} else {
$value = urlencode($value);
}
$req .= "&$key=$value";
}
// Post the data back to paypal, using curl. Throw exceptions if errors occur.
$ch = curl_init($this->getPaypalUri());
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSLVERSION, 6);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
// This is often required if the server is missing a global cert bundle, or is using an outdated one.
if ($this->use_local_certs) {
curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . "/cert/cacert.pem");
}
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Connection: Close']);
$res = curl_exec($ch);
$info = curl_getinfo($ch);
$http_code = $info['http_code'];
if ($http_code != 200) {
throw new Exception("PayPal responded with http code $http_code");
}
if ( ! ($res)) {
$errno = curl_errno($ch);
$errstr = curl_error($ch);
curl_close($ch);
throw new Exception("cURL error: [$errno] $errstr");
}
curl_close($ch);
// Check if paypal verfifes the IPN data, and if so, return true.
if ($res == self::VALID) {
return true;
} else {
return false;
}
}
}
Please help me understand what I am missing. Is there a way that I can call my function from the ipn message?

Using google places service with php curl

im trying to use the google places service with php curl
in my for loop (2 laps) , i send my url,
at the 1 lap, i can get json informations but the 2nd lap give me "REQUEST_DENIED" status. Here is my code :
<?php
//header("content-type: application/json");
//header("content-type: Access-Control-Allow-Origin: *");
//header("content-type: Access-Control-Allow-Methods: GET");
set_time_limit(0);
ini_set("memory_limit","12000M");
error_reporting(E_ALL);
ini_set('display_errors', True);
$cumulResults = array();
$pagenext="";
for($i=0;$i<2;$i++)
{
try{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=48.859294,2.347589&radius=50000&sensor=false&keyword=doctor&key=myapikeysecret'.$pagenext,
));
if(!curl_exec($curl)){
die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));
}
$resp = curl_exec($curl);
$result = json_decode($resp, true) ;
if(array_key_exists( 'status', $result ) )
{
switch ($result['status'])
{
case "OK":
break;
case "OVER_QUERY_LIMIT":
case "INVALID_REQUEST":
case "REQUEST_DENIED":
//echo $result['status'];
//exit;
break;
}
}
print_r($result );
if (array_key_exists('next_page_token', $result ) )
{
$pagenext = "&pagenex="+$result['next_page_token'];
}else{
$pagenext = "";
}
if($curl){curl_close($curl);}
sleep(5);
} catch (Exception $e) {
if($curl){curl_close($curl);}
}
}
?>
thanks
I would suggest using sleep to wait the thread between calls? Perhaps they are executing too quickly and hitting the request speed limit. Most Google maps services have them but they're not very well documented.
Hope this helps.