Elementor Form: How do I pass a metadata (like RemoteIP) using webhook? - metadata

I'm using Elementor Form Pro for a "work with us" form.
I know I can send some metadata, as RemoteIP, date and time, using "Action After Submit" Email.
How can I use the same metadata using Webhook? I know the values have to be sent by JSON, but I don't know how to do it.
Thanks in advance!

Don't know if this answer is still helpfull for you. But you can reach the meta data in a webhook by using the following structure for your array:
array["meta"]["remote_ip"]["value"]
As for the fields in the form you would use:
array["fields"]["email"]["value"]

Don't know if this answer is still helpful for you but you can send it via PHP using the elementor action hook: 'elementor_pro/forms/new_record'
All you have to add in the functions.php of your site is the following: & update the variables
.
add_action( 'elementor_pro/forms/new_record', 'send_data_using_webhook' , 10, 2 );
function send_data_using_webhook( $record )
{
$raw_fields = $record->get( 'fields' );
$data = array();
foreach ( $raw_fields as $id => $field ) {
$data[ $id ] = $field['value'];
}
// get the meta details
$raw_meta = $record->get('meta');
$meta = [];
foreach ( $raw_meta as $meta_id => $meta_value ) {
$meta[ $meta_id ] = $meta_value['value'];
}
$data['date'] = $meta['date'];
$data['time'] = $meta['time'];
$data['remote_ip'] = $meta['remote_ip'];
$data['page_url'] = $meta['page_url'];
$curl = curl_init("YOUR-WEBHOOK-URL-HERE");
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_exec($curl);
}

Related

Connect Yii2 to another RESTful application

I have a Yii2 application. I would like to connect it to another restful webpage. So user will send data to my application, I will send them via POST request and do something according to a JSON response. How can I do the send a request / fetch response part in a yii2?
The best method would be to use curl to make end to end calls to your RESTful API, in which case you may be interested in checking out a yii2 extension for curl.
Without a Yii2 extension, we can accomplish this by creating a more general function in a controller or more preferably a model (for shared access) as exampled below:
/**
* $method e.g POST, GET, PUT
* $data = [
'param' => 'value',
]
*/
public function curlToRestApi($method, $url, $data = null)
{
$curl = curl_init();
// switch $method
switch ($method) {
case 'POST':
curl_setopt($curl, CURLOPT_POST, 1);
if($data !== null) {
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
break;
// logic for other methods of interest
// .
// .
// .
default:
if ($data !== null){
$url = sprintf("%s?%s", $url, http_build_query($data));
}
}
// Authentication [Optional]
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "username:password");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
We then call this function on a need basis i.e. depending on the method and url and/or data.
It is also conveniently easy to use file_get_contents if fopen wrapper is enabled in order to access Web Service URLs.
$response = file_get_contents('http://example.com/path/to/api?param1=stack&param2=overflow');
If a JSON response is served, you can recover the php array as follows:
$response = json_decode($response, TRUE);
If an XML response is returned, then
$response = new \SimpleXMLElement($response);
However, if the API endpoint returns an HTTP error status, the file_get_contents function fails with a warning and returns null.

How can I get product list with its detail in rest API backend is magento2

I'm working on native mobile application backend is magento2 and I want to display product after customer selected a category. I am able to get list of the product by category in rest request but that list don't have much details about the product.
Request : http://localhost/magento2/index.php/rest/V1/categories/24/products
(24 is category ID)
Response : [{"sku":"WH01","position":1,"category_id":"24"},...]
Earlier in Magento 1.9 product list was something like
{
2: {
entity_id: "2"
type_id: "simple"
sku: "Levis Bagpack"
description: "Bagpack"
short_description: "Bagpack"
meta_keyword: null
name: "Levis Bagpack"
meta_title: null
meta_description: null
regular_price_with_tax: 45
regular_price_without_tax: 45
final_price_with_tax: 45
final_price_without_tax: 45
is_saleable: true
image_url: "http://172.16.8.24:8080/magento/media/catalog/product/cache/0/image/9df78eab33525d08d6e5fb8d27136e95/images/catalog/product/placeholder/image.jpg"
}
What should I do to get more info about product so I can show image and other things in mobile app ?
Maybe you can try the GET /V1/products/:sku REST API to get all the details.
Link
The returned value will be a representation of \Magento\Catalog\Api\Data\ProductInterface (including the additional attributes)
Link for Reference
Check \Magento\Catalog\Api\ProductRepositoryInterface::get which services the GET /V1/products/:sku REST API.
You can make multiple requests for all product SKUs.
OR
You can use the search API to fetch the entire list in a single request based on your criteria:
For example:
http://localhost/magento2/index.php/rest/V1/products?searchCriteria[filter_groups][0][filters][0][field]=sku&searchCriteria[filter_groups][0][filters][0][value]=simple&searchCriteria[filter_groups][0][filters][1][field]=sku&searchCriteria[filter_groups][0][filters][1][value]=Simple2&searchCriteria[filter_groups][0][filters][0][condition_type]=eq&searchCriteria[current_page]=1&searchCriteria[page_size]=2
In the case of products with SKUs - simple and Simple2 are being searched.
define('BASEURL','http://localhost/magento20_0407/');
$apiUser = 'testUser';
$apiPass = 'admin123';
$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
$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();
}
Similarly you can change $requestUrl and filter product list by category id and get product detail.
Please confirm whether it solves your problem or not. Else I'll post another solution.
You can try this, where '30' is category id. http://magentohost.com/rest/default/V1/products?searchCriteria[filter_groups][0][filters][0][field]=category_id&%20searchCriteria[filter_groups][0][filters][0][value]=30&%20searchCriteria[filter_groups][0][filters][0][condition_type]=eq&searchCriteria[pageSize]=10
Please try to use this endpoint instead of your endpoint:
/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
It is the same as #Alexander Timonchev, But you have to remove the space after &

sugarcrm REST get_entry

Can someone take a look at how I've set up this REST call? I haven't been able to find an example of this, and I can't get it to work.
It may be the blank 'link_name_to_fields_array' parameter. I have read the documentation and don't really understand that parameter. I don't know if that is causing my problem or not.
Any help would be apprecitated.
//SET UP CURL
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
//parameters for get_entry call (I received a session id from a call to the login function. Using it here)
//I manually got this user 'id' form the sugarcrm database
$parameters = array(
'session'=>$result->id,
'module_name' => 'users',
'id' => '21a6a633-40de-9bf4-aa14-4f8753ea5aa2',
'select_fields' => array('user_name'),
'link_name_to_fields_array'=> array()
);
$json = json_encode($parameters);
$postArgs='method=get_entry&input_type=JSON&response_type=JSON$rest_data=' . $json;
curl_setopt($curl,CURLOPT_POSTFIELDS, $postArgs);
$result2 = curl_exec( $curl );
echo("<pre>" . print_r($result2,true) . "</pre>");
The output is "Bad data passed in; Return to Home"
You have an error in the postArgs line (replace $rest_data with &rest_data). Try with this:
$postArgs='method=get_entry&input_type=JSON&response_type=JSON&rest_data=' . $json;

How to submit form to a page on another server with some type of ajax?

I would like to submit my form to another page but making it not go to that page (like AJAX, but I know that AJAX does not work across domains)
Do you guys know how to do this? I don't like submitting it to the page on the other site because it is just really a slower and crappier way of doing things.
Thanks,
Nathan Johnson
Submit your form to a local page via AJAX. From that page you can post the data to the remote site with e.g. cURL.
Here's a very abstract example:
page_with_form.php
<form id="form1">
//input fields
</form>
<script>
$.post('post_to_remote.php', $('#form1').serialize(), function(){
//do something when finished
return false; //prevent from reloading
});
</script>
post_to_remote.php
$param1 = $_POST['param1'];
$param2 = $_POST['param2'];
$remoteUrl = 'http://www.remote_site.com/page_to_post_to.php';
$postFields = array('param1' => $param1, 'param2' => $param2);
//if you don't want to do any sanitizing, you can also simply do this:
//$postFields = $_POST;
$data_from_remote_page = $getUrl($remoteUrl, 'post', $postFileds);
function getUrl($url, $method='', $vars='') {
$ch = curl_init();
if ($method == 'post') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
$buffer = curl_exec($ch);
curl_close($ch);
return $buffer;
}
If you do not need the full power of curl and it's really just a simple post, you can also use native PHP functions:
$postFields = http_build_query($_POST);
$remoteUrl = 'http://www.remote_site.com/page_to_post_to.php';
$context = stream_context_create(
array(
'http' => array(
'method' => 'POST',
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'content' => $postFields,
'timeout' => 10,
),
)
);
$result = file_get_contents($remoteURL, false, $context);
A vary basic example, but you get the idea.
You can try using JSONP:
http://davidwalsh.name/jsonp
http://api.jquery.com/jQuery.getJSON/#jsonp
It can be used cross-domain, but the data you send back from the server has to be something like (PHP):
echo $_GET['callback']."(".json_encode($data).")";
When I first used it I didn't echoed the callback function's name and it took me a couple of hours to see why it wasn't working.
Good luck!
Try jsonp in javascript:
$.ajax({
url: 'some_url' ,
data: $('#form_id').serialize(),
dataType: "jsonp",
jsonp : "callback",
jsonpCallback: "jsonpcallbask"
});
function jsonpcallbask(data) {
//handle response here
}

How to tag photos in facebook-api?

I wanted to ask if/how is it possible to tag a photo using the FB API (Graph or REST).
I've managed to create an album and also to upload a photo in it, but I stuck on tagging.
I've got the permissions and the correct session key.
My code until now:
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
$token = $session['access_token'];//here I get the token from the $session array
$album_id = $album[0];
//upload photo
$file= 'images/hand.jpg';
$args = array(
'message' => 'Photo from application',
);
$args[basename($file)] = '#' . realpath($file);
$ch = curl_init();
$url = 'https://graph.facebook.com/'.$album_id.'/photos?access_token='.$token;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
$data = curl_exec($ch);
//returns the id of the photo you just uploaded
print_r(json_decode($data,true));
$search = array('{"id":', "}");
$delete = array("", "");
// picture id call with $picture
$picture = str_replace($search, $delete, $data);
//here should be the photos.addTag, but i don't know how to solve this
//above code works, below i don't know what is the error / what's missing
$json = 'https://api.facebook.com/method/photos.addTag?pid='.urlencode($picture).'&tag_text=Test&x=50&y=50&access_token='.urlencode($token);
$ch = curl_init();
$url = $json;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_exec($ch);
} catch(FacebookApiException $e){
echo "Error:" . print_r($e, true);
}
I really searched a long time, if you know something that might help me, please post it here :)
Thanks for all your help,
Camillo
Hey,
you can tag the Picture directly on the Upload with the GRAPH API,
see the example below:
This Method creates an array for the tag information, in this examples the method becomes an array with Facebook user Ids:
private function makeTagArray($userId) {
foreach($userId as $id) {
$tags[] = array('tag_uid'=>$id, 'x'=>$x,'y'=>$y);
$x+=10;
$y+=10;
}
$tags = json_encode($tags);
return $tags;
}
Here are the arguments for the call of the GRAPH API to upload an picture:
$arguments = array(
'message' => 'The Comment on this Picture',
'tags'=>$this->makeTagArray($this->getRandomFriends($userId)),
'source' => '#' .realpath( BASEPATH . '/tmp/'.$imageName),
);
And here is the Method for the GRAPH API call:
public function uploadPhoto($albId,$arguments) {
//https://graph.facebook.com/me/photos
try {
$fbUpload = $this->facebook->api('/'.$albId.'/photos?access_token='.$this->facebook->getAccessToken(),'post', $arguments);
return $fbUpload;
}catch(FacebookApiException $e) {
$e;
// var_dump($e);
return false;
}
}
The argument $albId contains an ID from an Facebook Album.
And if you want to Tag an existing Picture from an Album you can user this Method:
At First we need the correct picture ID from the REST API, In this example we need the Name from an Album wich the Application has create or the user wich uses this Application.
The Method returns The Picture ID From the last Uploaded Picture of this Album:
public function getRestPhotoId($userId,$albumName) {
try {
$arguments = array('method'=>'photos.getAlbums',
'uid'=>$userId
);
$fbLikes = $this->facebook->api($arguments);
foreach($fbLikes as $album) {
if($album['name'] == $albumName) {
$myAlbId = $album['aid'];
}
}
if(!isset($myAlbId))
return FALSE;
$arguments = array('method'=>'photos.get',
'aid'=>$myAlbId
);
$fbLikes = $this->facebook->api($arguments);
$anz = count($fbLikes);
var_dump($anz,$fbLikes[$anz-1]['pid']);
if(isset($fbLikes[$anz-1]['pid']))
return $fbLikes[$anz-1]['pid'];
else
return FALSE;
//var_dump($fbLikes[$anz-1]['pid']);
//return $fbLikes;
}catch(FacebookApiException $e) {
$e;
// var_dump($e);
return false;
}
}
Now you have the correct picture ID From the REST API and you can make your REST API CALL to tag this Picture $pid is the Picture from the Method getRestPhotoId and $tag_uid is an Facebook userId:
$json = 'https://api.facebook.com/method/photos.addTag?pid='.$pid.'&tag_uid='.$userId.'&x=50&y=50&access_token='.$this->facebook->getAccessToken();
$ch = curl_init();
$url = $json;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_GET, true);
$data = curl_exec($ch);
And this line is very important:
curl_setopt($ch, CURLOPT_GET, true);
you must youse CUROPT_GET instead of CUROPT_POST to add a Tag throw the REST API.
I Hope this helps you.
Best wishes Kay from Stuttart
Photo id is unique for every user and looks like two numbers joined by underscore in the middle.
Getting this id is a bit tricky.
You can get it by running FQL on photo table but you need to provide album id which is also user unique. You can get album id from album table but you need to provide owner userid.
For example we have CocaCola user with userid 40796308305. To get photo ids from this user we can run FQL:
SELECT pid FROM photo WHERE aid IN ( SELECT aid FROM album WHERE owner="40796308305")
(you can run it in a test console on this page)
This would return our photo ids:
[
{
"pid": "40796308305_2298049"
},
{
"pid": "40796308305_1504673"
},
{
"pid": "40796308305_2011591"
},
...
]
I didn't work with photos much, maybe you don't have to go through all this process to get photo id, it might be some simple algorithm like <OWNER_ID>_<PHOTO_ID>. But try to get your photo id from FQL and see if tagging would work. If it does maybe you will be able to skip FQL part and build photo id from existing data you have.
Hopefully this helps.
I found out the problem, the problem is that when you use curl to send the array the post function will not send the array correctly, it was sending just "Array" that it was why the graph API complained about tags being an array. To solve that I did the following:
$data = array(array('tag_uid' => $taguser,
'x' => rand() % 100,
'y' => rand() % 100
));
$data = json_encode($data);
$photo_details = array(
'message'=> $fnames,
'tags' => $data
);
Now I just send using curl
curl_setopt($ch, CURLOPT_POSTFIELDS, $photo_details);