CURL - No response and no error - php

I'm hoping someone could help me as I'm getting no response, no error, and no indication of why my CURL is not working here. I've searched around and added a clause to ignore the SSL (SSLVerify is set to false) and tried numerous ways to get a response.
May someone please point me in the right direction?
Thanks!
<?php
function sendContactInfo() {
//Process a new form submission in HubSpot in order to create a new Contact.
$hubspotutk = $_COOKIE['hubspotutk']; //grab the cookie from the visitors browser.
$ip_addr = $_SERVER['REMOTE_ADDR']; //IP address too.
$hs_context = array(
'hutk' => $hubspotutk,
'ipAddress' => $ip_addr,
'pageUrl' => 'https://www.myfoodstorage.com/onestepcheckout/',
'pageTitle' => 'MyFoodStorage.com Cart Checkout'
);
$hs_context_json = json_encode($hs_context);
//Need to populate these varilables with values from the form.
$str_post = "firstname=" . urlencode($firstname)
. "&lastname=" . urlencode($lastname)
. "&email=" . urlencode($email)
. "&phone=" . urlencode($telephone)
. "&address=" . urlencode($street)
. "&city=" . urlencode($city)
. "&state=" . urlencode($region)
. "&country=" . urlencode($country)
. "&hs_context=" . urlencode($hs_context_json); //Leave this one be :)
//replace the values in this URL with your portal ID and your form GUID
$endpoint = 'https://forms.hubspot.com/uploads/form/v2/234423/4a282b6b-2ae2-4908-bc82-b89874f4e8ed';
$ch = #curl_init();
#curl_setopt($ch, CURLOPT_POST, true);
#curl_setopt($ch, CURLOPT_POSTFIELDS, $str_post);
#curl_setopt($ch, CURLOPT_URL, $endpoint);
#curl_setopt($ch, CURLOPT_HTTPHEADER, array('application/x-www-form-urlencoded'));
#curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
#curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = #curl_exec($ch);
$info = #curl_getinfo($ch);
#curl_close($ch);
}
echo sendContactInfo();
echo $response;
print_r($info);
?>

1.you can't print variable value defined inside a function outside of function, like this:
function sendContactInfo() {
$response = #curl_exec($ch);
$info = #curl_getinfo($ch);
}
echo $response;
print_r($info);
but you can print value so:
function sendContactInfo() {
$response = #curl_exec($ch);
$info = #curl_getinfo($ch);
echo $response;
print_r($info);
}
sendContactInfo();
2.when you want to run function and get after value, use "return", like this:
function sendContactInfo() {
$response = #curl_exec($ch);
$info = #curl_getinfo($ch);
return $response;
//or return $info;, when you want to get array values from #curl_getinfo
}
print_r(sendContactInfo());

sendContactInfo is a function but its not being used like one.
You can't access variables that are used inside the function. Also it needs to return something
Change:
$response = #curl_exec($ch);
to
return #curl_exec($ch);

Related

How do i get the correct redirect url for my shopify app?

I am learning how to make Shopify apps right but I am in trouble because even after following every single line of code correctly I can't seem to figure out what I have done wrong.
Error - It says theshopifystore.myshopify.com refused to connect
everything else is fine i can even store all the info about a store on MySQL but i think the redirect url should be something else can anyone figure out what it is?
Here is the code of all the files that I have made in that process
first - index.php
<?php
include_once("inc/mysql_connect.php");
include_once("header.php");?>
Second - install.php
<?php
// Set variables for our request
$shop = $_GET['shop'];
$api_key = "22xxxxxx151d751c89";
$scopes = "read_orders,write_orders,read_products,write_products";
$redirect_uri = "https://videomap.host/token.php";
// Build install/approval URL to redirect to
$install_url = "https://" . $shop . "/admin/oauth/authorize?client_id=" . $api_key . "&scope=" . $scopes . "&redirect_uri=" . urlencode($redirect_uri);
// Redirect
header("Location: " . $install_url);
die();?>
Third - token.php
<?php
// Get our helper functions
require_once("inc/functions.php");
require_once("inc/mysql_connect.php");
// Set variables for our request
$api_key = "x7151d751c89xxxxxxxxxxx";
$shared_secret = "shxxxxxxxxa72837xxxxxx4f";
$params = $_GET; // Retrieve all request parameters
$hmac = $_GET['hmac']; // Retrieve HMAC request parameter
$params = array_diff_key($params, array('hmac' => '')); // Remove hmac from params
ksort($params); // Sort params lexographically
$computed_hmac = hash_hmac('sha256', http_build_query($params), $shared_secret);
// Use hmac data to check that the response is from Shopify or not
if (hash_equals($hmac, $computed_hmac)) {
// Set variables for our request
$query = array(
"client_id" => $api_key, // Your API key
"client_secret" => $shared_secret, // Your app credentials (secret key)
"code" => $params['code'] // Grab the access key from the URL
);
// Generate access token URL
$access_token_url = "https://" . $params['shop'] . "/admin/oauth/access_token";
// Configure curl client and execute request
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $access_token_url);
curl_setopt($ch, CURLOPT_POST, count($query));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($query));
$result = curl_exec($ch);
curl_close($ch);
// Store the access token
$result = json_decode($result, true);
$access_token = $result['access_token'];
// Show the access token (don't do this in production!)
$sql = "INSERT INTO shop (shop_url, access_token, install_date)
VALUES ('".$params['shop']."', '".$access_token."', NOW())";
if (mysqli_query($conn, $sql)) {
header('Location: https://'.$params['shop'].'/admin/apps');
die();
} else {
echo "Error inserting new record: " . mysqli_error($conn);
}
} else {
// Someone is trying to be shady!
die('This request is NOT from Shopify!');
}?>
Fourth - header.php
<?php $shopify = $_GET;
$sql = "SELECT * FROM shops WHERE shop_url='" . $shopify['shop'] . "' LIMIT 1";
$check = mysqli_query($conn, $sql);
if(mysqli_num_rows($check) < 1){
header("Location: install.php?shop=" . $shopify['shop']);
exit();
}else{
$shop_row = mysqli_fetch_assoc($check);
$shop_url = $shopify['shop'];
$token = $shop_row['access_token'];
}
?>
Fifth - inc/functions.php
<?php
function shopify_call($token, $shop, $api_endpoint, $query = array(), $method = 'GET', $request_headers = array()) {
// Build URL
$url = "https://" . $shop . $api_endpoint;
if (!is_null($query) && in_array($method, array('GET', 'DELETE'))) $url = $url . "?" . http_build_query($query);
// Configure cURL
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($curl, CURLOPT_MAXREDIRS, 3);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
// curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 3);
// curl_setopt($curl, CURLOPT_SSLVERSION, 3);
curl_setopt($curl, CURLOPT_USERAGENT, 'My New Shopify App v.1');
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
// Setup headers
$request_headers[] = "";
if (!is_null($token)) $request_headers[] = "X-Shopify-Access-Token: " . $token;
curl_setopt($curl, CURLOPT_HTTPHEADER, $request_headers);
if ($method != 'GET' && in_array($method, array('POST', 'PUT'))) {
if (is_array($query)) $query = http_build_query($query);
curl_setopt ($curl, CURLOPT_POSTFIELDS, $query);
}
// Send request to Shopify and capture any errors
$response = curl_exec($curl);
$error_number = curl_errno($curl);
$error_message = curl_error($curl);
// Close cURL to be nice
curl_close($curl);
// Return an error is cURL has a problem
if ($error_number) {
return $error_message;
} else {
// No error, return Shopify's response by parsing out the body and the headers
$response = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
// Convert headers into an array
$headers = array();
$header_data = explode("\n",$response[0]);
$headers['status'] = $header_data[0]; // Does not contain a key, have to explicitly set
array_shift($header_data); // Remove status, we've already set it above
foreach($header_data as $part) {
$h = explode(":", $part);
$headers[trim($h[0])] = trim($h[1]);
}
// Return headers and Shopify's response
return array('headers' => $headers, 'response' => $response[1]);
}
}
Sixth - inc/mysql_connect.php
<?php
$host = "localhost";
$username = "xxxxxxx_shopify";
$password ="xxxxxxx1#";
$database = "xxxxxxxopify";
$conn = mysqli_connect($host, $username, $password, $database);
if(!$conn){
die("Connection Error" . mysqli_connect_error());
}
?>

Workflow Max add job via API

I'm trying to add a job to the Workflow Max API. I seem to be hitting the API but I keep getting the error message:
Message not in expected format. The following required element was missing - Job/ClientID
I'm sure that the client ID is added but something seems to be wrong. This is the code:
function post_job_to_workflow_max($job_data) {
// configure our connection to the api
$api_token = 'API_KEY';
$acc_key = 'ACC_TOKEN';
$url = 'https://api.workflowmax.com/job.api/add?apiKey=' . $api_token . '&accountKey=' . $acc_key;
// Job data must match the format required by WorkflowMax
// currently accepts XML data
// see: https://www.workflowmax.com/api/job-methods#POST%20add
$xml = new SimpleXMLElement("<Job></Job>");
$xml->addChild('Name', $job_data[0]);
$xml->addChild('Description', $job_data[1]);
$xml->addChild('ClientID', 18754031);
// $clientID = $xml->addChild('Client');
// $clientID->addChild('ID', 18754031);
// $clientID->addChild('Name', "TEST CLIENT");
$xml->addChild('State', 'Planned');
$xml->addChild('StartDate', $job_data[2]);
$xml->addChild('DueDate', $job_data[3]);
// print_r($xml);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml->asXML());
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: text/xml',
'Content-Length: ' . strlen($xml->asXML()))
);
$output = curl_exec($ch);
curl_close($ch);
$result = simplexml_load_string($output);
print_r($result);
}
If there's anyone with experience of using WFM, would be good to hear how you approached it.
Thanks
So in answer to my own question, I did finally work this out.
The way I did this was to return the ID of the client from the function I used to post a client to WorkFlow Max. See code:
1) post the client
function post_client_to_workflowmax($client_data) {
// configure our connection to the api
$api_token = 'YOUR_TOKEN';
$acc_key = 'YOUR_KEY';
$url = 'https://api.workflowmax.com/client.api/add?apiKey=' . $api_token . '&accountKey=' . $acc_key;
// Client data must match the format required by WorkflowMax
// currently accepts XML data
// These indexes match up with how the data has been stored
// see: https://www.workflowmax.com/api/client-methods#POST%20add
$xml = new SimpleXMLElement("<Client></Client>");
$xml->addChild('Name', htmlspecialchars($client_data[2]));
$xml->addChild('Email', htmlspecialchars($client_data[9]));
$xml->addChild('Phone', htmlspecialchars($client_data[10]));
$xml->addChild('Address', htmlspecialchars($client_data[3]) . ' ' . htmlspecialchars($client_data[4]));
$xml->addChild('City', htmlspecialchars($client_data[5]));
$xml->addChild('Postcode', htmlspecialchars($client_data[7]));
$xml->addChild('Country', htmlspecialchars($client_data[8]));
$xml->addChild('IsProspect', 'No');
$contacts = $xml->addChild('Contacts');
$contact = $contacts->addChild('Contact');
$name = $contact->addChild('Name', htmlspecialchars($client_data[0]) . ' ' . htmlspecialchars($client_data[1]));
// POST request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml->asXML());
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: text/xml',
'Content-Length: ' . strlen($xml->asXML()))
);
$output = curl_exec($ch);
curl_close($ch);
// Create an array from the data that is sent back from the API
$result = simplexml_load_string($output);
$clientID = NULL;
// here we get the ID created for this client and pass it into the variable $clientID
foreach($result->Client as $k => $v) {
$clientID = $v->ID;
}
return $clientID;
}
We then get that ID passed into our job posting function like so:
2) post a job to WFM
function post_job_to_workflow_max($job_data, $clientID) {
// configure our connection to the api
$api_token = 'YOUR_TOKEN';
$acc_key = 'YOUR_KEY';
$url = 'https://api.workflowmax.com/job.api/add?apiKey=' . $api_token . '&accountKey=' . $acc_key;
// Job data must match the format required by WorkflowMax
// currently accepts XML data
// see: https://www.workflowmax.com/api/job-methods#POST%20add
$xml = new SimpleXMLElement("<Job></Job>");
$xml->addChild('ClientID', $clientID);
$xml->addChild('Name', htmlspecialchars($job_data[0]));
$xml->addChild('Description', htmlspecialchars($job_data[1]));
$xml->addChild('State', 'Planned');
$xml->addChild('StartDate', htmlspecialchars($job_data[2]));
$xml->addChild('DueDate', htmlspecialchars($job_data[3]));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml->asXML());
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: text/xml',
'Content-Length: ' . strlen($xml->asXML()))
);
$output = curl_exec($ch);
curl_close($ch);
$result = simplexml_load_string($output);
}
And then calling these functions looks something like this:
$id = post_client_to_workflowmax($client);
post_job_to_workflow_max($job, $id);
Where $client must be an array of data. This worked for my case but might not work for your particular case so you may need to edit the fields etc.
Hopefully this helps someone who is stuck with the same problem. Not the most elegant code but it gets the job done.

Get JSON generated by a webhook hosted online

I am making a card payment and then it communicates to the server of the company via webhook, the response is then recorded in RequestBin, which generates a JSON response in their website, how do I extract the information from the website to my PHP code?
The webpage looks like this:
my requestb.in online webhook
What I need is to get that raw JSON.
You could try using CURL to retrieve the JSON object. Are you using CURL to send the payment payload out to the processor, etc? Below is an example (Obviously you would need to fill in the appropriate PHP variables where applicable).
$reqbody = json_encode($_REQUEST);
$serviceURL = "http://www.url.com/payment_processor";
$curl = curl_init($serviceURL);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $reqbody);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_VERBOSE, true);
$headers = array(
'Content-type: application/json',
"Authorization: ".$hmac_enc,
"apikey: ".$apikey,
"token: ".$token,
"timestamp: ".$timestamp,
"nonce: ".$nonce,
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 201 ) {
die("Error: call to URL $serviceURL failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}
curl_close($curl);
$response = json_decode($json_response, true);
echo "<hr/><br/><strong>PROCESSOR RESPONSE:</strong><br/>";
echo "<pre>";
print_r($response);
echo "</pre>";
You could get the json from requestbin and resend it to your localhost using a request client like Postman.
if (!empty($_POST)) {
$data = json_decode($_POST);
}
I found the solution, first you download HTML dom and then you just change the fields. The reason the for loop goes from 0-19 is because requestb.in saves 20 entries, for the rest just substitute the variables.
include('../simple_html_dom.php');
// get DOM from URL or file
// asegurese de incluir el ?inspect en el URL
$html = file_get_html('https://requestb.in/YOURURL?inspect');
for ($x = 0; $x <= 19; $x++) {
$result = $html->find('pre[class=body prettyprint]', $x)->plaintext;
if($result){
$json_a = str_replace('"', '"', $result);
$object = json_decode($json_a);
if(isset($object->type)) echo $object->type . "<br>";
if(isset($object->transaction->customer_id)) echo $object->transaction->customer_id . "<br>";
}
}

error :024 in sms sending with smsindiahub

I am using smsindiahub to send sms as below but it is not sending the message,
function send_user_pickup_sms($mobile_number = '', $verification_code = '', $smsemailarray=array(),$date="",$time="") {
if ($mobile_number != '' && $verification_code != '') {
//$customer_name = $userDetails['FirstName'].' '.$userDetails['LastName'];
$message = 'projectname Order ID '.$verification_code.' picked up on '.$date.' at '.$time.': ';
foreach($smsemailarray as $item){
$message .= $item["Qty"].$item["name"].' ';
}
$message = urlencode($message);
//Send Registration code to user via sms
$apiURL = "http://login.smsindiahub.in/vendorsms/pushsms.aspx?user=" . SMSHUB_USERNAME . "&password=" . SMSHUB_PASSWORD . "&msisdn=" . $mobile_number . "&sid=" . SMSHUB_SENDERID . "&msg=" . $message . "&fl=" . SMSHUB_FLAG . "&gwid=" . SMSHUB_GWID;
// Initiate curl
$ch = curl_init();
// Set The Response Format to Json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL, $apiURL);
// Execute
$result = curl_exec($ch);
echo"<pre>";print_R($result);die;
// Closing
curl_close($ch);
return $result;
}
return false;
}
it print a result as below :
{"ErrorCode":"24","ErrorMessage":"Invalid template or template mismatchInvalid template or template mismatch","JobId":null,"MessageData":null}
I am not understand where is fault,can any one help me to resolve it?
Please check it in your smsindiahub panel. Please check the status of your template. Make sure that, your template is approved and not pending.
Thanks

Magento & Hubspot - Submitting Form on Success Page

I'm trying to submit a form to Hubspot on the success page of Magento. I confirmed already that the variable $str_post contains all of the info that's needed. Unfortunately, I can't determine why $response is empty. It seems like the CURL connection is not being made but I can't seem to determine why. Is there something I need to do to trigger the CURL connection other than just loading the page?
Please note I've removed the GUI/Form ID from the URL.
<?php
//Process a new form submission in HubSpot in order to create a new Contact.
$hubspotutk = $_COOKIE['hubspotutk']; //grab the cookie from the visitors browser.
$ip_addr = $_SERVER['REMOTE_ADDR']; //IP address too.
$hs_context = array(
'hutk' => $hubspotutk,
'ipAddress' => $ip_addr,
'pageUrl' => 'https://www.myfoodstorage.com/onestepcheckout/',
'pageTitle' => 'MyFoodStorage.com Cart Checkout'
);
$hs_context_json = json_encode($hs_context);
//Need to populate these varilables with values from the form.
$str_post = "firstname=" . urlencode($firstname)
. "&lastname=" . urlencode($lastname)
. "&email=" . urlencode($email)
. "&phone=" . urlencode($telephone)
. "&address=" . urlencode($street)
. "&city=" . urlencode($city)
. "&state=" . urlencode($region)
. "&country=" . urlencode($country)
. "&hs_context=" . urlencode($hs_context_json); //Leave this one be :)
//replace the values in this URL with your portal ID and your form GUID
$endpoint = 'https://forms.hubspot.com/uploads/form/v2/GUI-ID/FORM-ID';
$ch = #curl_init();
#curl_setopt($ch, CURLOPT_POST, true);
#curl_setopt($ch, CURLOPT_POSTFIELDS, $str_post);
#curl_setopt($ch, CURLOPT_URL, $endpoint);
#curl_setopt($ch, CURLOPT_HTTPHEADER, array('application/x-www-form-urlencoded'));
#curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = #curl_exec($ch); //Log the response from HubSpot as needed.
#curl_close($ch);
echo $response;
?>
A successful submission to the Forms API will return a 204 (No Content) response, so there would be nothing in the body of the response. You can get the status code using curl_getinfo.
$response = #curl_exec($ch); //Log the response from HubSpot as needed.
echo #curl_getinfo($ch, CURLINFO_HTTP_CODE);
#curl_close($ch);
echo $response;

Categories