I have a class in php that sends push notification to android/IOS users of the app through web. Now I need to add emoji's to title/body of the push notification payload, but no luck doing so.
I've already tried convert encoding to UTF-8, I've tried using this library and I've tried replacing \\ to \ (json_encode function adds \\ instead of \ on e.g \xC2\xA9 becomes \\xC2\\xA9).
Here's my code :
public function sendPush($payload)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->base_url . "/push");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers[] = 'Content-Type: application/json';
$headers[] = 'X-AUTH-TOKEN: 94h4f5RCDSEYKYqXDHTk';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
That's push function, and here's the .tpl where I get the data from web.
<?php
include(SITE_ROOT . '/core/admin/logo.class.php');
if (isset($_POST['push-button'])) {
if (
isset($_POST['push-title'])
&& isset($_POST['push-body'])
&& isset($_POST['push-city'])
&& isset($_POST['push-url'])
&& isset($_POST['push-platform'])
) {
$push = new Push();
$title = $_POST['push-title'];
$body = $_POST['push-body'];
$url = $_POST['push-url'];
$platform = $_POST['push-platform'];
$cities = $_POST['push-city'];
$payload = [
'title' => $title,
'body' => $body,
'url' => $url,
'cities' => [
$cities
]
];
if ($platform === 'all') {
$responses_ios = json_decode($push->sendPush($payload), true);
$responses_android = json_decode($push->sendPushAndroid($payload), true);
} elseif ($platform === 'ios') {
$responses_ios = json_decode($push->sendPush($payload), true);
} elseif ($platform === 'android') {
$responses_android = json_decode($push->sendPushAndroid($payload), true);
}
// $devices = '';
// var_dump($responses);
// foreach ($responses_ios as $response) {
// $devices .= $response . "<br>";
// }
$message = '<span class="message"><strong>PUSH-notiser har skickats</strong></span>';
unset($_SESSION['message']);
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>PUSH - Administration</title>
<?php include(SITE_ROOT . '/views/admin/meta.tpl'); ?>
</head>
<body class="page-admin">
<?php include(SITE_ROOT . '/views/admin/header.tpl'); ?>
<?php include(SITE_ROOT . '/views/admin/navigation.tpl'); ?>
<p class="shoutout p-45 text-center">Skicka PUSH-meddelanden till användare i en stad</p>
<?php echo $message; ?>
<section class="wrapper">
<section class="container centered">
<section class="col-3-5">
<form method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<section class="row">
<span class="input-title">Välj stad</span>
<span class="input-field">
<select name="push-city">
<option value="all">Alla</option>
<?php
$cities = $app->get_page_list('city');
foreach ($cities as $city) {
echo '<option value=' . $city['page_name'] . ' />' . $city['page_name'] . '</option>';
}
?>
</select>
</span>
</section>
<section class="row">
<span class="input-title">Titel</span>
<span class="input-field">
<input type="text" name="push-title" class="slug" placeholder="Titel på meddelande"
required/>
</span>
</section>
<section class="row">
<span class="input-title">Meddelande</span>
<span class="input-field">
<textarea name="push-body" class="slug" placeholder="Meddelande" required></textarea>
</span>
</section>
<section class="row">
<span class="input-title">URL</span>
<span class="input-field">
<input type="text" name="push-url" class="slug" placeholder="URL att skicka med" required/>
</span>
</section>
<section class="row">
<span class="input-title">Plattform</span>
<span class="input-field">
<input type="radio" name="push-platform" class="slug"
placeholder="Välj plattform att skicka till"
value="all" checked required/>Alla
<input type="radio" name="push-platform" class="slug"
placeholder="Välj plattform att skicka till"
value="ios" required/>iOS
<input type="radio" name="push-platform" class="slug"
placeholder="Välj plattform att skicka till"
value="android" required/>Android
</span>
</section>
<section class="row" style="margin-top: 2rem;">
<input type="submit" class="button-large-2 button-no-g" name="push-button"
value="Skicka PUSH-notis"/>
</section>
</form>
</section>
</section>
</section>
<?php include(SITE_ROOT . '/views/admin/emoji.tpl'); ?>
<?php include(SITE_ROOT . '/views/admin/footer.tpl'); ?>
</body>
</html>
Here's what I get from echo/var_dump on title/body
string(13) "test \xC2\xA9" string(13) "test \xC2\xA9"
Those 2 \xC2\xA9 should be copyright signs.
Related
I am trying to search and get youtube videos on my webpage. but have some error want your help what to do know.
HTML code is:
<h2>Search Videos by keyword using YouTube Data API V3</h2>
<div class="search-form-container">
<form id="keywordForm" method="post" action="">
<div class="input-row">
Search Keyword : <input class="input-field" type="search"
id="keyword" name="keyword"
placeholder="Enter Search Keyword">
</div>
<input class="btn-submit" type="submit" name="submit"
value="Search">
</form>
</div>
Now moving to the PHP code where I used iframe for the video title and use my own created API from the developer account. But when I run the code I get an error about MAX_RESULT.
and the PHP code and youtube API is here:
<?php
if (isset($_POST['submit']) )
{
$keyword = $_POST['keyword'];
if (empty($keyword))
{
$response = array(
"type" => "error",
"message" => "Please enter the keyword."
);
}
}
?>
<?php
if(!empty($response)) {
?>
<div class="response <?php echo $response["type"]; ?>
">
<?php echo $response["message"]; ?>
</div>
<?php
}
?>
<?php
if (isset($_POST['submit']) )
{
if (!empty($keyword))
{
$apikey = 'AIzaSyAjowKxG2mRdr7p1N-3RtBd-BWAgjbf87g';
$googleApiUrl = 'https://www.googleapis.com/youtube/v3/search?part=snippet&q=' . $keyword . '&maxResults=' . MAX_RESULTS . '&key=' . $apikey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $googleApiUrl);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response);
$value = json_decode(json_encode($data), true);
?>
<div class="result-heading">About <?php echo MAX_RESULTS; ?> Results</div>
<div class="videos-data-container" id="SearchResultsDiv">
<?php
for ($i = 0; $i < MAX_RESULTS; $i++) {
$videoId = $value['items'][$i]['id']['videoId'];
$title = $value['items'][$i]['snippet']['title'];
$description = $value['items'][$i]['snippet']['description'];
?>
<div class="video-tile">
<div class="videoDiv">
<iframe id="iframe" style="width:100%;height:100%" src="//www.youtube.com/embed/<?php echo $videoId; ?>"
data-autoplay-src="//www.youtube.com/embed/<?php echo $videoId; ?>?autoplay=1"></iframe>
</div>
<div class="videoInfo">
<div class="videoTitle"><b><?php echo $title; ?></b></div>
<div class="videoDesc"><?php echo $description; ?></div>
</div>
</div>
<?php
}
}
}
?>
Edit:
Error message (copied from the comments):
Notice: Use of undefined constant MAX_RESULTS - assumed 'MAX_RESULTS' in C:\xampp\htdocs\php\youtube\youtubeVideoAPI.php on line 48 . On my text editor line, 48 code is $googleApiUrl = 'googleapis.com/youtube/v3/search?part=snippet&q=' . $keyword . '&maxResults=' . MAX_RESULTS . '&key=' . $apikey;
Check, if you have defined the MAX_RESULTS constant in your code.
If you want to define a constant, you can do it this way:
define('MAX_RESULTS', 1); // I don't know, what value you need, so you can the 1 for anything you want
I have a 1 page website that is using scrollify.js.
I have 2 buttons to scroll the window to the relevant section for filling out the form and returning to the top of the page.
The first button is (icon2) with an (a) tag with a class of scrollToB.
The 2nd button (home-btn) with another (a) tag and a class of scrollTo that fades in and out so you can return to the top section on clicking this button.
Both functions to scroll and fade in and out are working until i click submit on the form and although the fade function still works on the button the seperate click functions on the 2 buttons (scrollify.move) have stopped working? This behaviour is the same whether the form fails validation or is sent?
a working example is www.devonfoodmovement.com
I have searched for hours and cant find anything relevant?
All scripts/styles are being loaded from my functions.php file
Index (front-page.php)
<?php get_header(); ?>
<article id="section_1">
<section class='section-class' data-section-name="devonfoodmovement">
<?php include('home-layout.php');?>
</section>
</article>
<article id="section_2">
<section class='section-class' data-section-name="contact us">
<?php include('form.php');?>
</section>
<div class="home-btn"><i class="fas fa-home"></i></div>
</article>
<?php get_footer(); ?>
</body>
</html>
home-layout.php
<?php ?>
<div class="container">
<div class="logo">
<div class="logo-image">
</div>
</div>
<div class="text">
<h1>Devon Food Movement</h1>
<h2>Website under construction <br class="textbreak">follow us below on ...</h2>
</div>
<div class="icons">
<div class="icon1"></div>
<div class="icon2"></div>
<div class="icon3"></div>
<div class="icon3m"></div>
</div>
</div>
functions.php
<?php
function register_my_menus() {
register_nav_menus(
array( 'header_menu' => __( 'Header Menu', 'DevonFoodMovement'),
'footer_menu' => __( 'Footer Menu', 'DevonFoodMovement')
)
);
}
add_action('init', 'register_my_menus');
/* GOOGLE FONTS */
function DFM_styles()
{
wp_register_style('DFM', get_template_directory_uri() . '/style.css', array(), '1.0', 'all');
wp_enqueue_style('DFM');
}
add_action('wp_enqueue_scripts', 'DFM_styles');
function DFM_form()
{
wp_register_style('DFMform-css', get_template_directory_uri() . '/form.css', array(), '1.0', 'all');
wp_enqueue_style('DFMform-css');
}
add_action('wp_enqueue_scripts', 'DFM_form');
function DFM_scripts()
{
wp_register_script('j-query-min', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js' );
wp_enqueue_script('j-query-min');
wp_register_script('j-query-mob-min', 'http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js' );
wp_enqueue_script('j-query-mob-min');
wp_register_script( 'modernizr', get_template_directory_uri() . '/modernizr-1.6.min.js' );
wp_enqueue_script( 'modernizr' );
wp_register_script('scrollify-min', 'https://cdn.jsdelivr.net/npm/jquery-scrollify#1.0.17/jquery.scrollify.min.js' );
wp_enqueue_script('scrollify-min');
wp_register_script('jquery-custom', get_template_directory_uri() . '/customjs.js' );
wp_enqueue_script('jquery-custom');
}
add_action('wp_enqueue_scripts', 'DFM_scripts');
function load_fonts()
{
wp_register_style('et-googleFonts', 'https://fonts.googleapis.com/css?family=Josefin+Sans:300,400');
wp_enqueue_style( 'et-googleFonts');
}
add_action('wp_print_styles', 'load_fonts');
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
custom.js file
$(document).ready(function(){
$('article').css({'height':($(window).height())+'px'}).css({'width':($(window).width())+'px'});
$(window).resize(function(){
$('article').css({'height':($(window).height())+'px'}).css({'width':($(window).width())+'px'});
});
});
$(document).scroll(function(){
$(function() {
$.scrollify({
section: ".section-class",
sectionName : "section-name",
/*interstitialSection : ".footer-end",*/
scrollSpeed: 1000,
setHeights: true
});
});
});
$(document).scroll(function (){
if(window.location.href === "http://devonfoodmovement.com/#devonfoodmovement"){
$('.home-btn').fadeOut(500);
} else if(window.location.href === "http://devonfoodmovement.com/#contact-us") {
$('.home-btn').fadeIn(500).css('display','block');
}
});
$(document).ready(function (){
$(".scrollTo").click(function() {
$.scrollify.move(0);
});
});
$(document).ready(function (){
$(".scrollToB").click(function() {
$.scrollify.move(1);
});
});
form.php
<?php include ('form_process.php');?>
<div class="grey">
<div class="container-contact">
<form id="contact" method="post" >
<div id="column-contact-left">
<div class='contact-logo'></div>
<h3>Contact the Devon Food Movement</h3>
<fieldset id="field-no-ui">
<input placeholder="Your name" type="text" tabindex="1" name="name1" value="<?= $name ?>" >
</fieldset>
<span class="error"><?= $name_error ?></span>
<fieldset id="field-no-ui">
<input placeholder="Your Email Address" type="text" name="email" value="<?= $email ?>" tabindex="2" >
</fieldset>
<span class="error"><?= $email_error ?></span>
</div>
<div id="column-contact-right">
<fieldset id="field-no-ui">
<textarea id="field-no-ui" placeholder="Type your Message Here...." name="message" value="<?= $message ?>" tabindex="3" ></textarea>
</fieldset>
<div class="g-recaptcha" data-sitekey="sitekey" ></div>
<span class="captcha-failed"><?= $captchafailed; ?></span>
<span class="sent"><?= $sent; ?></span>
<fieldset id="field-no-ui">
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Submit</button>
</fieldset>
</div>
</form>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</div>
</div>
form-process.php
<?php
function post_captcha($user_response) {
$fields_string = '';
$fields = array(
'secret' => 'secret',
'response' => $user_response
);
foreach($fields as $key=>$value)
$fields_string .= $key . '=' . $value . '&';
$fields_string = rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
$res = post_captcha($_POST['g-recaptcha-response']);
$name_error = $email_error = $captchafailed = "";
$name = $email = $message = $sent = "";
if (isset($_POST['submit']) AND (!$res['success'])) {
$captchafailed = "please check reCaptcha";
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name1"])) {
$name_error = "Name is required";
} else {
$name = test_input($_POST["name1"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $email_error == '' and ($res['success']) ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$email = $_POST['email'];
$to = '#gmail.com';
$subject = 'Contact Form Submit';
$headers = 'From:' . $email . "\n" . 'Reply-to: ' . $email . "\n" ;
if (mail($to, $subject, $message, $headers)) {
$sent = "Message sent";
$name = $email = $message = '';
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
I'm seeing a lot of issue here with the way this is put together.
First thing you can start with is to prevent the default behaviour of your move links.
$(".scrollTo").click(function(event) {
event.preventDefault();
$.scrollify.move(0);
});
I'm trying to post the html form data below to hubspot but when i have it deployed to either heroku or aws elastic beanstalk I receive 204 back instead of my data being posted to the crm. I used the solution found here how to execute php function on html button click
but have had no success getting the information needed into hubspot.
html file
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
function myAjax () {
$.ajax( { type : 'POST',
data : { },
url : 'index.php', // <=== CALL THE PHP FUNCTION HERE.
success: function ( data ) {
alert( data ); // <=== VALUE RETURNED FROM FUNCTION.
},
error: function ( xhr ) {
alert( "error" );
}
});
}
</script>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form>
<div class="row">
<div class="row">
<div class="col-lg-12 form-group">
<label for="email">Email</label>
<input
type="email"
id="email"
class="form-control"
name="email"
required
pattern="'^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$'"
>
</div>
<div class="row moveRight">
<div class="col-lg-12 form-group">
<label for="firstname">First Name</label>
<input
type="text"
id="firstname"
class="form-control"
name="firstname"
required
>
</div>
</div>
<div class="row moveRight">
<div class="col-lg-12 form-group">
<label for="lastname">Last Name</label>
<input
type="text"
id="lastname"
class="form-control"
name="lastname"
required
>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<button onclick="myAjax()" class="btn btn-success" id="startnode" type="submit">Submit</button>
</div>
</div>
</div>
</div>
</form>
<?php include 'index.php';?>
</body>
</html>
php file
<?php
function bb() {
//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' => 'http://www.example.com/form-page',
'pageName' => 'Example Title'
);
$hs_context_json = json_encode($hs_context);
//Need to populate these variable with values from the form.
$str_post = "firstname=" . urlencode($firstname)
. "&lastname=" . urlencode($lastname)
. "&email=" . urlencode($email)
. "&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/hubid/guid';
$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(
'Content-Type: application/x-www-form-urlencoded'
));
#curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = #curl_exec($ch); //Log the response from HubSpot as needed.
$status_code = #curl_getinfo($ch, CURLINFO_HTTP_CODE); //Log the response status code
#curl_close($ch);
echo $status_code . " " . $response;
}
bb();
?>
sorry for the perhaps naive question, but I have absolutely 0 experience in web design and I've been plowing through .html/.css for 2 days straight, and I think it's time I just seek some help.
I'm making a simple landing page for a conference, and I've been using a few templates. The most recent template I'm using is perfect, except the email signup sends direct emails to my account, rather than creating a list using a service such as mailchimp - highly inefficient.
A previous template I tried out, however, did implement mailchimp, and I was wondering how I might just grab its code and throw it in the current template I have.
Here is the subscribe.php from the mailchimp template:
<?php
$apiKey = '';
$listId = '';
$double_optin=true;
$send_welcome=true;
$email_type = 'html';
$email = $_POST['email'];
//replace us2 with your actual datacenter
$submit_url = "http://us1.api.mailchimp.com/1.3/?method=listSubscribe";
$data = array(
'email_address'=>$email,
'apikey'=>$apiKey,
'id' => $listId,
'double_optin' => $double_optin,
'send_welcome' => $send_welcome,
'email_type' => $email_type
);
$payload = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $submit_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($payload));
$result = curl_exec($ch);
curl_close ($ch);
$data = json_decode($result);
if ($data->error){
echo $data->error;
} else {
echo "Thanks! We'll keep you updated on the conference :)";
}
?>
and here is the snippet of code in index.html:
<div class="row">
<div class="col-md-6 col-sm-12 col-md-offset-3 subscribe">
<form class="form-horizontal" role="form" action="subscribe.php" id="subscribeForm" method="POST">
<div class="form-group">
<div class="col-md-7 col-sm-6 col-sm-offset-1 col-md-offset-0">
<input class="form-control input-lg" name="email" type="email" id="address" placeholder="Enter your email" data-validate="validate(required, email)" required="required">
</div>
<div class="col-md-5 col-sm-4">
<button type="submit" class="btn btn-success btn-lg">SIGN UP TO BE NOTIFIED</button>
</div>
</div>
</form>
<span id="result" class="alertMsg"></span> </div>
</div>
For reference, here are the subscribe.php and index.html snippets from the non-mailchimp template:
Subscribe.php
<?php
if ( isset( $_POST['newsletter_submit'] ) ) {
// Initialize error array
$newsletter_errors = array();
// Check email input field
if ( trim( $_POST['newsletter_email'] ) === '' )
$newsletter_errors[] = 'Email address is required';
elseif ( !preg_match( "/^[_\.0-9a-zA-Z-]+#([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z] {2,4}$/i", trim( $_POST['newsletter_email'] ) ) )
$newsletter_errors[] = 'Email address is not valid';
else
$newsletter_email = trim( $_POST['newsletter_email'] );
// Send email if no input errors
if ( empty( $newsletter_errors ) ) {
$email_to = "register#neustep.org"; // Change to your own email address
$subject = "NeuSTEP Subscription";
$body = "Subscriber details: " . $newsletter_email . "\r\n";
mail( $email_to, $subject, $body, $headers );
echo 'Thank you for subscribing!';
} else {
echo 'Please go back and correct the following errors:<br />';
foreach ( $newsletter_errors as $error ) {
echo $error . '<br />';
}}}
?>
Index.html snippet
<div class="newsletter">
<form action="subscribe.php" method="post" id="newsletter-form">
<p class="form-field">
<label for="newsletter_email" class="visually-hidden">Your email address</label>
<i class="icon ion-paper-airplane" aria-hidden="true"></i>
<input type="text" name="newsletter_email" id="newsletter_email" value="" placeholder="Your email address" />
</p>
<p class="form-submit">
<input type="submit" name="newsletter_submit" id="newsletter_submit" value="Get Notified" />
</p>
</form>
</div>
thanks for helping! sorry for the long post. I'm not sure what the etiquette on stackoverflow is, so if i'm asking a crappy question, let me know.
Your form is ok, and you need to implement a handler for subscribing like;
subscribe.php
<?php
if (empty($_POST["newsletter_email"]) {
die("You should provide email!");
} else if (!preg_match( "/^[_\.0-9a-zA-Z-]+#([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z] {2,4}$/i", trim( $_POST['newsletter_email'] ) )) {
die("Email address is not valid!");
} else {
$newsletter_email = trim( $_POST['newsletter_email'] );
}
$apiKey = '';
$listId = '';
$double_optin=true;
$send_welcome=true;
$email_type = 'html';
$email = $newsletter_email;
//replace us2 with your actual datacenter
$submit_url = "http://us1.api.mailchimp.com/1.3/?method=listSubscribe";
$data = array(
'email_address'=>$email,
'apikey'=>$apiKey,
'id' => $listId,
'double_optin' => $double_optin,
'send_welcome' => $send_welcome,
'email_type' => $email_type
);
$payload = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $submit_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($payload));
$result = curl_exec($ch);
curl_close ($ch);
$data = json_decode($result);
if ($data->error){
echo $data->error;
} else {
echo "Thanks! We'll keep you updated on the conference :)";
}
?>
i have fetch data from tally erp 9.0 using this code,
<?php
$requestXML = '<ENVELOPE>'.
'<HEADER>'.
'<TALLYREQUEST>Export Data</TALLYREQUEST>'.
'</HEADER>'.
'<BODY>'.
'<EXPORTDATA>'.
'<REQUESTDESC>'.
'<REPORTNAME>Daybook</REPORTNAME>'.
'<STATICVARIABLES>'.
'<SVEXPORTFORMAT>$$SysName:XML</SVEXPORTFORMAT>'.
'</STATICVARIABLES>'.
'</REQUESTDESC>'.
'</EXPORTDATA>'.
'</BODY>'.
'</ENVELOPE>';
$server = 'LOCALHOST:9000';
$headers = array( "Content-type: text/xml","Content-length:".strlen($requestXML) ,"Connection: close");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $server);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestXML);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$data = curl_exec($ch);
if(curl_errno($ch)){
print curl_error($ch);
echo " something went wrong..... try later";
}else{
echo " request accepted";
print $data;
curl_close($ch);
}
But my problem is how to push(insert) data into Tally ERP 9.0 using php(curl).
instead of
$server = 'LOCALHOST:9000';
give
$server = '10.0.0.155:9000';
use tally to generate xml format, and use same format to insert data back in to tally for eg.
to create sale voucher, get the xml from tally
i.e
GatewayOfTAlly-->Display-->Account Books--> Sales Register-->chhose
month-->ctl+E to export the voucher,
Now you got the xml format, you are good to go.
Instead of
$server = 'LOCALHOST:9000';
Use
$server = 'http://localhost:9000';
<form action="" method="post">
<table width="100%" border="1">
<tr>
<th scope="col">Name</th>
<td><input name="nm" id="nm" type="text" /></td>
</tr>
<tr>
<td colspan="4"><div align="center">
<label>
<input type="submit" name="sub" value="Submit" />
</label>
</div></td>
</tr>
</table>
</form>
<?php
/* This is PHP code to insert an entry in Tally. All required XML tags by Tally are taken here in a string and name for Ledger is taken by posted value from HTML form. */
if(isset($_POST['sub']))
{
$name = $_POST['nm'];
$requestXML = '<?xml version="1.0"?>
<ENVELOPE>
<HEADER>
<TALLYREQUEST>Import Data</TALLYREQUEST>
</HEADER>
<BODY>
<IMPORTDATA>
<REQUESTDESC>
<REPORTNAME>Vouchers</REPORTNAME>
<STATICVARIABLES>
<SVCURRENTCOMPANY>SAVH</SVCURRENTCOMPANY>
</STATICVARIABLES>
</REQUESTDESC>
<REQUESTDATA>
<TALLYMESSAGE xmlns:UDF="TallyUDF">
<VOUCHER REMOTEID="123" VCHTYPE="Receipt" VCHKEY="321" ACTION="Create" OBJVIEW="Accounting Voucher View">
<OLDAUDITENTRIES.LIST> </OLDAUDITENTRIES.LIST>
<ACCOUNTAUDITENTRIES.LIST> </ACCOUNTAUDITENTRIES.LIST>
<AUDITENTRIES.LIST> </AUDITENTRIES.LIST>
<OLDAUDITENTRYIDS.LIST TYPE="Number">
<OLDAUDITENTRYIDS>-1</OLDAUDITENTRYIDS>
</OLDAUDITENTRYIDS.LIST>
<DATE>20130401</DATE>
<GUID>f6c10ce3-4a15-42b8-961e-143a512a9e62-00000009</GUID>
<VOUCHERTYPENAME>Receipt</VOUCHERTYPENAME>
<VOUCHERNUMBER>5</VOUCHERNUMBER>
<PARTYLEDGERNAME>'.$name.'</PARTYLEDGERNAME>
<CSTFORMISSUETYPE/>
<CSTFORMRECVTYPE/>
<FBTPAYMENTTYPE>Default</FBTPAYMENTTYPE>
<PERSISTEDVIEW>Accounting Voucher View</PERSISTEDVIEW>
<VCHGSTCLASS/>
<DIFFACTUALQTY>No</DIFFACTUALQTY>
<AUDITED>No</AUDITED>
<FORJOBCOSTING>No</FORJOBCOSTING>
<ISOPTIONAL>No</ISOPTIONAL>
<EFFECTIVEDATE>20130401</EFFECTIVEDATE>
<ISFORJOBWORKIN>No</ISFORJOBWORKIN>
<ALLOWCONSUMPTION>No</ALLOWCONSUMPTION>
<USEFORINTEREST>No</USEFORINTEREST>
<USEFORGAINLOSS>No</USEFORGAINLOSS>
<USEFORGODOWNTRANSFER>No</USEFORGODOWNTRANSFER>
<USEFORCOMPOUND>No</USEFORCOMPOUND>
<ALTERID>20</ALTERID>
<EXCISEOPENING>No</EXCISEOPENING>
<USEFORFINALPRODUCTION>No</USEFORFINALPRODUCTION>
<ISCANCELLED>No</ISCANCELLED>
<HASCASHFLOW>Yes</HASCASHFLOW>
<ISPOSTDATED>No</ISPOSTDATED>
<USETRACKINGNUMBER>No</USETRACKINGNUMBER>
<ISINVOICE>No</ISINVOICE>
<MFGJOURNAL>No</MFGJOURNAL>
<HASDISCOUNTS>No</HASDISCOUNTS>
<ASPAYSLIP>No</ASPAYSLIP>
<ISCOSTCENTRE>No</ISCOSTCENTRE>
<ISSTXNONREALIZEDVCH>No</ISSTXNONREALIZEDVCH>
<ISEXCISEMANUFACTURERON>No</ISEXCISEMANUFACTURERON>
<ISBLANKCHEQUE>No</ISBLANKCHEQUE>
<ISDELETED>No</ISDELETED>
<ASORIGINAL>No</ASORIGINAL>
<VCHISFROMSYNC>No</VCHISFROMSYNC>
<MASTERID>9</MASTERID>
<VOUCHERKEY>177657027231784</VOUCHERKEY>
<INVOICEDELNOTES.LIST> </INVOICEDELNOTES.LIST>
<INVOICEORDERLIST.LIST> </INVOICEORDERLIST.LIST>
<INVOICEINDENTLIST.LIST> </INVOICEINDENTLIST.LIST>
<ATTENDANCEENTRIES.LIST> </ATTENDANCEENTRIES.LIST>
<ORIGINVOICEDETAILS.LIST> </ORIGINVOICEDETAILS.LIST>
<INVOICEEXPORTLIST.LIST> </INVOICEEXPORTLIST.LIST>
<ALLLEDGERENTRIES.LIST>
<AMOUNT>200000.00</AMOUNT>
<OLDAUDITENTRYIDS.LIST TYPE="Number">
<OLDAUDITENTRYIDS>-1</OLDAUDITENTRYIDS>
</OLDAUDITENTRYIDS.LIST>
<LEDGERNAME>'.$name.'</LEDGERNAME>
<GSTCLASS/>
<ISDEEMEDPOSITIVE>No</ISDEEMEDPOSITIVE>
<LEDGERFROMITEM>No</LEDGERFROMITEM>
<REMOVEZEROENTRIES>No</REMOVEZEROENTRIES>
<ISPARTYLEDGER>Yes</ISPARTYLEDGER>
<ISLASTDEEMEDPOSITIVE>No</ISLASTDEEMEDPOSITIVE>
<BANKALLOCATIONS.LIST></BANKALLOCATIONS.LIST>
<BILLALLOCATIONS.LIST></BILLALLOCATIONS.LIST>
<INTERESTCOLLECTION.LIST></INTERESTCOLLECTION.LIST>
<OLDAUDITENTRIES.LIST></OLDAUDITENTRIES.LIST>
<ACCOUNTAUDITENTRIES.LIST></ACCOUNTAUDITENTRIES.LIST>
<AUDITENTRIES.LIST></AUDITENTRIES.LIST>
<TAXBILLALLOCATIONS.LIST></TAXBILLALLOCATIONS.LIST>
<TAXOBJECTALLOCATIONS.LIST></TAXOBJECTALLOCATIONS.LIST>
<TDSEXPENSEALLOCATIONS.LIST></TDSEXPENSEALLOCATIONS.LIST>
<VATSTATUTORYDETAILS.LIST></VATSTATUTORYDETAILS.LIST>
<COSTTRACKALLOCATIONS.LIST></COSTTRACKALLOCATIONS.LIST>
</ALLLEDGERENTRIES.LIST>
<ALLLEDGERENTRIES.LIST>
<OLDAUDITENTRYIDS.LIST TYPE="Number">
<OLDAUDITENTRYIDS>-1</OLDAUDITENTRYIDS>
</OLDAUDITENTRYIDS.LIST>
<LEDGERNAME>Bank of Maharashtra</LEDGERNAME>
<GSTCLASS/>
<ISDEEMEDPOSITIVE>Yes</ISDEEMEDPOSITIVE>
<LEDGERFROMITEM>No</LEDGERFROMITEM>
<REMOVEZEROENTRIES>No</REMOVEZEROENTRIES>
<ISPARTYLEDGER>Yes</ISPARTYLEDGER>
<ISLASTDEEMEDPOSITIVE>Yes</ISLASTDEEMEDPOSITIVE>
<AMOUNT>-200000.00</AMOUNT>
<BANKALLOCATIONS.LIST>
<DATE>20130401</DATE>
<INSTRUMENTDATE>20130401</INSTRUMENTDATE>
<BANKBRANCHNAME>Warje</BANKBRANCHNAME>
<TRANSACTIONTYPE>Cheque/DD</TRANSACTIONTYPE>
<BANKNAME>AXIS</BANKNAME>
<PAYMENTFAVOURING>'.$name.'</PAYMENTFAVOURING>
<INSTRUMENTNUMBER>50026</INSTRUMENTNUMBER>
<UNIQUEREFERENCENUMBER>38ROUrdV00QEKOhl</UNIQUEREFERENCENUMBER>
<STATUS>No</STATUS>
<CHEQUEPRINTED>-1</CHEQUEPRINTED>
<AMOUNT>-200000.00</AMOUNT>
</BANKALLOCATIONS.LIST>
<BILLALLOCATIONS.LIST></BILLALLOCATIONS.LIST>
<INTERESTCOLLECTION.LIST></INTERESTCOLLECTION.LIST>
<OLDAUDITENTRIES.LIST></OLDAUDITENTRIES.LIST>
<ACCOUNTAUDITENTRIES.LIST></ACCOUNTAUDITENTRIES.LIST>
<AUDITENTRIES.LIST></AUDITENTRIES.LIST>
<TAXBILLALLOCATIONS.LIST></TAXBILLALLOCATIONS.LIST>
<TAXOBJECTALLOCATIONS.LIST></TAXOBJECTALLOCATIONS.LIST>
<TDSEXPENSEALLOCATIONS.LIST></TDSEXPENSEALLOCATIONS.LIST>
<VATSTATUTORYDETAILS.LIST> </VATSTATUTORYDETAILS.LIST>
<COSTTRACKALLOCATIONS.LIST> </COSTTRACKALLOCATIONS.LIST>
</ALLLEDGERENTRIES.LIST>
<ATTDRECORDS.LIST> </ATTDRECORDS.LIST>
</VOUCHER>
</TALLYMESSAGE>
<TALLYMESSAGE xmlns:UDF="TallyUDF">
<COMPANY>
<REMOTECMPINFO.LIST MERGE="Yes">
<NAME>12</NAME>
<REMOTECMPNAME>SAVH</REMOTECMPNAME>
<REMOTECMPSTATE>Maharashtra</REMOTECMPSTATE>
</REMOTECMPINFO.LIST>
<REMOTECMPINFO.LIST MERGE="Yes">
<NAME>f6c10ce3-4a15-42b8-961e-143a512a9e62</NAME>
<REMOTECMPNAME>SAVH</REMOTECMPNAME>
<REMOTECMPSTATE>Maharashtra</REMOTECMPSTATE>
</REMOTECMPINFO.LIST>
</COMPANY>
</TALLYMESSAGE>
<TALLYMESSAGE xmlns:UDF="TallyUDF">
<COMPANY>
<REMOTECMPINFO.LIST MERGE="Yes">
<NAME>12</NAME>
<REMOTECMPNAME>SAVH</REMOTECMPNAME>
<REMOTECMPSTATE>Maharashtra</REMOTECMPSTATE>
</REMOTECMPINFO.LIST>
<REMOTECMPINFO.LIST MERGE="Yes">
<NAME>f6c10ce3-4a15-42b8-961e-143a512a9e62</NAME>
<REMOTECMPNAME>SAVH</REMOTECMPNAME>
<REMOTECMPSTATE>Maharashtra</REMOTECMPSTATE>
</REMOTECMPINFO.LIST>
</COMPANY>
</TALLYMESSAGE>
</REQUESTDATA>
</IMPORTDATA>
</BODY>
</ENVELOPE>';
/* Actual code for importing goes here */
$server = 'http://localhost:9000';
$headers = array( "Content-type: text/xml" ,"Content-length: ".strlen($requestXML) ,"Connection: close" );
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $server);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestXML);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$data = curl_exec($ch);
if(curl_errno($ch))
{
print curl_error($ch);
echo " something went wrong..... try later";
}
else
{
echo " request accepted";
print $data;
curl_close($ch);
}
}
?>
Try this, it will be working....
give your port in "$server" which is in tally configuration....
<?php
if(count($_POST)) {
$group_name = strtoupper($_POST['group_name']);
$item_name = $_POST['item_name'];
/*$opening_balance = $_POST['opening_balance'];
$opening_value = $_POST['opening_value'];
$opening_rate = $opening_value * $opening_balance;*/
$res_str =<<<XML
<ENVELOPE>
<HEADER>
<TALLYREQUEST>Import Data</TALLYREQUEST>
</HEADER>
<BODY>
<IMPORTDATA>
<REQUESTDESC>
<REPORTNAME>All Masters</REPORTNAME>
</REQUESTDESC>
<REQUESTDATA>
<!-- Create Stock Group named "$group_name" -->
<TALLYMESSAGE xmlns:UDF="TallyUDF">
<STOCKGROUP NAME="{$group_name}" ACTION="Create">
<NAME.LIST>
<NAME>{$group_name}</NAME>
</NAME.LIST>
<PARENT/>
<ISADDABLE>Yes</ISADDABLE>
</STOCKGROUP>
</TALLYMESSAGE>
<!-- Create Stock Item named "$item_name" -->
<TALLYMESSAGE xmlns:UDF="TallyUDF">
<STOCKITEM NAME="{$item_name}" ACTION="Create">
<NAME.LIST>
<NAME>{$item_name}</NAME>
</NAME.LIST>
<PARENT>{$group_name}</PARENT>
<BATCHALLOCATIONS.LIST>
<NAME>Primary Batch</NAME>
<BATCHNAME>Primary Batch</BATCHNAME>
<GODOWNNAME>Main Location</GODOWNNAME>
<MFDON>20190120</MFDON>
<OPENINGBALANCE>0.000 NOS</OPENINGBALANCE>
<OPENINGVALUE>0.000</OPENINGVALUE>
<OPENINGRATE>0.000/NOS</OPENINGRATE>
</BATCHALLOCATIONS.LIST>
</STOCKITEM>
</TALLYMESSAGE>
</REQUESTDATA>
</IMPORTDATA>
</BODY>
</ENVELOPE>
XML;
//var_dump($res_str);die;
$url = "http://localhost:8000/";
//setting the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Following line is compulsary to add as it is:
curl_setopt($ch, CURLOPT_POSTFIELDS,
"xmlRequest=" . $res_str);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
$data = curl_exec($ch);
if(curl_errno($ch)){
var_dump($data);
} else {
$msg = $data;
}
curl_close($ch);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Tally</title>
<!-- Bootstrap -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="col-md-6 col-md-offset-3" style="margin-top:20px">
<?php if(isset($msg) && $msg) :?>
<div class="alert alert-success" role="alert"><?=$msg?></div>
<?php endif;?>
<div class="pull-left">Item List | </div>
<div class="pull-left">Create StockGroup Item | </div>
<div class="pull-left">Create Ledger | </div>
<hr>
<form class="form-horizontal" method="post" action="">
<div class="form-group">
<label for="group-name" class="col-sm-4 control-label">Stock Group name</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="group-name" placeholder="Stock Group name" name="group_name">
</div>
</div>
<div class="form-group">
<label for="item-name" class="col-sm-4 control-label">Stock Item name</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="item-name" placeholder="Stock Item name" name="item_name" required>
</div>
</div>
<!-- <div class="form-group">
<label for="opening_balance" class="col-sm-4 control-label">Quantity</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="opening_balance" placeholder="Item Quantity" name="opening_balance" required>
</div>
</div>
<div class="form-group">
<label for="opening_value" class="col-sm-4 control-label">Unit Price</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="opening_value" placeholder="Item Unit Price" name="opening_value" required>
</div>
</div> -->
<div class="form-group">
<div class="col-sm-offset-4 col-sm-6">
<button type="submit" class="btn btn-primary">Insert</button>
</div>
</div>
</form>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>