how to update product information outside from Magento - php

I want to programmatically update product information, such as quantity, price, etc.
(from outside of the Magento source directory.)
How can I do that?

Magento is pretty easy to bootstrap. If you want a standalone script where you can access all your functions, just add the following at the top of your PHP file :
define('MAGENTO', realpath(dirname(__FILE__)));
require_once MAGENTO . '/../app/Mage.php'; //or whatever location your Mage.php file is
Mage::app(Mage_Core_Model_Store::ADMIN_CODE); //initialization with another store is possible
After that you can load all your models. To update your products I suggest you two ways. The regular one :
Mage::getModel('catalog/product')->setStoreId($myStoreId)->load($myProductId)
->setPrice(50)
->save();
Or the API model usage :
$api = Mage::getModel('catalog/product_api_v2');
$api->update($productId, $productData, $store, $identifierType);

I'd highly recommend leveraging the REST APIs available in M2x to Create/Update products and its attributes.
Note: You have the option of using OAuth or Bearer Tokens in Magento 2 to Authenticate/Authorize your API invocations.
You can find additional information on all the APIs available in Magento 2.1 here -
http://devdocs.magento.com/swagger/index_21.html
You'll find specifics of the APIs you need under the grouping titled catalogProductRepositoryV1
Get info on product(s) using a search/filter criteria -> GET /V1/products
Get info on a specific Product -> GET /V1/products/{sku}
Create New Product -> POST /V1/products
Create/Update specific Product -> PUT /V1/products/{sku}
I haven't tested the code, but I think something like this should do the trick:
$BEARER_TOKEN_TO_USE_FOR_TRANSACTION = 'XYZ';
$REQUEST_HEADER = array(
"Authorization => Bearer ". $BEARER_TOKEN_TO_USE_FOR_TRANSACTION ,
"cache-control: no-cache",
"content-type: application/json"
);
$REQUEST_URL='INSTANCE_URL/rest/V1/products';
$PRODUCT_DATA_TO_USE ='{
"product": {
ENTER_PRODUCT_ATTRIBUTES_AS_JSON
} }';
$CURL_OBJ = curl_init($REQUEST_URL);
$CURL_OPTIONS_ARRAY_TO_USE = array (
CURLOPT_HTTPHEADER => $REQUEST_HEADER,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $PRODUCT_DATA_TO_USE,
CURLOPT_URL => $REQUEST_URL,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
);
curl_setopt_array($CURL_OBJ, $CURL_OPTIONS_ARRAY_TO_USE);
$result = curl_exec($CURL_OBJ);
$result = json_decode($result);
echo 'Output -> " . $result;

Related

Eventbrite PHP RSVP

I have a list of our Eventbrite events inside our PHP CodeIgniter web app.
Here's the code fo my events list:
<?php
$token = "our_token";
$organizer_id = "our_organizer_id";
$request_url = "https://www.eventbriteapi.com/v3/events/search/?sort_by=date&organizer.id=".$organizer_id."&token=".$token;
$params = array('sort_by' => 'date', 'organizer.id' => $organizer_id, 'token' => $token);
$context = stream_context_create(
array(
'http' => array(
'method' => 'GET',
'header' => "Content-type: application/x-www-form-urlencoded\r\n"
)
)
);
$json_data = file_get_contents( $request_url, false, $context );
$response = json_decode($json_data, true);
?>
I used $response inside a loop so I could display them. Here's what it looks like.
Now, I want the users to be able to RSVP inside the system and not by redirecting through Eventbrite. Here's a sample event from the list.
I know it's possible but how can I make it work?
This is my first time to work on Eventbrite and their official documentation is in Python. I already emailed their support if they could provide me a good documentation in PHP but I haven't heard from them.
Although there's an SDK and some libraries available, I don't how how to use them and some of them with examples are deprecated.
Your help is highly appreciated.
This is not possible via Eventbrite's API endpoints. However, you can use Eventbrite's embedded checkout widget to accomplish this.
Here are the Eventbrite Articles on Embedded Checkout:
https://www.eventbrite.com/support/articles/en_US/Multi_Group_How_To/how-to-sell-eventbrite-tickets-on-your-website-through-an-embedded-checkout?lg=en_US
https://www.eventbrite.com/support/articles/en_US/How_To/how-to-add-eventbrite-s-embedded-checkout-to-your-wordpress-org-site?lg=en_US
I hope this helps you!

how does one pull information from a cURL request in wordpress

This is the header:
GFC-X-PORTER-PIPE: wZ5u8QgsCsTKR2Wz
Content-Type: application/json
So when you do a get using curl(like below):
curl -XGET -H "GFC-X-PORTER-PIPE: wZ5u8QgsCsTKR2Wz" -H "Content-Type: application/json" "https://mywebsite.com/employeestatus?key=John.Doe|John%20Doe"
RESULT:
{"name":"John Doe","request_header":{"Source-IP":"50.200.140.2"},"status":"out","update_date":"2017-12-13 08:54:04","username":"John.Doe","key":"John.Doe|John Doe"}
If you look at the result, you will see the status “OUT” (in red font) and that will change as there is a script that runs to update that status. That status needs to be underneath the employee info (except the executives) on this link: https://www.mywebsite.com/contact-us/addison/, https://www.mywebsite.com/contact-us/chicago/, and https://www.mywebsite.com/contact-us/hammond/ and you match their key(in yellow highlight) to the user in the contact-us page of the website.
It should show as “I am IN” and “I am OUT” underneath each user. The “IN” and “OUT” word will come from the database and the “I am” is hardcoded.
You can use WordPress' built in WP_Http class to make HTTP requests like so:
<?php
$client = new WP_Http();
$request = $client->request( 'https://mywebsite.com/employeestatus', array(
'headers' => array(
'GFC-X-PORTER-PIPE: wZ5u8QgsCsTKR2Wz',
'Content-Type: application/json',
),
'body' => array(
'key' => 'John.Doe|John Doe',
),
) );
$result = $request['body']; // This is your request output.
Then you can do whatever you want with your $result, you'll probably want to json_decode() it first.

Forward data from php script to calendar

I have a project where I need to do the following: retrieve some data from a form, fill the database, create a response for the user and post the data to a third party. To give an example, it's like booking a ticket to a concert.The ajax call: You buy the ticket, you receive a response (whether the purchase was successful), a php script sends data to the database, and someone may be announced that a new ticket was bought. Now, I need to pass data to that "someone". Which is what I don't know how to do.
Or, like when someone posts a comment to my question on stackoverflow, I get a notification.
In my particular case, the user creates an event, receives a response and I will need to have certain parameters posted by the user on a calendar. It is important that I could hardly integrate the calendar with the script retrieving the data. I would rather need to "forward" the data to the calendar- quite like pushing notifications.
Can anyone please give me a clue what should I use, or what should I need in order to do the above?
The process will go like this:
AJAX
user----> php script->database
|_ calendar
So if i get you right, you could post your data to the calendar via curl:
$url = "http://www.your-url-to-the-calendar.com";
$postData = array(
"prop1" => "value1",
"prop2" => "value2",
"prop3" => "value3"
);
//urlify the data for the post
$data_string = "";
foreach ($postData as $key => $value)
$data_string .= urlencode($key) . '=' . urlencode($value) . '&';
$data_string = rtrim($data_string, '&');
//will output --> prop1=value1&prop2=value2=prop3=value3
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_HEADER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_POST => count($postData),
CURLOPT_POSTFIELDS => $data_string
));
$result = curl_exec($ch);
If your third party calendar does not require authentication than this would be the best way to post it, if you can not write to the database yourself.
When it requires authentication you would have to first login via curl (send credentials via curl-post, receive cookies, send cookies with your data)
Hope this helps.

Dynamic W3C Validation

I have a small element on my website that displays the validity of the current page's markup. At the moment, it is statically set as "HTML5 Valid", as I constantly check whether it is, in fact, HTML5 valid. If it's not then I fix any issues so it stays HTML5-valid.
I would like this element to be dynamic, though. So, is there any way to ping the W3C Validation Service with the current URL, receive the result and then plug the result into a PHP or JavaScript function? Does the W3C offer an API for this or do you have to manually code this?
Maintainer of the W3C HTML Checker (aka validator) here. In fact the checker does expose an API that lets you do, for example:
https://validator.w3.org/nu/?doc=https%3A%2F%2Fgoogle.com%2F&out=json
…which gives you the results back as JSON. There’s also a POST interface.
You can find more details here:
https://github.com/validator/validator/wiki/Service-»-HTTP-interface
https://github.com/validator/validator/wiki/Service-»-Input-»-POST-body
https://github.com/validator/validator/wiki/Service-»-Input-»-GET
https://github.com/validator/validator/wiki/Output-»-JSON
They do not have an API that I am aware of.
As such, my suggestion would be:
Send a request (GET) to the result page (http://validator.w3.org/check?uri=) with your page's URL (using file_get_contents() or curl). Parse the response for the valid message (DOMDocument or simple string search).
Note: This is a brittle solution. Subject to break if anything changes on W3C's side. However, it will work and this tool has been available for several years.
Also, if you truly want this on your live site I'd strongly recommend some kind of caching. Doing this on every page request is expensive. Honestly, this should be a development tool. Something that is run and reports the errors to you. Keep the badge static.
Here is an example how to implement W3C API to validate HTML in PHP:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://validator.w3.org/nu/?out=json",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => '<... your html text to validate ...>',
CURLOPT_HTTPHEADER => array(
"User-Agent: Any User Agent",
"Cache-Control: no-cache",
"Content-type: text/html",
"charset: utf-8"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
//handle error here
die('sorry etc...');
}
$resJson = json_decode($response, true);
$resJson will look like this:
{
"messages": [
{
"type": "error",
"lastLine": 13,
"lastColumn": 110,
"firstColumn": 5,
"message": "Attribute “el” not allowed on element “link” at this point.",
"extract": "css\">\n <link el=\"stylesheet\" href=\"../css/plugins/awesome-bootstrap-checkbox/awesome-bootstrap-checkbox.min.css\">\n <",
"hiliteStart": 10,
"hiliteLength": 106
},
{
"type": "info",
"lastLine": 294,
"lastColumn": 30,
"firstColumn": 9,
"subType": "warning",
"message": "Empty heading.",
"extract": ">\n <h1 id=\"promo_codigo\">\n ",
"hiliteStart": 10,
"hiliteLength": 22
},....
Check https://github.com/validator/validator/wiki/Service-»-Input-»-POST-body for more details.

Scraping aspx page using php curl

I am trying to scrape a aspx page using php curl code, which contains data page wise. Initially the page loads with get method, but as we select page no. from drop down it submits page the page using post method.
I want to find data of particular page no by passing postfields to curl, but couldn't do that.
I have created a dummy code to get records of 5th page, but it always returns result of first page.
Sample code
$url = 'http://www.ticketalternative.com/SitePages/Search.aspx?catid=All&pattern=Enter%20Artist%2c%20Team%2c%20or%20Venue';
$file=file_get_contents($url);
//<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value=
preg_match_all("#<input.*?name=\"__VIEWSTATE\".*?value=\"(.*?)\".*?>.*?<input.*?name=\"__EVENTVALIDATION\".*?value=\"(.*?)\".*?>#mis", $file, $arr_viewstate);
$viewstate = urlencode($arr_viewstate[1][0]);
$eventvalidation = urlencode($arr_viewstate[2][0]);
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => true, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_USERAGENT => "spider", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 1120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_POST => true,
CURLOPT_VERBOSE => true,
CURLOPT_POSTFIELDS => '__EVENTTARGET='.urlencode('ctl00$ContentPlaceHolder1$SearchResults1$SearchResultsGrid$ctl13$ctl05').'&__EVENTARGUMENT='.urlencode('').'&__VIEWSTATE='.$viewstate.'&__EVENTVALIDATION='.$eventvalidation.'&__LASTFOCUS='.urlencode('').'&ctl00$ContentPlaceHolder1$SearchResults1$SearchResultsGrid$ctl13$ctl05=4');
$ch = curl_init($url);
curl_setopt_array($ch,$options);
$result = curl_exec($ch);
curl_close($ch);
preg_match_all('/<a id=\".*?LinkToVenue\" href=\"(.*?)\">(.*?)<\/a>/ms',$result,$matches);
print_r($matches);
Can anybody help me out with this, where am I getting wrong, I think its not working because at first time page loads with GET method and as we go on page links it uses post.
How will I get records of particular page no.?
Regards
I write scrapers in php sometimes when a client requires it but I would never attempt to scrape an ASP.NET site with php. For that you need perl python or ruby. All 3 have a mechanize library that usually makes it easy.

Categories