Magento Observer: Cannot send headers; headers already sent - php

I have been trying to create an Observer which automatically sends SMS whenever an invoice has been created by hooking into the:
sales_order_save_after
Now I am getting an error says: "a:5:{i:0;s:132:"Cannot send headers; headers already sent in /home2/uditgupta/public_html/app/code/local/Yng/AssignDealer/Model/Observer.php, line 4";i:1;s:1407:"#0 /home2/uditgupta/public_html/lib/Zend/Controller/Response/Abstract.php(148): Zend_Controller_Response_Abstract->canSendHeaders(true)
"
Here is my code:
class Yng_AssignDealer_Model_Observer {
public function customerRegisterSuccess(Varien_Event_Observer $observer) {
$order = $observer->getEvent()->getOrder();
print_r($order->getData());
echo $ordid = $order['increment_id'];
$orderObj = Mage::getModel('sales/order')->loadByIncrementId($ordid);
print_r($orderObj);
$billing_info=$orderObj->getBillingAddress();
echo $mobile=$billing_info['telephone'];
echo $name=$billing_info['firstname'];
if($order['status']=="processing")
{
$msg='Hello';
$path='http://login.smsgatewayhub.com/';
$ch = curl_init($path);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,0);
curl_exec($ch);
curl_close($ch);
//echo $path;
}
if($order['status']=="complete")
{
$msg='Hello';
$path='http://login.smsgatewayhub.com/';
$ch = curl_init($path);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,0);
curl_exec($ch);
curl_close($ch);
//echo $path;
}
}
}
Please help. Many thanks in advance.

remove echo and print_r from your code then check

Related

Get Facebook Profile URL From Facebook Profile id Using PHP

I have a list of Facebook links in xls sheet with Facebook id something like this
and when i go through these links means if i access Facebook with id www.facebook.com/7500
i get urls something like this https://www.facebook.com/davesachs/
so my question is i want to do this with PHP, i have a PHP page which read data from xls sheet
my code here:
require_once 'src/SimpleXLSX.php';
if ( $xlsx = SimpleXLSX::parse('fburl.xlsx') ) {
$rows= $xlsx->rows();
foreach($rows as $data){
echo $data[0].'<br>';
}
} else {
echo SimpleXLSX::parseError();
}
its returning all Facebook link with id same that i am passing like www.facebook.com/7500 but i want it return URL / link of profile as https://www.facebook.com/davesachs/ ,if it is possible please help me to do that.
You can do something like that, Taken reference from here
<?php
require_once 'src/SimpleXLSX.php';
if ( $xlsx = SimpleXLSX::parse('fburl.xlsx') ) {
$rows= $xlsx->rows();
foreach($rows as $data){
getRedirectedUrl($data[0]);
}
} else {
echo SimpleXLSX::parseError();
}
function getRedirectedUrl($link){
$url=$link;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Must be set to true so that PHP follows any "Location:" header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$a = curl_exec($ch); // $a will contain all headers
$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); // This is what you need, it will return you the last effective URL
// Uncomment to see all headers
/*
echo "<pre>";
print_r($a);echo"<br>";
echo "</pre>";
*/
echo $url; // Voila
}
?>

Payment gateway development - Handling and Processing parameters/keys PHP to Json, Json to PHP

I have written a Payment processor.php file to receive parameters from an ecommerce system then post to a PSP (Payment Service Provider), then this Json response from the PSP will be decoded, verified and Keys converted and parsed to the ecommerce system this way:
header("Location: ".$hosturl."orderprocessor?
orderid=$custref&sig=".$_POST['SessionId']);
Before giving out item in cart to users.
$hosturl has been defined as
$hosturl="localhost:8080/ekp/";
in another file
The result I get each time I do cart checkout with "Payment processor.php" file is just a white screen. I am supposed to see the PSP's interface to receive user's card details instead.
The PSP's URL is; " https://developers.paystack.co/reference#paystack-standard-x" I am following the cURL PHP sample for reference.
kindly assist if corrections are spotted in my code.
This is my Payment processor.php file:
<?php require_once 'includes/config.inc.php' ?>
<?php
$parameters = array();
if (isset($_POST['amount'])) { /* came the LMS; about to send data to
Paystack */
$sig=hash_hmac("md5","amount=".urlencode($_POST['amount']).
"&currency=".urlencode($_POST['currency']).
"&orderid=".urlencode($_POST['orderid']), $KEY);
$parameters['UserName']=$username;
$parameters['Password']=$password;
$parameters['reference']=$_POST['orderid'];
$parameters['Amount']=($_POST['amount'] * 100);
//should change SessionId' to be named reference
$parameters['SessionId']=$sig;
$parameters['SessionKey']=$encryptionKey;
$parameters['DL']="activ_purchase";
$parameters['ServerURL']=
base64_encode("http://localhost/nse/ecommerce/paystack.php");
$parameters['UserURL']=
base64_encode("http://localhost/nse/ecommerce/paystack.php");
$parameters['AccountNumber']=$accountnumber;
//$parameters['UserDeclinedURL']=
base64_encode($hosturl."externalpaymentcancel?
orderid=".$_POST['orderid']);
// print_r($parameters);
$cart=$_POST['cart'];
// var_dump($cart); die;
$cartitems=objectToArray(json_decode($cart));
foreach ( $cartitems['items'] as $item )
{
$productName=$item['description'];
$quantity=1;
$price=$item['price']['amount'];
$parameters['Reference4']=$productName." Qty
".$quantity." # $".$price."\r\n" ;
}
// created parameters for Paystack $postdata here
$postdata = array('email' => 'customer#gmail.com',
'amount' => $parameters['Amount'],
'reference' => $parameters['reference'],
);
//$url = "https://api.paystack.co/transaction/initialize";
//My codes for $ch here
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$paystackUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($postdata)); //Post
Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = [
'Authorization: Bearer sk_test_*****************************',
'Content-Type: application/json'];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec ($ch);
curl_close ($ch);
//My code for $ch ends here
//starting to setup redirect url
if ($result) {
$request = json_decode($result, true);
//print_r($request);
foreach ($request as $input) {
if($input ['data']['reference']){
$sst=['data']['reference'];
break;
}
}
header('Location:'.$result['data']
['authorization_url'].$parameters['SessionId'].$sst);
}
//Use the $result array to get redirect URL paystack
//var_dump($result);
}
else {
$result = array();
$url = 'https://api.paystack.co/transaction/verify/'.$_GET['reference'];
// print_r($parameters);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt(
$ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer sk_test_*****************************']
);
$request = curl_exec($ch);
curl_close($ch);
if ($request) {
$result = json_decode($request, true);
// print_r($result);
if($result){
if($result['data']){
//something came in
if($result['data']['status'] == 'success'){
header("Location: ".$hosturl."orderprocessor?
orderid=$reference&sig=".$_POST['SessionId']);
//echo "success";
// the transaction was successful, you can deliver value
/*
# also remember that if this was a card transaction, you can store
the
# card authorization to enable you charge the customer
subsequently.
# The card authorization is in:
# $result['data']['authorization']['authorization_code'];
# PS: Store the authorization with this email address used for this
transaction.
# The authorization will only work with this particular email.
# If the user changes his email on your system, it will be unusable
*/
echo "Transaction was successful";
}else{
// the transaction was not successful, do not deliver value'
// print_r($result); //uncomment this line to inspect the result,
to check why it failed.
echo "Transaction was not successful: Last gateway response was:
".$result['data']['gateway_response'];
}
}else{
echo $result['message'];
}
}else{
//print_r($result);
die("Something went wrong while trying to convert the request variable
to json. Uncomment the print_r command to see what is in the result
variable.");
}
}else{
echo "<html><head><meta http-equiv=\"refresh\"
content=\"5;URL=$hosturl"."externalpaymentcancel?orderid=$custref\">
</head><body style=\"text-align:center; font-family:'Open Sans', Arial,
Helvetica, sans-serif;\"><p><img
src=\"/nd/repository/EKP000000414.jpg\" alt=\"Activ logo\" /></p>
<p>Unfortunately, we were unable to process your payment.</p><p>The
response from your financial institution was "$declinedmessage"
</p><p>You will be redirected to the LMS shortly.</p></body></html>";
}
//echo $payresult;
//if ($payresult=="1") {
//header("Location: ".$hosturl."orderprocessor?
orderid=$custref&sig=".$_POST['SessionId']);
//echo "success";
//} else {
//echo "fail";
//echo "<html><head><meta http-equiv=\"refresh\"
content=\"5;URL=$hosturl"."externalpaymentcancel?orderid=$custref\">
</head><body style=\"text-align:center; font-family:'Open Sans', Arial,
Helvetica, sans-serif;\"><p><img
src=\"/nd/repository/EKP000000414.jpg\" alt=\"Activ logo\" /></p>
<p>Unfortunately, we were unable to process your payment.</p><p>The
response from your financial institution was "$declinedmessage"
</p><p>You will be redirected to the LMS shortly.</p></body></html>";
//header("Location: ".$hosturl."externalpaymentcancel?orderid=$custref");
// }
}
function objectToArray($d) {
if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$d = get_object_vars($d);
}
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return array_map(__FUNCTION__, $d);
}
else {
// Return array
return $d;
}
}
?>

Using cURL and PHP for CACTI in Windows

Recently tasked to monitor external webpage response/loading time via CACTI. I found some PHP scripts that were working (pageload-agent.php and class.pageload.php) using cURL. All was working fine until they requested it to be transferred from LINUX to Windows 2012R2 server. I'm having a very hard time modifying the scripts to work for windows. Already installed PHP and cURL and both working as tested. Here are the scripts taken from askaboutphp.
class.pageload.php
<?php
class PageLoad {
var $siteURL = "";
var $pageInfo = "";
/*
* sets the URLs to check for loadtime into an array $siteURLs
*/
function setURL($url) {
if (!empty($url)) {
$this->siteURL = $url;
return true;
}
return false;
}
/*
* extract the header information of the url
*/
function doPageLoad() {
$u = $this->siteURL;
if(function_exists('curl_init') && !empty($u)) {
$ch = curl_init($u);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_ENCODING, "gzip");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOBODY, false);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, false);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");
$pageBody = curl_exec($ch);
$this->pageInfo = curl_getinfo($ch);
curl_close ($ch);
return true;
}
return false;
}
/*
* compile the page load statistics only
*/
function getPageLoadStats() {
$info = $this->pageInfo;
//stats from info
$s['dest_url'] = $info['url'];
$s['content_type'] = $info['content_type'];
$s['http_code'] = $info['http_code'];
$s['total_time'] = $info['total_time'];
$s['size_download'] = $info['size_download'];
$s['speed_download'] = $info['speed_download'];
$s['redirect_count'] = $info['redirect_count'];
$s['namelookup_time'] = $info['namelookup_time'];
$s['connect_time'] = $info['connect_time'];
$s['pretransfer_time'] = $info['pretransfer_time'];
$s['starttransfer_time'] = $info['starttransfer_time'];
return $s;
}
}
?>
pageload-agent.php
#! /usr/bin/php -q
<?php
//include the class
include_once 'class.pageload.php';
// read in an argument - must make sure there's an argument to use
if ($argc==2) {
//read in the arg.
$url_argv = $argv[1];
if (!eregi('^http://', $url_argv)) {
$url_argv = "http://$url_argv";
}
// check that the arg is not empty
if ($url_argv!="") {
//initiate the results array
$results = array();
//initiate the class
$lt = new PageLoad();
//set the page to check the loadtime
$lt->setURL($url_argv);
//load the page
if ($lt->doPageLoad()) {
//load the page stats into the results array
$results = $lt->getPageLoadStats();
} else {
//do nothing
print "";
}
//print out the results
if (is_array($results)) {
//expecting only one record as we only passed in 1 page.
$output = $results;
print "dns:".$output['namelookup_time'];
print " con:".$output['connect_time'];
print " pre:".$output['pretransfer_time'];
print " str:".$output['starttransfer_time'];
print " ttl:".$output['total_time'];
print " sze:".$output['size_download'];
print " spd:".$output['speed_download'];
} else {
//do nothing
print "";
}
}
} else {
//do nothing
print "";
}
?>
Thank you. any type of assistance is greatly appreciated.

Using Postmark with PHP

Hi I'm new to php and postmark and am trying to get a form submission set to my email. I have the email working however I can't get it to show the header("Location: thanks.php) page. Any help would be greatly appreciated. Thanks.
require("postmark.php");
$postmark = new Postmark("API KEY","calvin.hemington#example.com","$email");
if($postmark->to("calvin.hemington#example.com")->subject("Mission Woodshop | " . $name)->plain_message($email_body)->send()){
exit;
}
header("Location: thanks.php");
exit;
<?php
/**
* This is a simple library for sending emails with Postmark created by Matthew Loberg (http://mloberg.com)
*/
class Postmark{
private $api_key;
private $data = array();
function __construct($apikey,$from,$reply=""){
$this->api_key = $apikey;
$this->data["From"] = $from;
$this->data["ReplyTo"] = $reply;
}
function send(){
$headers = array(
"Accept: application/json",
"Content-Type: application/json",
"X-Postmark-Server-Token: {$this->api_key}"
);
$data = $this->data;
$ch = curl_init('http://api.postmarkapp.com/email');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$return = curl_exec($ch);
$curl_error = curl_error($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// do some checking to make sure it sent
if($http_code !== 200){
return false;
}else{
return true;
}
}
function to($to){
$this->data["To"] = $to;
return $this;
}
function subject($subject){
$this->data["subject"] = $subject;
return $this;
}
function html_message($body){
$this->data["HtmlBody"] = "<html><body>{$body}</body></html>";
return $this;
}
function plain_message($msg){
$this->data["TextBody"] = $msg;
return $this;
}
function tag($tag){
$this->data["Tag"] = $tag;
return $this;
}
}
Presumably $postmark->send() returns true when it works. Your if/then statement says 'exit when the send succeeds'.
If you move the header() call into the if/then it should work as expected. You'll also want to handle the case where the $postmark->to call fails, possibly redirect to error page at that point.
It may be easier to use our new officially supported lib which gives full details on responses for API calls. http://developer.postmarkapp.com/developer-official-libs.html#php

Gotomeeting php api(oauth) implementation

I am trying to create a php gotomeating api implementation. I successfully got the access_token but for any other requests I get error responses. This is my code:
<?php
session_start();
$key = '#';
$secret = '#';
$domain = $_SERVER['HTTP_HOST'];
$base = "/oauth/index.php";
$base_url = urlencode("http://$domain$base");
$OAuth_url = "https://api.citrixonline.com/oauth/authorize?client_id=$key&redirect_uri=$base_url";
$OAuth_exchange_keys_url = "http://api.citrixonline.com/oauth/access_token?grant_type=authorization_code&code={responseKey}&client_id=$key";
if($_SESSION['access_token']) CreateForm();else
if($_GET['send']) OAuth_Authentication($OAuth_url);
elseif($_GET['code']) OAuth_Exchanging_Response_Key($_GET['code'],$OAuth_exchange_keys_url);
function OAuth_Authentication ($url){
$_SESSION['access_token'] = false;
header("Location: $url");
}
function CreateForm(){
$data = getURL('https://api.citrixonline.com/G2M/rest/meetings?oauth_token='.$_SESSION['access_token'],false);
}
function OAuth_Exchanging_Response_Key($code,$url){
if($_SESSION['access_token']){
CreateForm();
return true;
}
$data = getURL(str_replace('{responseKey}',$code,$url));
if(IsJsonString($data)){
$data = json_decode($data);
$_SESSION['access_token'] = $data->access_token;
CreateForm();
}else{
echo 'error';
}
}
/*
* Helper functions
*/
/*
* checks if a string is json
*/
function IsJsonString($str){
try{
$jObject = json_decode($str);
}catch(Exception $e){
return false;
}
return (is_object($jObject)) ? true : false;
}
/*
* CURL function to get url
*/
function getURL($url,$auth_token = false,$data=false){
// Initialize session and set URL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if($auth_token){
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: OAuth oauth_token='.$auth_token));
}
if($data){
curl_setopt($ch, CURLOPT_POST,true);
$d = json_encode('{ "subject":"test", "starttime":"2011-12-01T09:00:00Z", "endtime":"2011-12-01T10:00:00Z", "passwordrequired":false, "conferencecallinfo":"test", "timezonekey":"", "meetingtype":"Scheduled" }');
echo implode('&', array_map('urlify',array_keys($data),$data));
echo ';';
curl_setopt($ch, CURLOPT_POSTFIELDS,
implode('&', array_map('urlify',array_keys($data),$data))
);
}
// Get the response and close the channel.
$response = curl_exec($ch);
/*
* if redirect, redirect
*/
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code == 301 || $code == 302) {
preg_match('/<a href="(.*?)">/', $response, $matches);
$newurl = str_replace('&','&',trim(array_pop($matches)));
$response = getURL($newurl);
} else {
$code = 0;
}
curl_close($ch);
return $response;
}
function urlify($key, $val) {
return urlencode($key).'='.urlencode($val);
}
to start the connect process you need to make a request to the php file fith send=1. I tryed diffrent atempts to get the list of meetings but could not get a good response.
Did anybody had prev problems with this or know of a solution for this?
Edit:
This is not a curl error, the server responds with error messages, in the forums from citrix they say it should work, no further details on why it dosen't work, if I have a problem with the way I implemented the oauth or the request code. The most comon error I get is: "error code:31305" that is not documented on the forum.
[I also posted this on the Citrix Developer Forums, but for completeness will mention it here as well.]
We are still finalizing the documentation for these interfaces and some parameters which are written as optional are actually required.
Compared to your example above, changes needed are:
set timezonekey to 67 (Pacific time)
set passwordrequired to false
set conferencecallinfo to Hybrid (meaning: both PSTN and VOIP will be provided)
Taking those changes into account, your sample data would look more like the following:
{"subject":"test meeting", "starttime":"2012-02-01T08:00:00",
"endtime":"2012-02-01T09:00:00", "timezonekey":"67",
"meetingtype":"Scheduled", "passwordrequired":"false",
"conferencecallinfo":"Hybrid"}
You can also check out a working PHP sample app I created: http://pastebin.com/zE77qzAz

Categories