I am trying to pass amount parameters in url from the shortcode. The from and to attributes are working fine but the amount attribute is not working. The output shows the value of 1.
using the shortcode like this:
[exchange_rate from="USD" to="EUR" amount="100"]
function exchange_rate_shortcode($atts) {
$atts = shortcode_atts(array(
'from' => 'AED',
'to' => 'NPR',
'amount' => '1',
), $atts);
$url = "https://api.fastforex.io/convert?from=" . $atts['from'] . "&to=" . $atts['to'] . "&amount=" . $atts['amount'] . "&api_key=xxxx-xxxxx-xxxx";
$result = file_get_contents($url);
$result = json_decode($result, true);
return number_format((float)$result['result']['rate'], 2, '.', '') . " " . $atts['to'];
}
add_shortcode('exchange_rate', 'exchange_rate_shortcode');
Perhaps you somehow wrote the word "amount" wrong and therefore an error occurs. To avoid confusion, use the build_query function.
Your code will look like this:htt
function exchange_rate_shortcode($atts)
{
$atts = shortcode_atts(array(
'from' => 'AED',
'to' => 'NPR',
'amount' => '1',
'api_key' => 'xxxx-xxxxx-xxxx',
), $atts);
// to make sure the correct value type is specified
$atts['amount'] = (float)$atts['amount'];
$url = "https://api.fastforex.io/convert?" . build_query($atts);
$result = file_get_contents($url);
if ( ! empty($result)) {
$result = json_decode($result, true);
return number_format((float)$result['result']['rate'], 2, '.', '') . " " . $atts['to'];
}
return '';
}
add_shortcode('exchange_rate', 'exchange_rate_shortcode');
Related
I'm trying to integrate payzone payment in wordpress and getting some error. I've done some code to take remaining payment after the order is processed via woocommerce..The site takes certain amount via woocommerce payzone plugin and final amount via custom payzone hosted form..The error im getting is below:
"This transaction cannot be processed. The submitted data was rejected for a SECURITY reason: HashDigest does not match."
The merchant detials are correct and working fine with woocommerce but custom integration is giving me errors..I tried but couldnt trackt the error yet! Below is my code to create the hashdigest
public static function calculate_hash_digest($string, $pre_shared_key, $hash_method) {
switch($hash_method) {
case "MD5":
$hash_digest = md5($string);
break;
case "SHA1":
$hash_digest = sha1($string);
break;
case "HMACMD5":
$hash_digest = hash_hmac("md5", $string, $pre_shared_key);
break;
case "HMACSHA1":
$hash_digest = hash_hmac("sha1", $string, $pre_shared_key);
break;
}
return $hash_digest;
}
public static function get_country_code($country_code) {
$code = 826;
switch ($country_code ) {
case 'GB':
$code = 826;
break;
case 'US':
$code = 840;
break;
case 'AU':
$code = 36;
break;
case 'CA':
$code = 124;
break;
default;
$code = 826;
break;
}
return $code;
}
public static function payzone_settings($key) {
$settings = get_option('woocommerce_payzone_settings');
if($key) {
if(array_key_exists($key, $settings)) {
return $settings[$key];
}
}
else {
return $settings;
}
}
public static function generate_string_to_hash(
$merchant_id,
$merchant_password,
$amount,
$country_code,
$order_id,
$transaction_type,
$transaction_date_time,
$callback_url,
$order_description,
$customer_name,
$billing_address_1,
$billing_address_2,
$billing_address_3,
$billing_address_4,
$billing_city,
$billing_state,
$billing_postcode,
$billing_country,
$CV2_mandatory,
$address1_mandatory,
$city_mandatory,
$postcode_mandatory,
$state_mandatory,
$country_mandatory,
$result_delivery_method,
$server_result_url,
$payment_form_displays_result,
$pre_shared_key,
$hash_method,
$billing_email,
$billing_phone
)
{
$return_string = "";
switch($hash_method) {
case "MD5":
$include_pre_shared_key_in_string = true;
break;
case "SHA1":
$include_pre_shared_key_in_string = true;
break;
case "HMACMD5":
$include_pre_shared_key_in_string = false;
break;
case "HMACSHA1":
$include_pre_shared_key_in_string = false;
break;
}
if($include_pre_shared_key_in_string) {
$return_string = "PreSharedKey=" . $pre_shared_key . "&";
}
$return_string .=
"MerchantID=" .
$merchant_id .
"&Password=" .
$merchant_password.
"&Amount=" .
$amount .
"&CurrencyCode=" .
$country_code .
"&EchoAVSCheckResult=true" .
"&EchoCV2CheckResult=true" .
"&EchoThreeDSecureAuthenticationCheckResult=true" .
"&EchoCardType=true" .
"&OrderID=" .
$order_id .
"&TransactionType=" .
$transaction_type .
"&TransactionDateTime=" .
$transaction_date_time .
"&CallbackURL=" .
$callback_url .
"&OrderDescription=" .
$order_description .
"&CustomerName=" .
$customer_name .
"&Address1=" .
$billing_address_1 .
"&Address2=" .
$billing_address_2 .
"&Address3=" .
$billing_address_3.
"&Address4=" .
$billing_address_4.
"&City=" .
$billing_city .
"&State=" .
$billing_state .
"&PostCode=" .
$billing_postcode .
"&CountryCode=" .
$billing_country .
"&EmailAddress=" .
$billing_email .
"&PhoneNumber=" .
$billing_phone .
"&CV2Mandatory=" .
$CV2_mandatory .
"&Address1Mandatory=" .
$address1_mandatory .
"&CityMandatory=" .
$city_mandatory .
"&PostCodeMandatory=" .
$postcode_mandatory .
"&StateMandatory=" .
$state_mandatory .
"&CountryMandatory=" .
$country_mandatory .
"&ResultDeliveryMethod=
".$result_delivery_method."
&ServerResultURL=" .
$server_result_url .
"&PaymentFormDisplaysResult=" .
$payment_form_displays_result.
"&ServerResultURLCookieVariables=" .
"&ServerResultURLFormVariables=" .
"&ServerResultURLQueryStringVariables=";
return $return_string;
}
public static function get_hosted_payment_form_args(
$callback_url,
$server_result_url,
$order_id,
$amount = 0
) {
$order = new WC_Order( $order_id );
$transaction_date_time = date('Y-m-d H:i:s P');
$currency = get_option('woocommerce_currency');
$country_code = self::get_country_code($currency);
$settings = self::payzone_settings();
$mode = $settings['test_mode'];
$merchant_id = $mode == 'yes' ? $settings['test_mid'] : $settings['live_mid'];
$merchant_password = $mode == 'yes' ? $settings['test_password'] : $settings['live_password'];
$pre_shared_key = $settings['pre_shared_key'];
$hash_method = $settings['hash_method'];
$transaction_type = $settings['transaction_type'];
$string_to_hash =
self::generate_string_to_hash(
$merchant_id,
$merchant_password,
$amount,
$country_code ,
$order->get_id(),
$transaction_type,
$transaction_date_time,
$callback_url,
'Rental Remaining Payment for Order '.$order->get_id(),
$order->billing_first_name.' '.$order->billing_last_name,
$order->billing_address_1,
$order->billing_address_2,
'',
'',
$order->billing_city,
$order->billing_state,
$order->billing_postcode,
$country_code,
"true",
"false",
"false",
"false",
"false",
"false",
'POST',
$server_result_url,
'false',
$pre_shared_key ,
$hash_method,
$order->billing_email,
$order->billing_phone
);
return array(
'HashDigest' => self::calculate_hash_digest($string_to_hash , $pre_shared_key, $hash_method),
'MerchantID' => $merchant_id,
'Amount' => (string) $amount,
'CurrencyCode' => (string) $country_code ,
'EchoAVSCheckResult' => "true",
'EchoCV2CheckResult' => "true",
'EchoThreeDSecureAuthenticationCheckResult' => "true",
'EchoCardType' => "true",
'OrderID' => (string) $order->get_id(),
'TransactionType' => $transaction_type,
'TransactionDateTime' => $transaction_date_time,
'CallbackURL' => $callback_url,
'OrderDescription' => 'Rental Remaining Payment for Order '.$order->get_id(),
'CustomerName' => $order->billing_first_name.' '.$order->billing_last_name,
'Address1' => $order->billing_address_1,
'Address2' => $order->billing_address_2,
'Address3' => "",
'Address4' => "",
'City' => $order->billing_city,
'State' => $order->billing_state,
'Postcode' => $order->billing_postcode,
'CountryCode' => (string) $country_code,
'EmailAddress' => $order->billing_email,
'PhoneNumber' => $order->billing_phone,
'CV2Mandatory' => "true",
'Address1Mandatory' => "false",
'CityMandatory' => "false",
'PostCodeMandatory' => "false",
'StateMandatory' => "false",
'CountryMandatory' => "false",
'ResultDeliveryMethod' => 'POST',
'ServerResultURL' => $server_result_url,
'PaymentFormDisplaysResult' => 'false',
'ServerResultURLCookieVariables' => "",
'ServerResultURLFormVariables' => "",
'ServerResultURLQueryStringVariables' => ""
);
}
Any help is really appreciated!!
I'm only using a small part of this function actually but I wanted to post it all to provide the big picture. There is a part of the query in this function that finds recent attachments a user has posted to the forums. The block is on the user profile. IT works but the problem is ... it's VERY slow!! Core attachments locks up for 30+ seconds and makes my site unusable.
Any one who could help it would be much appreciated.
private function getAttImages($limit, $forumIds = 0, $fidsReverse = false, $topicIds = 0, $membersIds = 0, $order = 'attach_date', $sort = 'desc', $group = null)
{
$fids = '';
if ($forumIds)
{
$r = '';
if ($fidsReverse)
{
$r = ' NOT ';
}
if (is_array($forumIds))
{
$forumIds = implode(',', $forumIds);
}
$fids = ' AND forums_topics.forum_id ' . $r . ' IN (' . $forumIds . ')';
}
$tids = '';
if ($topicIds)
{
$tids = ' AND forums_topics.tid IN (' . $topicIds . ')';
}
$mids = '';
if ($membersIds)
{
$mids = ' AND core_attachments.attach_member_id IN (' . $membersIds . ')';
}
$whereT = array();
$joinsT = array();
$findInPosts = ' AND ' . \IPS\Db::i()->findInSet('queued', array('0'));
$joinsT[] = array(
'select' => 'forums_posts.*',
'from' => 'forums_posts',
'where' => array("forums_posts.pid=core_attachments_map.id2" . $findInPosts),
);
$findInTopics = ' AND ' . \IPS\Db::i()->findInSet('approved', array('1'));
$joinsT[] = array(
'select' => 'forums_topics.*',
'from' => 'forums_topics',
'where' => array("forums_topics.tid=forums_posts.topic_id" . $findInTopics . $fids . $tids),
);
$select = 'core_attachments.attach_id AS custom_data, core_attachments.*';
if ($group)
{
$select = 'core_attachments.attach_id AS custom_data, COUNT(attach_is_image) as cnt_images, SUM(attach_hits) as summ_attach_hits, core_attachments.*';
}
$joinsT[] = array(
'select' => $select,
'from' => 'core_attachments',
'where' => array('core_attachments.attach_is_image=1 AND core_attachments.attach_is_archived=0 AND core_attachments.attach_id=core_attachments_map.attachment_id' . $mids),
);
$joinsT[] = array( 'select' => 'core_members.member_id, core_members.member_group_id, core_members.mgroup_others, core_members.name, core_members.members_seo_name',
'from' => 'core_members',
'where' => array('core_attachments.attach_member_id=core_members.member_id' . $mids),
);
$joinsT[] = array( 'select' => 'core_permission_index.perm_id',
'from' => 'core_permission_index',
'where' => array("core_permission_index.app='forums' AND core_permission_index.perm_type='forum' AND core_permission_index.perm_type_id=forums_topics.forum_id"),
);
$groupT = $group;
$whereT[] = array(
"core_attachments_map.location_key='forums_Forums' AND " .
\IPS\Db::i()->findInSet('perm_view', array_merge(array(\IPS\Member::loggedIn()->member_group_id), array_filter(explode(',', \IPS\Member::loggedIn()->mgroup_others)))) . " OR perm_view='*'" .
$fids . $tids . $mids
);
$table = new \IPS\Helpers\Table\Db(
'core_attachments_map',
\IPS\Http\Url::internal('app=core&module=system&controller=nbattachpictures', 'front', 'nbattachpictures'),
$whereT,
$groupT
);
$table->joins = $joinsT;
$table->limit = $limit;
$table->sortBy = $order;
$table->sortDirection = $sort;
$table->rowsTemplate = array(\IPS\Theme::i()->getTemplate('plugins', 'core', 'global'), 'nbAttachmentsBlocksRows');
$table->parsers = array(
'custom_data' => function( $val, $row )
{
return array(
'topic_data' => \IPS\Http\Url::internal("app=forums&module=forums&controller=topic&id={$row['tid']}", 'front', 'forums_topic', array($row['title_seo'])),
'summ_attach_hits' => $row['summ_attach_hits'],
'jewel' => $this->attachJewel($row['summ_attach_hits']),
);
},
);
return $table;
}
I have a and Array which looks like this:
$sms = array(
'from' => 'DummyFrom',
'to' => '+46709751949',
'message' => 'Hello hello!'
);
echo sendSMS ($sms) . "\n";
what i'm trying to do is to put this array within a foreach loop so it can be executed multiple time (based on the given times from mysql database). to explain it better, I did something like this:
if (is_array($g_numbers)) {
foreach ($g_numbers as $number) {
$sms = array(
'from' => 'DummyFrom',
'to' => "" . $number . "",
'message' => 'Hello hello!'
);
echo sendSMS($sms) . "\n";
}
}
but that is wrong and its stops the PHP page to execute properly without any errors!
Could someone please advise on this issue?
My full code :
<?php
$people = array();
$sql = "SELECT id, g_name, numbers FROM groups WHERE g_name='$groups'";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$g_id = $row['id'];
$g_name = $row['g_name'];
$g_numbers = $row['numbers'];
$people[$g_numbers] = $g_numbers;
}
?>
<?
// Example to send SMS using the 46elks service
// Change $username, $password and the mobile number to send to
function sendSMS($sms)
{
// Set your 46elks API username and API password here
// You can find them at https://dashboard.46elks.com/
$username = 'xxxxxxxxxxxxxxxxxxxxxxxx';
$password = 'xxxxxxxxxxxxxxxxxxxxxxxx';
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => "Authorization: Basic " . base64_encode($username . ':' . $password) . "\r\n" . "Content-type: application/x-www-form-urlencoded\r\n",
'content' => http_build_query($sms),
'timeout' => 10
)
));
$response = file_get_contents('https://api.46elks.com/a1/SMS', false, $context);
if (!strstr($http_response_header[0], "200 OK"))
return $http_response_header[0];
return $response;
}
if (is_array($g_numbers)) {
foreach ($g_numbers as $number) {
$sms = array(
'from' => 'DummyFrom',
/* Can be up to 11 alphanumeric characters */
'to' => "" . $number . "",
/* The mobile number you want to send to */
'message' => 'Hello hello!'
);
echo sendSMS($sms) . "\n";
}
}
?>
This will work because tables values are stored in $people:
if (is_array($people)) {
foreach ($people as $number) {
$sms = array(
'from' => 'DummyFrom',
/* Can be up to 11 alphanumeric characters */
'to' => "" . $number . "",
/* The mobile number you want to send to */
'message' => 'Hello hello!'
);
echo sendSMS($sms) . "\n";
}
}
I have the following code:
static function getContext($data) {
// use key 'http' even if you send the request to https://...
$options = array (
'http' => array (
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query ( $data )
)
);
return stream_context_create ( $options );
}
static function addEmailsToRecipientList($name, $emails) {
$url = 'https://sendgrid.com/api/newsletter/lists/email/add.json';
$temp = array();
foreach($emails as $email){
$temp[] = array('email' => $email, 'name' => 'unknown');
}
$data = array (
'list' => $name,
'data' => json_encode($temp),
'api_user' => $api_user_name,
'api_key' => $api_password
);
$context = SendGridAPI::getContext ( $data );
return file_get_contents ( $url, false, $context );
}
When I pass to addEmailsToRecipientList a name of an existing list and an array of email addresses that I want to add to it, I get an error 500 (internal server error).
Adding a single email ($temp = array('email' => $email, 'name' => 'unknown')) works fine.
What am I doing wrong?
Thanks a lot!
Solved it! :)
//listname: the name of an existing recipients list
//$emails: an array of emails
static function addEmailsToRecipientList($listname, $emails){
$username= 'sendgrid_username';
$password= 'sendgrid_password';
$url = 'https://sendgrid.com/api/newsletter/lists/email/add.json?api_user='.$username.'&api_key='.$password;
$str= '&list=' . $listname;
for ($i=0;$i<count($emails);$i++) {
$str.= '&data[]={"email":"'.$emails[$i] . '","name":"unknown'. $i .'"}';
}
return file_get_contents($url . $str);
}
The scripts with a some touchs works very fine, i add the urlencode, the json_decode and simulated name for the email.
$url = 'https://sendgrid.com/api/newsletter/lists/email/add.json?api_user='.$username.'&api_key='.$password;
$str= '&list=' . $listname;
foreach ($data as $email) {
$attributes = explode("#", $email);
$str.= '&data[]=';
$str.= urlencode('{"email":"'. $email . '","name":"'. ucfirst($attributes[0]) .'"}');
}
$results = file_get_contents($url . $str);
$results = json_decode($results, TRUE);
return (isset($results['inserted'])) ? $results['inserted'] : 0;
I'm trying to pass variable to the view and this one is very weird as the naming and directory structure is correct. Below is the function in my controller:
public function validate_apply_link(){
App::uses('CakeEmail', 'Network/Email');
$this->layout = 'blank';
$listings = $this->CareersAndJob->query("
SELECT l.sid, l.title, lp.value, u.CompanyName, u.WebSite
FROM listings l
LEFT JOIN listings_properties lp
ON lp.object_sid = l.sid
LEFT JOIN users u
ON u.sid = l.user_sid
WHERE l.active = 1
AND lp.add_parameter = 2
AND l.JobGateSenderReference IS NULL
AND u.CompanyName != 'AECOM'
ORDER BY u.CompanyName ASC
LIMIT 5
");
$doc = new DOMDocument();
ob_start();
$listing_count = count($listings);
echo nl2br("Checking $listing_count active jobs...\n\n");
$i=0;
foreach($listings as $listing){
$sid = $listing['l']['sid'];
$url = $listing['lp']['value'];
$company_name = $listing['u']['CompanyName'];
$title = htmlspecialchars($listing['l']['title']);
$length = strpos($title, "-");
if($length != 0){
$title = substr($title, 0, $length-1);
}
$title = substr($title, 0, $length-1);
$title = substr($title, 0, 10);
$data = $this->curl($url);
$check_pdf = strpos($data['info']['content_type'], "pdf");
if($check_pdf != false){
$outputs['data'][$i]['url'] = $url;
$outputs['data'][$i]['sid'] = $sid;
$outputs['data'][$i]['title'] = $title;
$outputs['data'][$i]['company_name'] = $company_name;
$outputs['data'][$i]['our_link'] = "http://careersandjobs.com.au/display-job/{$sid}";
$outputs['data'][$i]['content_type'] = $data['info']['content_type'];
$outputs['data'][$i]['data_type'] = 'pdf';
$i++;
continue;
}
#$doc->loadHTML($data['results']);
$html = $doc->saveHTML();
$xpath = new DOMXpath($doc);
$body = $doc->getElementsByTagName('body')->item(0);
$parsed_url = parse_url($url);
switch($parsed_url['host']){
case "www.michaelpage.com.au":
parse_str($url);
$exist = $xpath->query("//*[contains(#value,'{$ref}')]");
break;
case "https://vacancies.mackay.qld.gov.au":
parse_str($url);
$exist = $xpath->query("//*[contains(#value,'{$title}')]");
break;
default:
$exist = $xpath->query("//*[contains(text(),'{$title}')]");
break;
}
if($exist->length == 0){
if(strpos($url, '#') == false){
$outputs['data'][$i]['url'] = $url;
$outputs['data'][$i]['sid'] = $sid;
$outputs['data'][$i]['title'] = $title;
$outputs['data'][$i]['company_name'] = $company_name;
$outputs['data'][$i]['our_link'] = "http://careersandjobs.com.au/display-job/{$sid}";
$outputs['data'][$i]['content_type'] = $data['info']['content_type'];
$response_code = $this->http_response_codes($data['info']['http_code']);
$outputs['data'][$i]['response_code'] = $response_code;
$outputs['data'][$i]['data_type'] = 'title_not_found';
}else{
$outputs['data'][$i]['data_type'] = 'no_iframe';
}
$i++;
}
flush();
ob_flush();
}
$this->set(compact('outputs'));
}
I can do pr on the outputs variable in the view but this outputs to NULL but when I delete the entire bunch of code inside the controller function and just pass a test variable through it works.
Is there something wrong with the function that I am not aware of?
No errors were found in the above function by the way
app/Controller/CareersAndJobsController.php (line 1048)
array(
'data' => array(
(int) 0 => array(
'url' => 'http://bawbawshire.currentjobs.com.au/cvbuilder/apply+for+this+job/no/1225055',
'sid' => '3649',
'title' => 'Graduate P',
'company_name' => 'Baw Baw Shire Council',
'our_link' => 'http://careersandjobs.com.au/display-job/3649',
'content_type' => 'text/html; charset=utf-8',
'response_code' => 'OK',
'data_type' => 'title_not_found'
),
(int) 1 => array(
'url' => 'http://bawbawshire.currentjobs.com.au/cvbuilder/apply+for+this+job/no/1225724',
'sid' => '3726',
'title' => 'Program &a',
'company_name' => 'Baw Baw Shire Council',
'our_link' => 'http://careersandjobs.com.au/display-job/3726',
'content_type' => 'text/html; charset=utf-8',
'response_code' => 'OK',
'data_type' => 'title_not_found'
),
(int) 2 => array(
'url' => 'http://bawbawshire.currentjobs.com.au/cvbuilder/apply+for+this+job/no/1225826',
'sid' => '3727',
'title' => 'Road Netwo',
'company_name' => 'Baw Baw Shire Council',
'our_link' => 'http://careersandjobs.com.au/display-job/3727',
'content_type' => 'text/html; charset=utf-8',
'response_code' => 'OK',
'data_type' => 'title_not_found'
)
)
)
This is what I am getting from outputs variable just before it gets set by the set function in controller
Any reason you chose to use CakePHP? Because you seem to not make use of its functionality!
You're using literal SQL queries, therefore basically skipping the Models functionality.
You're outputting your content from your Controller? Be careful when using output buffering, this may conflict with CakePHP's inner workings, which also relies on output buffering in many cases. Because you're already outputting the content here (ob_flush()), you'll be outputting your content before your View is reached..
Normally I would point to specific points in the manual, however, because there's so much wrong here, I would suggest to start reading at the beginning