I've created a web page that uses Javascript and PHP to send email after inserting a valid email address into a form.
Form executes a validation of the mail inserted and shows a popup if there is some error or if the sending fails. It works correctly.
A green popup should be shown if everything goes well, but it does not happen. Mail is sent and I see the following error (if I use the #button-send form):
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Here is the code:
PHP
<?php
require 'mandrill.php';
$send_email_to = "contacts#email.it";
$email_subject = "Feedback landing page";
function send_email($email)
{
global $send_email_to;
global $email_subject;
$headers = "MIME-Version: 1.0" . "rn";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "rn";
$headers .= "From: ".$email. "rn";
$message = "<strong>Email = </strong>".$email."<br>";
try{
$mandrill = new Mandrill("mandrillcode");
//this is not useful
/*$message = array(
'html' => '<p><strong>Email = </strong>'.$email.'</p>',
'text' => 'Example text content',
'subject' => 'Feedback landing page ',
'from_email' => $email,
'from_name' => $email,
'to' => array(
array(
'email' => 'contacts#email.it',
'name' => 'Recipient Name',
'type' => 'to'
)
)
);
$result = $mandrill->messages->send($message, $async, $ip_pool, $send_at);
print_r($result); */
$template_name = 'autoresponder';
$template_content = array(
array(
'name' => 'example name',
'content' => 'example content'
)
);
$message = array(
'html' => '<p>this is a test message with Mandrills PHP wrapper!</p>',
'subject' => 'Feedback email',
'from_email' => 'contacts#email.it',
'to' => array(
array(
'email' => $email,
'name' => 'Recipient 1'
)
),
'merge_vars' => array(
array(
'rcpt' => $email,
'vars' => array(
array(
'name' => 'merge2',
'content' => 'merge2 content'
)
)
)
)
);
print_r($mandrill->messages->sendTemplate($template_name, $template_content, $message));
return true;
}
catch(Mandrill_Error $e) {
// Mandrill errors are thrown as exceptions
echo 'A mandrill error occurred: ' . get_class($e) . ' - ' . $e->getMessage();
// A mandrill error occurred: Mandrill_Unknown_Subaccount - No subaccount exists with the id 'customer-123'
throw $e;
}
}
function validate($email)
{
$return_array = array();
$return_array['success'] = '1';
$return_array['email_msg'] = '';
if($email == '')
{
$return_array['success'] = '0';
$return_array['email_msg'] = 'inserire email';
}
else
{
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email)) {
$return_array['success'] = '0';
$return_array['email_msg'] = 'inserire email valida';
}
}
return $return_array;
}
$email = $_POST['email'];
$return_array = validate($email);
if($return_array['success'] == '1')
{
send_email($email);
}
header('Content-type: text/json');
echo json_encode($return_array);
die();
?>
JS
$(document).ready(function(){
$('#button-send').click(function(event){
event.preventDefault();
$.ajax({
type: 'POST',
url: 'send_form_email.php',
data: $('#email-form').serialize(),
dataType: "json",
success: function(html) {
if(html.success == '1')
{
console.log("#button-send-1 html.success 1");
$('.formdone').show("slow").delay(5000).hide("slow");
}
else
{
console.log("#button-send-1 html.success not 1");
$('.formfail').show("slow").delay(5000).hide("slow");
}
console.log("success");
},
error: function(XMLHttpRequest, textStatus, errorThrown){
console.log("#button-send-1 not html.success");
console.log("textStatus = "+textStatus);
console.log("XMLHttpRequest= "+XMLHttpRequest);
console.log("errorThrown= "+errorThrown);
}
});
});
$('#button-send-2').click(function(event){
event.preventDefault();
$.ajax({
type: 'POST',
url: 'send_form_email.php',
data: $('#email-form-2').serialize(),
success: function(html) {
if(html.success == '1')
{
console.log("#button-send-2 html.success 1");
$('.formdone2').show("slow").delay(5000).hide("slow");
}
else
{
console.log("#button-send-2 html.success not 1");
$('.formfail2').show("slow").delay(5000).hide("slow");
}
console.log("#button-send-2 success");
},
error: function(){
console.log("#button-send-2 not html.success");
}
});
});
});
EDIT:
I've added error_reporting(E_ALL); in php file and I've seen that there are some variables not initialized. In particular $async $ip_pool $send_at. I' ve added the following:
$async = false;
$ip_pool = null;
$send_at = null;
before
$result = $mandrill->messages->send($message, $async, $ip_pool, $send_at);
but nothing changes. Looking at the php error log of my provider no new errors on php are present.
I've also noticed that the first send is not useful $mandrill->messages->send($message, $async, $ip_pool, $send_at);. Only the second is needed. I've removed the first but nothing changes.
CORRECT CODE:
<?php
error_reporting(E_ALL);
require 'mandrill.php';
$send_email_to = "contacts#docgem.it";
$email_subject = "Feedback landing page DocGem";
function send_email($email)
{
global $send_email_to;
global $email_subject;
$headers = "MIME-Version: 1.0" . "rn";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "rn";
$headers .= "From: ".$email. "rn";
$message = "<strong>Email = </strong>".$email."<br>";
try{
$mandrill = new Mandrill("mfSC_K7XBO8Kj5nW0VobjQ");
$template_name = 'docgem autoresponder';
$template_content = array(
array(
'name' => 'example name',
'content' => 'example content'
)
);
$message = array(
'html' => '<p>this is a test message with Mandrills PHP wrapper!</p>',
'subject' => 'Feedback landing page DocGem',
'from_email' => 'contacts#docgem.it',
'to' => array(
array(
'email' => $email,
'name' => 'Recipient 1'
)
),
'merge_vars' => array(
array(
'rcpt' => $email,
'vars' => array(
array(
'name' => 'merge2',
'content' => 'merge2 content'
)
)
)
)
);
json_encode($mandrill->messages->sendTemplate($template_name, $template_content, $message));
return true;
}
catch(Mandrill_Error $e) {
// Mandrill errors are thrown as exceptions
echo 'A mandrill error occurred: ' . get_class($e) . ' - ' . $e->getMessage();
// A mandrill error occurred: Mandrill_Unknown_Subaccount - No subaccount exists with the id 'customer-123'
throw $e;
}
}
function validate($email)
{
$return_array = array();
$return_array['success'] = '1';
$return_array['email_msg'] = '';
if($email == '')
{
$return_array['success'] = '0';
$return_array['email_msg'] = 'inserire email';
}
else
{
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email)) {
$return_array['success'] = '0';
$return_array['email_msg'] = 'inserire email valida';
}
}
return $return_array;
}
$email = $_POST['email'];
$return_array = validate($email);
if($return_array['success'] == '1')
{
send_email($email);
}
header('Content-type: text/json');
echo json_encode($return_array);
?>
in JSON related outputs specially when it is going to be read by javascript you need to use error reporting desabled, and also remove the die(); after the echo json_encode...
<?php
error_reporting(0);
...
...
...
header('Content-Type:application/json;');
echo json_encode($return_array);
Related
I have some code like this in my controller "UserController.php" to export from the model database to CSV.
when I use die dump dd($id,$performance); data that I want to export its looks fine...
die dump img
but when I click the export button, it didn't work
the button code
<span data-href="{{ route('user/export', $user->id) }}" id="export" class="btn btn-success btn-sm" onclick="exportTasks(event.target);">Export</span>
the javascript
<script>
function exportTasks(_this) {
let _url = $(_this).data('href');
window.location.href = _url;
}
</script>
my controller export method
public function exportCsv(Request $request , User $user)
{
$date = \Carbon\Carbon::today();
$id = $request->id;
$performance = Performance::where('user_id', '=', $id)
->get();
$count = 1;
$fileName = 'performance.csv';
$headers = array(
"Content-type" => "text/csv",
"Content-Disposition" => "attachment; filename=$fileName",
"Pragma" => "no-cache",
"Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
"Expires" => "0"
);
$columns = array('No', 'User_ID', 'Username', 'No Order', 'Update Status','Tanggal');
$callback = function() use($performance, $columns) {
$file = fopen('php://output', 'w');
fputcsv($file, $columns);
foreach ($performance as $pr) {
$row['No'] = $count++;
$row['User_ID'] = $pr->user_id;
$row['ID_Moban'] = $pr->id_moban;
$row['Username'] = $pr->user_name;
$row['No Order'] = $pr->no_order;
$row['Update Status'] = $pr->update_status;
$row['Tanggal'] = $pr->created_at;
fputcsv($file, array($row['No'], $row['User_ID'], $row['ID_Moban'], $row['Username'], $row['No Order'], $row['Update Status'], $row['Tanggal']));
}
fclose($file);
};
//dd($id,$performance);
return response()->stream($callback, 200, $headers);
}
my routes
Route::get('user/{id}/export', [UserController::class, 'exportCsv'])->name('user/export');
the error message looks like this
Im having trouble trying to call my function in my Function.php this is the function
enqueue script & localize
function my_enqueue() {
wp_enqueue_script( 'wc_shop', get_template_directory_uri() . '/wc_shop.js', array('') );
wp_localize_script( 'wc_shop', 'a_product_filter',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
the Function thats in function.php that im trying to call that filters product
add_action('wp_ajax_a_product_filter', 'a_product_filter');
add_action('wp_ajax_nopriv_a_product_filter', 'a_product_filter');
function a_product_filter() {
echo "called";
$args = array(
'post_type' => 'product',
'posts_per_page' => 5,
'product_tag' => 'FEMALE' //just for testing without passing a variable
);
// Create the new query
$loop = new WP_Query( $args );
// Get products number
$product_count = $loop->post_count;
// If results
if( $product_count > 0 ) :
echo '<ul class="products">';
// Start the loop
while ( $loop->have_posts() ) : $loop->the_post(); //global $product;
//global $post;
wc_get_template_part( 'content', 'product' );
echo ''.get_the_title($product_id).'';
if (has_post_thumbnail( $loop->post->ID ))
echo get_the_post_thumbnail($loop->post->ID, 'shop_catalog');
else
echo '<img src="'.$woocommerce .'/assets/images/placeholder.png" alt="" width="'.$woocommerce->get_image_size('shop_catalog_image_width').'px" height="'.$woocommerce->get_image_size('shop_catalog_image_height').'px" />';
endwhile;
echo '</ul><!--/.products-->';
else :
_e('No product matching your criteria.');
endif; // endif $product_count > 0
}
this is the call I'm calling from the front end i cant even get the a_product_filter to echo 'called'
function ajax_call_test(){
// data to be sent to the POST request
let _data = {
action : 'a_product_filter',
}
fetch(a_product_filter.ajax_url , {
method: "POST",
body: JSON.stringify(_data),
headers: {"Content-type": "application/json; charset=UTF-8"}
})
.then(response => response.json())
.then(json => console.log(json));
}
I keep getting 400 Bad Request can someone help me and tell me what is wrong with this
Just like what I have stated in the comments, the backend requires you to send a request in normal POST fashion, not in JSON.
So use application/x-www-form-urlencoded as your header and send query string in the body, not JSON.
let _data = { action : 'a_product_filter', product_something: 'value that i want to send to the server'};
fetch(a_product_filter.ajax_url, {
method: 'POST',
body: (new URLSearchParams(_data)).toString(),
headers: { 'Content-type': 'application/x-www-form-urlencoded' }
})
.then(response => response.text())
.then(product_html => document.getElementById('container').insertAdjacentHTML(product_html));
// put the markup created by server and put it inside somewhere in the frontend
Then on the backend, prepare for that request. Here's an untested code that you can use in the server. So that when the front end requests it, your server (the PHP code that will handle the request will give out the markup with the product you want to respond).
Just follow this idea. Create the markup and respond (echo and exit).
add_action('wp_ajax_a_product_filter', 'a_product_filter');
add_action('wp_ajax_nopriv_a_product_filter', 'a_product_filter');
function a_product_filter() {
// $variable = $_POST['product_something'];
$html_markup = _e('No product matching your criteria.');
$args = array(
'post_type' => 'product',
'posts_per_page' => 5,
'product_tag' => 'FEMALE' //just for testing without passing a variable
);
$loop = new WP_Query($args);
if ($loop->found_posts > 0) {
// get template in string
ob_start();
wc_get_template_part('content', 'product');
$template = ob_get_contents();
ob_end_clean();
$html_markup = '<ul class="products">';
foreach ($loop->get_posts() as $post) {
$html_markup .= '<li>'; // initialize list item
$html_markup .= $template; // add the template
$html_markup .= '' . get_title($post->ID). ''; // link and title
$html_markup .= has_post_thumbnail( $loop->post->ID) ? get_the_post_thumbnail($post->ID, 'shop_catalog'); : '<img src="placeholder.jpg" />' ; // image of product
$html_markup .= '</li>'; // end list item
}
$html_markup .= '</ul>';
}
echo $html_markup;
exit;
}
I have a gridview in which there also a checkbox.
<?= Html::a('Disconnect', ['dco'], ['class' => 'btn btn-success', 'id'=>'dco']) ?>
<?= Html::a('Connect', ['rco'], ['class' => 'btn btn-info','id'=>'rco']) ?>
<?php Pjax::begin(); ?>
<div class="pre-scrollable">
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d) {
return ['value' => $d['msn']];
}],
'customer_id',
'dept_name:ntext',
'sub_div_name',
'division_name',
'allowed_units',
'msn',
'units_consumed',
[
'label' => 'Disconnected',
'attribute' => 'disconnected',
'format'=>'raw',
'contentOptions' => ['style'=>'text-align:center'],
'value' => function($model){
return $model->disconnected == 1 ? '<span class="glyphicon glyphicon-ok text-success"></span>' : '<span class="glyphicon glyphicon-remove text-danger"></span>';
},
'filter' => Html::activeDropDownList($searchModel, 'disconnected', [''=>'All','1'=>'Yes','0'=>'No'], ['class' => 'form-control']),
],
'active_energy_total_m',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
I am using ajax for sending checked data to the controller.
There is two buttons Disconnect and Connect. On the checkbox checked and after clicking any of the two buttons, the corresponding selected item will be connected or disconnected.
$DCOurl = Url::toRoute(['/hescolog/dco']);
$RCOurl = Url::toRoute(['/hescolog/rco']);
$(document).ready(function () {
//DCO
$('#dco').on('click',function(e) {
e.preventDefault();
var strValue = "";
$('input[name="selection[]"]:checked').each(function() {
if(strValue!=="")
{
strValue = strValue + " , " + this.value;
}
else
strValue = this.value;
});
// alert(strValue);
$.ajax({
url: '$DCOurl',
type: 'POST',
dataType: 'json',
data: {data:strValue},
success: function(data) {
alert(data);
}
});
});
$('#rco').on('click',function(e) {
e.preventDefault();
var strValue = "";
$('input[name="selection[]"]:checked').each(function() {
if(strValue!=="")
{
strValue = strValue + " , " + this.value;
}
else
strValue = this.value;
});
// alert(strValue);
$.ajax({
url: '$RCOurl',
type: 'POST',
dataType: 'json',
data: {data:strValue},
success: function(data) {
alert(data);
}
});
});
});
Controller
if(Yii::$app->request->isAjax && Yii::$app->request->post())
{
$data = explode(',',$_POST['data']);
foreach($data as $value)
{
//...... other code
}
}
Now the problem I am facing is when I check all the checkboxes and click on any of the buttons, only the 1st checkbox checked an item is connect or disconnect.
Although while checking the controller `` I can see both the items against checkbox checked.
array(2) { [0]=> string(13) "002995000100 " [1]=> string(13) " 002992002018" }
Update 1
Against these two buttons, I have a SOAP service
if(Yii::$app->request->isAjax && Yii::$app->request->isPost)
{
$data = explode(',',$_POST['data']);
foreach($data as $value)
{
$ic++;
$msn = $value;
$xml_post_string = /** #lang text */
'<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:soap="http://soap.inf.hexing.cn">
<soapenv:Header/>
<soapenv:Body>
<soap:doCommand>
<!--Optional:-->
<arg0><![CDATA[<?xml version="1.0" encoding="utf-8"?>
<RequestMessage
xmlns="http://iec.ch/TC57/2011/schema/message"
xmlns:m="http://iec.ch/TC57/2011/EndDeviceControls#"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://iec.ch/TC57/2011/schema/message
Message.xsd">
<Header>
<Verb>create</Verb>
<Noun>EndDeviceControls</Noun>
<Revision>2.0</Revision>
<Timestamp>2016-01-01T00:00:00+04:30</Timestamp>
<Source>MDM</Source>
<AsyncReplyFlag>true</AsyncReplyFlag>
<ReplyAddress>http://ip:port/AmiWeb/services/Metering</ReplyAddress>
<AckRequired>true</AckRequired>
<User>
<UserID>'.$userName.'</UserID>
</User>
<MessageID>83c643e6-85c5-43c0-9e0a-fa1deb469b72</MessageID>
<CorrelationID>1001</CorrelationID>
<Property>
<Name>password</Name>
<Value>'.$password.'</Value>
</Property>
<Property>
<Name>timeout(m)</Name>
<Value>30</Value>
</Property>
</Header>
<Payload>
<m:EndDeviceControls>
<m:EndDeviceControl>
<m:reason>Disconnect/Reconnect</m:reason>
<m:EndDeviceControlType ref="3.0.211.23"/>
<m:EndDevices>
<m:mRID>'.$msn.'</m:mRID>
<m:Names>
<m:name>Disconnect</m:name>
<m:NameType>
<m:name>ControlType</m:name>
</m:NameType>
</m:Names>
</m:EndDevices>
</m:EndDeviceControl>
</m:EndDeviceControls>
</Payload>
</RequestMessage>
]]></arg0>
</soap:doCommand>
</soapenv:Body>
</soapenv:Envelope>';
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"Content-length: ".strlen($xml_post_string),
); //SOAPAction: your op URL
$url = $soapUrl;
// PHP cURL for https connection
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// converting
$response = curl_exec($ch);
curl_close($ch);
$domd=new DOMDocument();
if(!$domd->loadXML($response)){
throw new \RuntimeException("failed to parse XML!");
}
$inner_xml=$domd->getElementsByTagName("return")->item(0)->textContent;
if(!($domd2=#DOMDocument::loadXML($inner_xml))){
throw new \RuntimeException("failed to parse inner_xml!");
}
$AsyncReplyFlag=$domd2->getElementsByTagName("AsyncReplyFlag")->item(0)->textContent;
if ($AsyncReplyFlag =='true')
{
$ds = 1;
$disconnected_at = date('Y-m-d H:i:s');
try {
Yii::$app->db->createCommand(/** #lang text */
"update
`accurate_mam`.`daily_log`
set
`disconnected` = '$ds',
`diconnected_at` = '$disconnected_at',
`reconnected_at` = NULL
where `msn` = '$msn' ;
")->execute(); //update master table
Yii::$app->db->createCommand(/** #lang text */
"update
`accurate_mam`.`log_disconnected`
set
`disconnected_at` = '$disconnected_at'
where `msn` = '$msn'")->execute();// update log disconnected table
} catch (Exception $e) {
} // updating the master table
}
}
}
I don't know what is the issue and why I am not able to process both the records.
Any help would be highly appreciated.
Because you left a comment here, I used the beginForm method:
in View
<div class="pre-scrollable">
<?php Pjax::begin() ?>
<?=Html::beginForm(['test'],'post');?>
<?= Html::submitButton('Disconnect', ['class' => 'btn btn-success', 'name'=>'dco', 'value'=>'dco', 'id'=>'dco','style'=>'margin:0 10px;']) ?>
<?= Html::submitButton('Connect', ['class' => 'btn btn-primary', 'name'=>'rco', 'value'=>'rco','id'=>'rco']) ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d) {
return ['value' => $d['msn']];
}],
'customer_id',
'dept_name:ntext',
'sub_div_name',
'division_name',
'allowed_units',
'msn',
'units_consumed',
[
'label' => 'Disconnected',
'attribute' => 'disconnected',
'format'=>'raw',
'contentOptions' => ['style'=>'text-align:center'],
'value' => function($model){
return $model->disconnected == 1 ? '<span class="glyphicon glyphicon-ok text-success"></span>' : '<span class="glyphicon glyphicon-remove text-danger"></span>';
},
'filter' => Html::activeDropDownList($searchModel, 'disconnected', [''=>'All','1'=>'Yes','0'=>'No'], ['class' => 'form-control']),
],
'active_energy_total_m',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
<?= Html::endForm();?>
<?php Pjax::end() ?>
</div>
in controllers
public function actionTest()
{
$searchModel = \Yii::createObject(\app\models\TestSearch::className());
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
if ( Yii::$app->request->post() ) {
$arr_select=(array)Yii::$app->request->post('selection'); //An array of selected items (checkbox)
$dco=Yii::$app->request->post('dco'); // submitButton Disconnect
$rco=Yii::$app->request->post('rco'); // submitButton Connect
if ($dco === 'dco') {
//code for Disconnect here ($query)
// example: $modelTest::updateAll(['disconnected' => 1], ['msn' => $arr_select]);
} elseif ($rco == 'rco') {
//code for Connect here ($query)
}
}
return $this->render('test', [
'dataProvider' => $dataProvider,
'searchModel' => $searchModel,
]);
}
You can optimize your code in the controller.
Of course, I think if you use the following method, it is better (a button and ...).
You can easily decide on the controller.
<?= Html::dropDownList('action','',[ 'Connect' =>'Connect','Disconnect' =>'Disconnect'],['prompt' => 'Please select','class'=> 'field-black input-sm']) ?>
<?= Html::submitButton('Apply', ['class' => 'btn btn-success','style'=>'margin:0 10px;']) ?>
You can place the above code instead of the two submitButton. Then decide on the controller according to the dropDownList value. Like below:
also add:, 'data-pjax'=>''
$_action=Yii::$app->request->post('action'); // dropDown
$arr_select=(array)Yii::$app->request->post('selection'); //selected items
Campaign Monitor seems to have updated their code snippets to use a different method of submitting the forms. Now in the <form> tag there's a data-id attribute. None of the usual ways of submitting the forms using Ajax work anymore. Does anybody know how to use Ajax to submit the new style of Campaign Monitor forms?
Here's the code snippet Campaign Monitor gives me:
<form id="subForm" class="js-cm-form" action="https://www.createsend.com/t/subscribeerror?description=" method="post" data-id="A61C50BDC994654B1D79D5719EC1255C09788D1CED7F46D508DAE8944C2CB34BA5EC78954EB81FB5F54AD0716B1F245E696D5CFAF72B819D19DC3B44517">
<p>
<label for="fieldEmail">Email</label>
<br />
<input id="fieldEmail" name="cm-wmpt-wmpt" type="email" class="js-cm-email-input"
required />
</p>
<p>
<button class="js-cm-submit-button" type="submit">Subscribe</button>
</p>
</form>
<script type="text/javascript" src="https://js.createsend1.com/javascript/copypastesubscribeformlogic.js"></script>
I emailed their support, so I can answer the question myself. They've replaced all the old methods with their API. You need to have the form's action set to your own endpoint (e.g. signup.php).
I'm using PHP, so I downloaded their PHP API wrapper from https://github.com/campaignmonitor/createsend-php. A simple example is like this:
require_once 'lib/campaignmonitor/csrest_subscribers.php';
$auth = array(
'api_key' => 'Your API key'
);
$wrap = new CS_REST_Subscribers( 'Your list ID', $auth );
$result = $wrap->add( array(
'EmailAddress' => 'Subscriber email',
'Name' => 'Subscriber name',
'CustomFields' => array(
array(
'Key' => 'Field 1 Key',
'Value' => 'Field Value'
),
array(
'Key' => 'Field 2 Key',
'Value' => 'Field Value'
),
array(
'Key' => 'Multi Option Field 1',
'Value' => 'Option 1'
),
array(
'Key' => 'Multi Option Field 1',
'Value' => 'Option 2'
)
),
'ConsentToTrack' => 'yes',
'Resubscribe' => true
) );
Update: Here's my complete PHP if you're curious:
require_once 'libs/campaignmonitor/csrest_subscribers.php';
$success_message = 'You\'ve been signed up for our email list.';
$error_message_general = 'There was a problem signing you up for the email list. Please try again.';
$error_message_format = 'Please enter a valid email address.';
if ( $_SERVER[ 'REQUEST_METHOD' ] !== 'POST' ) {
renderResponse( true, $error_message_general );
}
else {
$api_key = 'your_api_key_here';
$list_id = 'your_list_id_here';
$email = array_key_exists( 'email', $_POST ) ? $_POST[ 'email' ] : '';
$email = cleanInput( $email );
if ( filter_var( $email, FILTER_VALIDATE_EMAIL ) ) {
try {
$auth = array(
'api_key' => $api_key
);
$wrap = new CS_REST_Subscribers( $list_id, $auth );
$result = $wrap->add( array(
'EmailAddress' => $email,
'ConsentToTrack' => 'yes',
'Resubscribe' => true
) );
if ( $result->was_successful() )
renderResponse( false, $success_message );
else
renderResponse( true, $error_message_general );
}
catch ( Exception $e ) {
renderResponse( true, $error_message_general );
}
}
else {
renderResponse( true, $error_message_format );
}
}
function renderResponse( $error, $message ) {
header( 'Content-Type: application/json' );
$result = [
'error' => $error,
'message' => $message
];
echo json_encode( $result );
die();
}
function cleanInput( $data ) {
$data = trim( $data );
$data = stripslashes( $data );
$data = htmlspecialchars( $data );
return $data;
}
integration payment gateway in asp.net webform based website. sample code documentation examples are in php only.
I am not sure how to go forward as documentation doesnt seem to be of much help
https://telr.com/support/knowledge-base/hosted-payment-page-integration-guide/
<%# Page Language="C#" AutoEventWireup="true" CodeFile="PaymentProcess.aspx.cs" Inherits="PaymentProcess" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<style>
#telr {
width: 100%;
min-width: 600px;
height: 600px;
frameborder: 0;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<p> Enter You Credit Card Details Here</p>
<p><iframe id= " telr " src= " [url obtained from create order] " ></iframe></p>
<div>
</div>
</form>
<script type="text/javascript">
</script>
</body>
</html>
Any help or pointer is appreciated
UPDATE:
I am trying to using HTTPClient for same but i am not sure if i am doing it wring
protected void btn_Click(object sender, EventArgs e)
{
using (var client = new HttpClient())
{
TelrObj obj = new TelrObj();
obj.ivp_method = "create";
obj.ivp_store = 12345;
obj.ivp_cart = "cardid1234";
obj.ivp_test = 1;
obj.return_auth = "xxxx-xxxx-xxx";
obj.return_can = "";
obj.return_decl = "";
obj.ivp_amount = 10;
obj.bill_fname = "David";
obj.ivp_currency = "USD";
var str = "{ 'method':'create', 'order':{ 'ref':'OrderRef', 'cartid':'cardid1234', 'test':1,'amount':10,'currency':'USD', 'url':'https://secure.telr.com/gateway/process.html?o=OrderRef' }";
var response = client.PostAsync("https://secure.telr.com/gateway/order.json",
new StringContent(JsonConvert.SerializeObject(str).ToString(),
Encoding.UTF8, "application/json"))
.Result;
Response.Write(response);
if (response.IsSuccessStatusCode)
{
dynamic content = JsonConvert.DeserializeObject(
response.Content.ReadAsStringAsync()
.Result);
// Access variables from the returned JSON object
var appHref = content.links.applications.href;
}
}
}
RESPONSE
StatusCode: 417, ReasonPhrase: 'Expectation Failed', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Connection: close Date: Tue, 17 Jan 2017 10:52:30 GMT Server: Apache Content-Length: 364 Content-Type: text/html; charset=iso-8859-1 }
I have changed return_auth & ivp_store as i cant share it. Any pointer to do it right would be of great help.
I am confused with there documentation so to do it right way. They dont seem to have any .net example on their website rather they have PHP Plugins which i don't understand.
I found another example for wooCommerce plugin which is in PHP
<?php
if (!defined('ABSPATH')) { exit; } // Exit if accessed directly
if (!defined('WP_CONTENT_URL')) { define('WP_CONTENT_URL', get_option('siteurl').'/wp-content'); }
if (!defined('WP_PLUGIN_URL')) { define('WP_PLUGIN_URL', WP_CONTENT_URL.'/plugins'); }
if (!defined('WP_CONTENT_DIR')) { define('WP_CONTENT_DIR', ABSPATH.'wp-content'); }
if (!defined('WP_PLUGIN_DIR')) { define('WP_PLUGIN_DIR', WP_CONTENT_DIR.'/plugins'); }
function telr_init() {
/**
* __construct function.
*
* #access public
* #return void
*/
class WC_Gateway_Telr extends WC_Payment_Gateway {
public function __construct() {
global $woocommerce;
$this->min_wc_ver="2.3.8";
$this->id = 'telr';
$this->has_fields = false; // No additional fields in checkout page
$this->method_title = __('Telr', 'woocommerce');
$this->method_description = __('Telr Checkout', 'telr-for-woocommerce');
$this->order_button_text = __( 'Proceed to Telr', 'telr-for-woocommerce' );
$this->woocom_ver = $woocommerce->version;
// Load the settings.
$this->init_form_fields(); // Config page fields
$this->init_settings();
if ($this->can_init()) {
$preload='<iframe style="width:1px;height:1px;visibility:hidden;display:none;" src="https://secure.telrcdn.com/preload.html"></iframe>';
$this->enabled = $this->get_config_option('enabled');
$this->title = $this->get_config_option('title');
$this->description = $this->get_config_option('description').$preload;
$this->store_id = $this->get_config_option('store_id');
$this->store_secret = $this->get_config_option('store_secret');
$this->testmode = $this->get_config_option('testmode');
$this->debug = $this->get_config_option('debug');
$this->order_status = $this->get_config_option('order_status');
$this->cart_desc = $this->get_config_option('cart_desc');
$this->form_submission_method = true;
$this->api_endpoint = 'https://secure.telr.com/gateway/order.json';
// Actions
add_action('woocommerce_update_options_payment_gateways_'.$this->id, array($this, 'process_admin_options'));
add_action( 'woocommerce_thankyou', array($this, 'update_order_status'));
} else {
$this->enabled = false;
}
}
private function can_init() {
if (version_compare(PHP_VERSION, '5.5.0') < 0) {
return false;
}
if (!function_exists('curl_version')) { return false; }
if (!function_exists('curl_init')) { return false; }
if (version_compare($this->woocom_ver,$this->min_wc_ver) < 0) {
return false;
}
return true;
}
public function update_order_status($order_id) {
global $woocommerce;
$order = new WC_Order( $order_id );
$order_check = $this->check_order($order_id);
if($order_check) {
$new_status = $this->sorder_status;
if (empty($new_status)) { $new_status="completed"; }
$order->update_status($new_status);
}
}
/**
* Process the payment and return the result.
*
* #access public
* #return array
*/
function process_payment($order_id) {
$order = new WC_Order($order_id);
$result = $this->generate_request($order);
$telr_ref = trim($result['order']['ref']);
$telr_url= trim($result['order']['url']);
if (empty($telr_ref) || empty($telr_url)) {
wc_add_notice('Payment API Failure, Please try again.', 'error');
} else {
update_post_meta( $order_id, '_telr_ref', $telr_ref);
}
return array(
'result' => 'success',
'redirect' => $telr_url,
);
}
public function generate_request($order) {
global $woocommerce;
$order_id = $order->id;
$cart_id = $order_id."_".uniqid();
$cart_desc=trim($this->cart_desc);
if (empty($cart_desc)) { $cart_desc='Order {order_id}'; }
$cart_desc = preg_replace('/{order_id}/i',$order_id,$cart_desc);
$test_mode = ($this->testmode == 'yes') ? 1 : 0;
$return_url = 'auto:'.add_query_arg('utm_nooverride','1',$this->get_return_url($order));
$cancel_url = 'auto:'.$order->get_cancel_order_url();
$data = array(
'ivp_method' => "create",
'ivp_source' => 'WooCommerce '.$woocommerce->version,
'ivp_store' => $this->store_id ,
'ivp_authkey' => $this->store_secret,
'ivp_cart' => $cart_id,
'ivp_test' => $test_mode,
'ivp_amount' => $order->order_total,
'ivp_currency' => get_woocommerce_currency(),
'ivp_desc' => $cart_desc,
'return_auth' => $return_url,
'return_can' => $cancel_url,
'return_decl' => $cancel_url,
'bill_fname' => $order->billing_first_name,
'bill_sname' => $order->billing_last_name,
'bill_addr1' => $order->billing_address_1,
'bill_addr2' => $order->billing_address_2,
'bill_city' => $order->billing_city,
'bill_region' => $order->billing_state,
'bill_zip' => $order->billing_postcode,
'bill_country' => $order->billing_country,
'bill_email' => $order->billing_email,
);
if (is_ssl() && is_user_logged_in()) {
$data['bill_custref'] = get_current_user_id();
}
$response = $this->api_request($data);
return $response;
}
public function check_order($order_id) {
global $woocommerce;
$order_ref = get_post_meta($order_id, '_telr_ref', true);
$data = array(
'ivp_method' => "check",
'ivp_store' => $this->store_id ,
'order_ref' => $order_ref,
'ivp_authkey' => $this->store_secret,
);
$response = $this->api_request($data);
$order_status_arr = array(2,3);
$transaction_status_arr = array('A', 'H');
if (array_key_exists("order", $response)) {
$order_status = $response['order']['status']['code'];
$transaction_status = $response['order']['transaction']['status'];
if ( in_array($order_status, $order_status_arr) && in_array($transaction_status, $transaction_status_arr)) {
return true;
}
}
return false;
}
public function api_request($data) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->api_endpoint);
curl_setopt($ch, CURLOPT_POST, count($data));
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
$results = curl_exec($ch);
curl_close($ch);
$results = json_decode($results,true);
return $results;
}
/* ------------------------------ Admin setting page ------------------------------------------------ */
public function get_config_option($key) {
return $this->get_option($key);
}
public function admin_options() {
if ($this->can_init()) {
$this->show_admin_options();
} else {
$this->not_available();
}
}
public function not_available() {
?>
<div class="inline error"><p><strong><?php _e( 'Gateway Disabled', 'woocommerce' ); ?></strong>: <?php _e( sprintf('Requires WooCommerce %s or later, PHP 5.5 or later, and PHP cURL',$this->min_wc_ver), 'woocommerce' ); ?></p></div>
<?php
}
public function show_admin_options() {
// Admin Panel Options
$configured = true;
if ((empty($this->store_id)) || (empty($this->store_secret))) { $configured=false; }
?>
<h3><?php _e('Telr', 'woocommerce'); ?></h3>
<?php if (!$configured) : ?>
<div id="wc_get_started">
<span class="main"><?php _e('Telr Hosted Payment Page', 'woocommerce'); ?></span>
<span>Telr <?php _e('are a PCI DSS Level 1 certified payment gateway. We guarantee that we will handle the storage, processing and transmission of your customer\'s cardholder data in a manner which meets or exceeds the highest standards in the industry.', 'woocommerce'); ?></span>
<span><br><b>NOTE: </b> You must enter your store ID and authentication key</span>
</div>
<?php else : ?>
<p><?php _e('Telr Hosted Payment Page', 'woocommerce'); ?></p>
<?php endif; ?>
<table class="form-table">
<?php $this->generate_settings_html(); ?>
</table><!--/.form-table-->
<?php
}
// Admin settings fields
function init_form_fields() {
// Initialise Gateway Settings Form Fields
$this->form_fields = array(
'enabled' => array(
'title' => __('Enable/Disable', 'woocommerce'),
'type' => 'checkbox',
'label' => __('Enable Telr', 'woocommerce'),
'default' => 'yes'
),
'title' => array(
'title' => __('Title', 'woocommerce'),
'type' => 'text',
'description' => __('This controls the title which the user sees during checkout.', 'woocommerce'),
'default' => __('Credit/Debit card', 'woocommerce'),
'desc_tip' => true,
),
'description' => array(
'title' => __('Description', 'woocommerce'),
'type' => 'textarea',
'description' => __('This controls the description which the user sees during checkout.', 'woocommerce'),
'default' => __('Pay using a credit or debit card via Telr Secure Payments', 'woocommerce'),
'desc_tip' => true,
),
'cart_desc' => array(
'title' => __('Transaction description', 'woocommerce'),
'type' => 'text',
'description' => __('This controls the transaction description shown within the hosted payment page.', 'woocommerce'),
'default' => __('Your order from StoreName', 'woocommerce'),
'desc_tip' => true,
),
'store_id' => array(
'title' => __('Store ID', 'woocommerce'),
'type' => 'text',
'description' => __('Enter your Telr Store ID.', 'woocommerce'),
'default' => '',
'desc_tip' => true,
'placeholder' => '[StoreID]'
),
'store_secret' => array(
'title' => __('Authentication Key', 'woocommerce'),
'type' => 'text',
'description' => __('This value must match the value configured in the hosted payment page V2 settings', 'woocommerce'),
'default' => '',
'desc_tip' => true,
'placeholder' => '[Authentication Key]'
),
'testmode' => array(
'title' => __('Test Mode', 'woocommerce'),
'type' => 'checkbox',
'label' => __('Generate transactions in test mode', 'woocommerce'),
'default' => 'yes',
'description' => __('Use this whilst testing your integration. You must disable test mode when you are ready to take live transactions')
),
'order_status' => array(
'title' => __('Order Status', 'woocommerce'),
'type' => 'select',
'label' => __('Order status for authorised payments', 'woocommerce'),
'default' => 'processing',
'description' => __('Set the WooCommerce order status that will be used for authorised transations', 'woocommerce'),
'options' => array(
'processing' => __( 'Processing', 'woocommerce' ),
'completed' => __( 'Completed', 'woocommerce' )
)
)
);
}
}
}
if(!function_exists('telr_list_network_plugins')) {
function telr_list_network_plugins() {
if (!is_multisite()) {
return false;
$sitewide_plugins = array_keys((array) get_site_option('active_sitewide_plugins'));
}
if (!is_array($sitewide_plugins)) {
return false;
}
return $sitewide_plugins;
}
}
function add_telr_gateway($methods) {
$methods[] = 'WC_Gateway_Telr';
return $methods;
}
// Add plugin to wordpress/woocommerce
if ((in_array('woocommerce/woocommerce.php', (array)get_option('active_plugins'))) || (in_array('woocommerce/woocommerce.php', (array)telr_list_network_plugins()))) {
add_action('plugins_loaded', 'telr_init', 0);
add_filter('woocommerce_payment_gateways', 'add_telr_gateway');
}
?>
If I use Postman and send a following request to the https://secure.telr.com/gateway/order.json I'm getting HTTP 200:
POST /gateway/order.json HTTP/1.1
Host: secure.telr.com
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache
Postman-Token: 570a44c1-9c4e-58b2-5d4d-fdd352272235
ivp_method=create&ivp_store=12345&ivp_authkey=12345&ivp_cart=12345&ivp_test=1&ivp_amount=100.00&ivp_currency=AED&ivp_desc=Description&return_auth=https%3A%2F%2Fdomain.com%2Freturn.html&return_can=https%3A%2F%2Fdomain.com%2Freturn.html&return_decl=https%3A%2F%2Fdomain.com%2Freturn.html
So I guess you're building your request in a wrong way(especially Content-Type which should be application/x-www-form-urlencoded, not application/json).
I cannot test it more since I don't ivp_store parameter, thus following response appears:
{
"method": "create",
"trace": "4001/18544/587dfa99",
"error": {
"message": "E04:Invalid store ID"
}
}
EDIT:
Here's working example:
static void Main(string[] args)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://secure.telr.com/");
client.DefaultRequestHeaders.ExpectContinue = false;
var result = client.PostAsync("gateway/order.json",
new FormUrlEncodedContent(new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("ivp_method", "create"),
new KeyValuePair<string, string>("ivp_store", "12345"),
new KeyValuePair<string, string>("ivp_authkey", "12345"),
new KeyValuePair<string, string>("ivp_cart", "12345"),
new KeyValuePair<string, string>("ivp_desc", "Desc"),
new KeyValuePair<string, string>("ivp_test", "1"),
new KeyValuePair<string, string>("ivp_amount", "100.00"),
new KeyValuePair<string, string>("ivp_currency", "AED"),
new KeyValuePair<string, string>("return_auth", "https://wwww.google.pl"),
new KeyValuePair<string, string>("return_can", "https://wwww.google.pl"),
new KeyValuePair<string, string>("return_decl", "https://wwww.google.pl"),
})).Result;
Console.WriteLine(result.Content.ReadAsStringAsync().Result);
Console.ReadLine();
}
}
Note following line:
client.DefaultRequestHeaders.ExpectContinue = false;
which is required for this server. If you do not include this line and run my code, you will get following response:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>417 Expectation Failed</title>
</head><body>
<h1>Expectation Failed</h1>
<p>The expectation given in the Expect request-header
field could not be met by this server.
The client sent<pre>
Expect: 100-continue
</pre>
</p><p>Only the 100-continue expectation is supported.</p>
</body></html>
HttpClient by default sends a Expect: 100-continue header, which clearly messes with a server you're trying to connect.