Unable to open the file attachment - sendgrid

I tried to send attachment using sendgrid CURL, the mail send successfully, but i'm unable to open the attachment file(like jpg, png, xls). the input file will be changes as per the user, also the file is not correct as in the original size.
I tried to send attachment using sendgrid CURL, the mail send successfully, but i'm unable to open the attachment file(like jpg, png, xls). the input file will be changes as per the user, also the file is not correct as in the original size.
<?php
// use actual sendgrid username and password in this section
$url = 'https://api.sendgrid.com/';
$user = 'SGusername'; // place SG username here
$pass = 'SGpassword'; // place SG password here
// grabs HTML form's post data; if you customize the form.html parameters then you will need to reference their new new names here
$name = $_POST['userName'];
$email = $_POST['userEmail'];
$user_Product = $_POST['userProduct'];
$message = $_POST['userMessage'];
$fileName = $_FILES['file_attach']['name'];
$filePath = dirname(__FILE__);
$params = array(
'api_user' => "$user",
'api_key' => "$pass",
'to' => "myemail.com", // set TO address to have the contact form's email content sent to
'subject' => "Feedback", // Either give a subject for each submission, or set to $subject
'html' => "<html><head><title> Contact Form</title><body>
Name: $name\n<br>
Email: $email\n<br>
Product: $user_Product\n<br>
Message: $message <body></title></head></html>", // Set HTML here. Will still need to make sure to reference post data names
'text' => "
Name: $name\n
Email: $email\n
Subject: $subject\n
$message",
'from' => "myemail.com", // set from address here, it can really be anything
'files['.$fileName.']' => '#'.$filePath.'/'.$fileName.
);
curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
$request = 'https://api.sendgrid.com/api/mail.send.json';
// Generate curl request
$session = curl_init($request);
// Tell curl to use HTTP POST
curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt ($session, CURLOPT_POST, true);
// Tell curl that this is the body of the POST
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// obtain response
$response = curl_exec($session);
curl_close($session);
if(!$response) //output success or failure messages
{
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$name .'.Thank you for your feedback.'));
die($output);
}
exit();
// print everything out
print_r($response);
?>

Related

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

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);
}

SugarCRM REST api error

I am trying to retrieve custom module data through the Sugarcrm REST api but I am not able to do so as I am not even able to login with the documentation code, I tried same thing as given in documentation
<?php
// specify the REST web service to interact with
$url = 'localhost/~jmertic/sugarcrm/service/v4_1/rest.php';
// Open a curl session for making the call
$curl = curl_init($url);
// Tell curl to use HTTP POST
curl_setopt($curl, CURLOPT_POST, true);
// Tell curl not to return headers, but do return the response
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Set the POST arguments to pass to the Sugar server
$parameters = array(
'user_auth' => array(
'user_name' => 'username',
'password' => md5('password'),
),
);
$json = json_encode($parameters);
$postArgs = array(
'method' => 'login',
'input_type' => 'JSON',
'response_type' => 'JSON',
'rest_data' => $json,
);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call, returning the result
$response = curl_exec($curl);
// Convert the result from JSON format to a PHP array
$result = json_decode($response);
if ( !is_object($result) ) {
die("Error handling result.\n");
}
if ( !isset($result->id) ) {
die("Error: {$result->name} - {$result->description}\n.");
}
// Get the session id
$sessionId = $result->id;
changed the username,password and url to match my setup but i get an error stating
No direct script access allowed
I tried to search this on web but couldnt find any relevant solution.
I am using sugarCRM 6.5.0RC2 version
Regards,
Anand Joshi
You probably has some defense configured on your WEB server which allows you to access only to index.php.
To verify it, try to go from the browser to your API URL: http://YOUR_DOMAIN_NAME/service/v4_1/rest.php
Or/and run from terminal: wget http://YOUR_DOMAIN_NAME/service/v4_1/rest.php
If it shows the same message, check your .httaccess on this folder or/and your web server config file.
If no, how do you run the API test script? through CLI or from browser?
Also I suggest you to use some Open Source SugarCRM REST API Wrapper. I use this one: https://github.com/asakusuma/SugarCRM-REST-API-Wrapper-Class
Shouldn't the line be this...
$url = 'http://yoursugarinstance/service/v4_1/rest.php';

Facebook API upload photo from URL

I have a website with photo gallery and I'd like to upload each photo (one by one) to my facebook page (not wall). I managed to post a message but now I want to upload a photo to a FB Page Wall by uploading an existing image from the server - specific URL (I don't want to upload again locally). Is this possible?
Yes you can do it
Example
In Graph Api Explorer
Make the call post, set url to https://graph.facebook.com/me/photos,
Add field with key message and value "any custom message"
Add another field with key url and value https://appharbor.com/assets/images/stackoverflow-logo.png
click submit
You need to know the album id and make call POST to:
https://graph.facebook.com/albumid/photos?access_token=$access_token
You will find the album id entering into the album and looking at the URL. Will be something like https://www.facebook.com/media/set/?set=a.XXXXXXXXXXX.YYYY.ZZZZZZZZZZ&type=3
Your album id are the XXXX.
this is what I use:
$facebook = new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET,
'cookie' => true,
'fileUpload' => true,
));
$user = $facebook->getUser(); // Get the UID of the connected user, or 0 if the Facebook user is not connected.
$facebook->setFileUploadSupport(true);
if($user == 0) {
// If the user is not connected to your application, redirect the user to authentication page
/**
* Get a Login URL for use with redirects. By default, full page redirect is
* assumed. If you are using the generated URL with a window.open() call in
* JavaScript, you can pass in display=popup as part of the $params.
*
* The parameters:
* - redirect_uri: the url to go to after a successful login
* - scope: comma separated list of requested extended perms
*/
$login_url = $facebook->getLoginUrl($params = array('redirect_uri' => REDIRECT_URI,'scope' => PERMISSIONS_REQUIRED));
echo ("<script> top.location.href='".$login_url."'</script>");
} else {
// if the user is already connected, then fetch access_token and user's information or show some content to logged in user.
try
{
$access_token = $facebook->getAccessToken(); // Gives you current user's access_token
$user = $facebook->api('/me'); // Gets User's information based on permissions the user has granted to your application.
} catch(FacebookApiException $e){
$results = $e->getResult();
// Print results if you want to debug.
}
}
$img = './upload/'.$image_path;
$args = array(
'message' => 'Some Message',
'access_token'=>urlencode($access_token),
);
$args[basename($img)] = '#'.realpath($img);
$ch = curl_init();
$url = 'https://graph.facebook.com/me/photos';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
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);
$response = json_decode($data,true);
$config = array('appId' => $config['App_ID'],'secret' => $config['App_Secret']);
$facebook = new Facebook($config);
// sets our access token as the access token when we call
// something using the SDK, which we are going to do now.
$facebook->setAccessToken($access_token);
$page_id = "XXXXXXXXXXXXXXX";
$page_access_token = "";
$result = $facebook->api("/me/accounts");
foreach($result["data"] as $page) {
if($page["id"] == $page_id) {
$page_access_token = $page["access_token"];
break;
}
}
$facebook->setFileUploadSupport(true);
$photo = "http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png";
$args = array(
'access_token' => $page_access_token,
'message' => "message here",
'url' => $photo,
);
$post = $facebook->api("/$page_id/photos","post",$args);

How to get Paypal transaction Id after getting paykey in paypal integration in iphone?

I am going to implement paypal in my iphone native app. But I am facig an issue in that.
I want to get my transaction Id regarding my PayKey. There is a direct method to get pay key in PayPal library to get PayKey but not a method to get transactionId.
Here is that method:
-(void)paymentSuccessWithKey:(NSString *)payKey andStatus:(PayPalPaymentStatus)paymentStatus;
As I am thinking IPN(Instant Payment Notification ) can help to resolve this issue but I don't know how to implement that one in my app?
Please help me to resolve this issue.
Thanks,
Chandra Prakash
Fianlly I have got solution of my question.
I have got transaction Id using IPN.
When I selected ENABLE IPN Option from my PayPal account then all details send by paypal I have received on URL which I given from there I have got all required fields.
Here are a few links to help you
IPN Overview:
https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/howto_html_instantpaymentnotif
IPN Documentation:
https://cms.paypal.com/cms_content/US/en_US/files/developer/IPNGuide.pdf
IPN Variables:
https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_html_IPNandPDTVariables
IPN Script Example:
https://cms.paypal.com/us/cgi-bin/?&cmd=_render-content&content_ID=developer/e_howto_admin_IPNImplementation
IPN Script Generator:
https://www.paypaltech.com/SG2/
Thanks,
Cp
I had a similar issue but was unable to rely on IPN so I thought I would share another method.
you don't need to use IPN, you can get the transaction ID with the payKey, which is useful for verifying mobile payments. Here is a php block that will get all of the transaction information from a payKey. You'll need to call it from your mobile app. For iOS you could use this tutorial: http://www.raywenderlich.com/13511/how-to-create-an-app-like-instagram-with-a-web-service-backend-part-12
<?
header("Content-Type: application/json");
//DEBUG TO CHECK PAYKEY
//turn php errors on
ini_set("track_errors", true);
//Example payKey (got from iOS app)
$payKey = "<snip>";
//set PayPal Endpoint to sandbox
$url = trim("https://svcs.sandbox.paypal.com/AdaptivePayments/PaymentDetails?payKey=".$payKey."&requestEnvelope.errorLanguage=en_US");
//PayPal API Credentials
//to do: change these for production credentials in the production app
$API_UserName = "<snip>";
$API_Password = "<snip>";
$API_Signature = "<snip>";
//Default App ID for Sandbox
$API_AppID = "APP-80W284485P519543T";
$API_RequestFormat = "NV";
$API_ResponseFormat = "NV";
try
{
//Create payload for this query
$bodyparams = array ("requestEnvelope.errorLanguage" => "en_US");
// convert payload array into url encoded query string
$body_data = http_build_query($bodyparams, "", chr(38)); // Generates body data
//create request and add headers
$params = array("http" => array(
"method" => "POST",
"content" => $body_data,
"header" => "X-PAYPAL-SECURITY-USERID: " . $API_UserName . "\r\n" .
"X-PAYPAL-SECURITY-PASSWORD: " . $API_Password . "\r\n" .
"X-PAYPAL-SECURITY-SIGNATURE: " . $API_Signature . "\r\n" .
"X-PAYPAL-APPLICATION-ID: " . $API_AppID . "\r\n" .
"X-PAYPAL-REQUEST-DATA-FORMAT: " . $API_RequestFormat . "\r\n" .
"X-PAYPAL-RESPONSE-DATA-FORMAT: " . $API_ResponseFormat
));
//create stream context
$ctx = stream_context_create($params);
//open the stream and send request
$fp = #fopen($url, "r", false, $ctx);
//get response
$response = stream_get_contents($fp);
//check to see if stream is open
if ($response === false) {
throw new Exception("php error message = " . "$php_errormsg");
}
//close the stream
fclose($fp);
//parse the ap key from the response
$keyArray = explode("&", $response);
foreach ($keyArray as $rVal){
list($qKey, $qVal) = explode ("=", $rVal);
$kArray[$qKey] = $qVal;
}
//print the response to screen for testing purposes
If ( $kArray["responseEnvelope.ack"] == "Success")
{
foreach ($kArray as $key =>$value){
echo $key . ": " .$value . "<br/>";
}
}
else {
echo 'ERROR Code: ' . $kArray["error(0).errorId"] . " <br/>";
echo 'ERROR Message: ' . urldecode($kArray["error(0).message"]) . " <br/>";
}
}
catch(Exception $e)
{
echo "Message: ||" .$e->getMessage()."||";
}
//End check paykey
?>
I would have attached an image showing all of the fields that you can get at with $kArray but I don't have the reputation. you would want: $kArray["paymentInfoList.paymentInfo(0).transactionId"]
NOTE: the API credentials you should use for sandbox can be found under your "sandbox accounts" at developer.paypal.com. Expand the profile of xxxfacilitator#xxx to get them
We can get transaction details like -
First get access token using your clientId and ClientSecret
$ch = curl_init();
$clientId = PAYPAL_CLIENT_ID; //client Id
$secret = PAYPAL_CLIENT_SECRET; client secrete key
curl_setopt($ch, CURLOPT_URL, "https://api.sandbox.paypal.com/v1/oauth2/token");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $clientId . ":" . $secret);
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
$result = curl_exec($ch);
$accessToken = null;
if (empty($result))
die('invalid access token');
else {
$json = json_decode($result);
$accessToken = $json->access_token;
}
curl_close($ch);
After Getting access token, I get transaction detail using following code
$curl = curl_init("https://api.sandbox.paypal.com/v1/payments/payment/<paykey>");
curl_setopt($curl, CURLOPT_POST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer ' . $accessToken,
'Accept: application/json',
'Content-Type: application/json'
));
$response = curl_exec($curl);
$result = json_decode($response);
With this we can validate transaction.
remove sandbox work from url when you are using it for live.

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
}