Api Oppwa payment button, Problems with a foreach - php

I am integrating a Payment Button with Oppwa API,
But with the method that brings me the "CheckoutId".
What happens I have to send all the parameters.
$total = 120;
$iva = 004012000000000012;
$totalTarifa12 = 053012000000000100;
$totalBase0 = 052012000000000200;
$email = "JonathanVeraMarin98#outlook.com";
$primer_nombre = "Jonathan";
$segundo_nombre = "Fernando";
$apellido = "Vera";
$cedula = "0952152525";
$trx = 123456789;
$ip_address = '05100817913101';
$finger = 'https://test.oppwa.com/v1/checkouts';
$merchterm= '1000000505_PD100406';
$telefono ='2172161';
$direccion_cliente = 11222;
$pais_cliente = 121212;
$direccion_entrega = '1600 Pennsylvania Ave NW';
$pais_entrega = 121212;
$checkoutId = prepareCheckout($items,$total,$iva,$totalTarifa12,$totalBase0,$email,$primer_nombre,$segundo_nombre,$apellido,$cedula,$trx,$ip_address,$finger,$merchterm,$telefono,$direccion_cliente,$pais_cliente,$direccion_entrega,$pais_entrega);
These are the values ​​of the burned parameters that I sent to the function
function prepareCheckout($items,$total,$iva,$totalTarifa12,$totalBase0,$email,$primer_nombre
,$segundo_nombre,$apellido,$cedula,$trx,$ip_address,$finger,$merchterm,
$telefono,$direccion_cliente,$pais_cliente,$direccion_entrega,$pais_entrega){
$finger = urlencode($finger);
$i =0;
$url = "https://test.oppwa.com/v1/checkouts";
$iva = str_replace('.', '', $iva);
$totalTarifa12 = str_replace('.', '', $totalTarifa12);
$totalBase0 = str_replace('.', '', $totalBase0);
$valueIva = str_pad($iva,12,'0'.STR_PAD_LEFT);
$valueTotalIva = str_pad($totalTarifa12,12,'0'.STR_PAD_LEFT);
$valueIvaTotalBase0 = str_pad($totalBase0,12,'0'.STR_PAD_LEFT);
$data = "authentication.userId=8a8294184b4f2868014b4f86f767015d" .
"&authentication.password=F8T7N4PD" .
"&authentication.entityId=8a8294184b4f2868014b4f87bf160173" .
"&amount=".$total.
"&currency=USD".
"&paymentType=DB".
"&customer.givenName=".$primer_nombre.
"&customer.middleName=".$segundo_nombre.
"&customer.surname=".$apellido.
"&customer.ip=".$ip_address.
"&customer.merchantCustomerId=00000000001".
"&merchantTransactionId=transaction_".$trx.
"&customer.email=".$email.
"&customer.identificationDocType=IDCAD".
"&customer.identificationDocId=".$cedula.
"&customer.phone=".$telefono.
"&billing.street1=".$direccion_cliente.
"&billing.country=".$pais_cliente.
"&shipping.street1=".$direccion_entrega.
"&shipping.country=".$pais_entrega.
"&risk.paramters[USER_DATA2]=MiComercio".
"customParamters[".$merchterm."]=00810030070103910004012".$valueIva.
"05100817913101052012".$valueIvaTotalBase0."053012".$valueTotalIva;
foreach ($items["cart"] as $c )
{
$data.="&cart.items[".$i."].name =".$c["product_name"];
$data.="&cart.items[".$i."].description ="."Descripcion: ".$c["product_name"];
$data.="&cart.items[".$i."].price =".$c["product_price"];
$data.="&cart.items[".$i."].quantity= ".$c["q"];
}
$data.= "&testMode=EXTERNAL";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization:Bearer OGE4Mjk0MTg1MzNjZjMxZDAxNTMzZDA2ZmQwNDA3NDh8WHQ3RjIyUUVOWA=='));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// this should be set to true inproduction
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$responseData = curl_exec($ch);
if(curl_errno($ch)) {
return curl_error($ch);
}
curl_close($ch);
return $responseData;
}
My function that generates a checkoutId.
The problem I have is in the foreach I know that it is going through an array but I get an error because I don't know what the condition $ items ['cart'] refers to
foreach ($items["cart"] as $c )
{
$data.="&cart.items[".$i."].name =".$c["product_name"];
$data.="&cart.items[".$i."].description ="."Descripcion: ".$c["product_name"];
$data.="&cart.items[".$i."].price =".$c["product_price"];
$data.="&cart.items[".$i."].quantity= ".$c["q"];
}
I've tried it like this
$items = array();
$items['product_name'] = 'Software';
$items['product_name'] = 'Hola';
$items['product_price'] = '50';
$items['q'] = '1';
I hurt:
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\Datafast\index.php on line 63
`

Related

Sandbox Paypal Checkout (PHP, Laravel)

I'm trying to implement Paypal's checkout to my Laravel Api (connected to an Ionic app) and it gets stuck when in the app I press the button to checkout and it goes to Paypal (so far so good) in the login screen. I found it weird because it wouldn't let me login with my sandbox account or even my real account, the error is the same: "Some of your info isn't correct. Please try again." By opening developer tools, those are the errors I get (see screenshots). I really couldn't find where I'm making a mistake here. Maybe you can help me. Below are the screenshots and the code that makes takes the checkout to Paypal. Let me know if I should add any extra info here! Thanks a lot!
error 1: ,
investigating one of the console errors:
Route::middleware('auth:api')->post('/paypal', function (Request $request) {
$user = $request->user();
$data = $request->all();
$list_products_id = $data;
$products = [];
$total = 0;
$titles = '';
foreach($list_products_id as $key => $value) {
$product = Product::find($value);
if($product){
$products[$key] = $product;
$total += $product->price;
$titles .= $product->title." ";
}
}
if($total){
$paypal = config('app.paypal', "sandbox");
if($paypal == "sandbox"){
$userProvider = 'In my app I have the sandbox business credentials here';
$pwdProvider = 'In my app I have the sandbox business credentials here';
$signProvider = 'In my app I have the sandbox business credentials here';
$url = 'https://api-3t.sandbox.paypal.com/nvp';
$url2 = 'https://www.sandbox.paypal.com/cgi-bin/webscr?%s';
} else {
$userProvider = '';
$pwdProvider = '';
$signProvider = '';
$url = 'https://api-3t.paypal.com/nvp';
$url2 = 'https://www.paypal.com/cgi-bin/webscr?%s';
}
$data = [];
$data['USER'] = $userProvider;
$data['PWD'] = $pwdProvider;
$data['SIGNATURE'] = $signProvider;
$data['METHOD'] = 'SetExpressCheckout';
$data['VERSION'] = '108';
$data['LOCALECODE'] = 'en_US';
$data['L_PAYMENTREQUEST_0_NAME0'] = "Products Orders";
$data['L_PAYMENTREQUEST_0_DESC0'] = $titles;
$data['PAYMENTREQUEST_0_AMT'] = number_format($total, 2).'';
$data['PAYMENTREQUEST_0_CURRENCYCODE'] = 'EUR';
$data['PAYMENTREQUEST_0_PAYMENTACTION'] = 'Sale';
$data['L_PAYMENTREQUEST_0_QTY0'] = '1'; //number of the same product the user is ordering
$data['L_PAYMENTREQUEST_0_AMT0'] = number_format($total, 2).'';
$data['L_BILLINGAGREEMENTDESCRIPTION0'] = $titles;
$data['CANCELURL'] = url('/');
$data['RETURNURL'] = url('/');
// curl
$data = http_build_query($data);
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($curl);
curl_close($curl);
$nvp = array();
if (preg_match_all('/(?<name>[^\=]+)\=(?<value>[^&]+)&?/', $response, $matches)) {
foreach ($matches['name'] as $offset => $name) {
$nvp[$name] = urldecode($matches['value'][$offset]);
}
}
if(isset($nvp['ACK']) && $nvp['ACK'] == "Success" ){
$query = array(
'cmd' => '_express-checkout',
'token' => $nvp['TOKEN']
);
$redirectURL = sprintf($url2, http_build_query($query));
return ['date'=>$redirectURL];
}else{
return ['status'=>'error purchasing! - 1'];
}
}
echo "total: " . $total;
return ['status'=>'error purchasing! - 2'];
});
so I did a password reset on my sandboxes account and it worked!

Clear session after checkout with custom payment method

Im using custom payment method for payments with credit and debit cards in OpenCart 2.1.0.1 but I am facing a problem. When I make a successful purchase and I redirected to succsess.tpl page, after that when i continue shopping (in the same browser session) and make a second successful purchase - its not recording as new order with new order id! I will attach my controller, which can be the code for clearing session?
class ControllerPaymentFibank extends Controller {
public function index() {
$this->load->model('checkout/order');
$this->language->load('payment/fibank');
$data['button_confirm'] = $this->language->get('button_confirm');
if (!$this->config->get('fibank_test')) {
$communication_url = "https://mdpay.fibank.bg:9443/ecomm/MerchantHandler";
$payment_url = "https://mdpay.fibank.bg/ecomm/ClientHandler";
} else {
$communication_url = "https://mdpay-test.fibank.bg:9443/ecomm/MerchantHandler";
$payment_url = "https://mdpay-test.fibank.bg/ecomm/ClientHandler";
}
$order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']);
if ($order_info) {
$data['action'] = $this->session->data['order_id'];
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/payment/fibank.tpl')) {
return $this->load->view($this->config->get('config_template') . '/template/payment/fibank.tpl', $data);
} else {
return $this->load->view('default/template/payment/fibank.tpl', $data);
}
}
}
public function make_payment() {
$this->load->model('checkout/order');
$this->language->load('payment/fibank');
$data['button_confirm'] = $this->language->get('button_confirm');
if (!$this->config->get('fibank_test')) {
$communication_url = "https://mdpay.fibank.bg:9443/ecomm/MerchantHandler";
$payment_url = "https://mdpay.fibank.bg/ecomm/ClientHandler";
} else {
$communication_url = "https://mdpay-test.fibank.bg:9443/ecomm/MerchantHandler";
$payment_url = "https://mdpay-test.fibank.bg/ecomm/ClientHandler";
}
$order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']);
if ($order_info) {
$ip = $this->get_client_ip();
$amount = $this->currency->format($order_info['total'], 'BGN', '', false);
$amount *= 100;
$post_request="command=v&amount=".$amount."&currency=975&client_ip_addr=".$ip."&description=".$this->session->data['order_id']."&msg_type=SMS";
$res = $this->execute_fibank_query($communication_url, $post_request);
$result = str_replace("TRANSACTION_ID: ", "", $res);
$this->model_checkout_order->addOrderHistory($this->session->data['order_id'], '1', $result);
$_SESSION['order_id']=$this->session->data['order_id'];
header("location:".$payment_url."?trans_id=".rawurlencode($result));
}
exit();
}
public function callback() {
if (isset($this->request->post['trans_id'])) {
$tranz_id = $this->request->post['trans_id'];
} else {
$tranz_id = '';
}
if (!$this->config->get('fibank_test')) {
$communication_url = "https://mdpay.fibank.bg:9443/ecomm/MerchantHandler";
$payment_url = "https://mdpay.fibank.bg/ecomm/ClientHandler";
} else {
$communication_url = "https://mdpay-test.fibank.bg:9443/ecomm/MerchantHandler";
$payment_url = "https://mdpay-test.fibank.bg/ecomm/ClientHandler";
}
if ($tranz_id!="" && $_SESSION['order_id']>0) {
$ip = $this->get_client_ip();
$request="command=c&trans_id=".rawurlencode($tranz_id)."&client_ip_addr=".$ip;
$result = $this->execute_fibank_query($communication_url, $request);
$res = explode("\n", $result);
$fibank_info = str_replace("RESULT: ", "", $res[0]);
$this->load->model('checkout/order');
$order_info = $this->model_checkout_order->getOrder($_SESSION['order_id']);
if ($fibank_info=="OK") {
$order_status = $this->config->get('fibank_order_status_id');
$this->model_checkout_order->addOrderHistory($_SESSION['order_id'], $order_status, $result);
$this->cart->clear();
header("location:/successfull-transaction");
}
else{
$order_status = $this->config->get('fibank_order_status_denied_id');
$this->model_checkout_order->addOrderHistory($_SESSION['order_id'], $order_status, $result);
$this->cart->clear();
header("location:/transaction-error");
}
}
}
function execute_fibank_query($url, $request){
// debug
$fp = fopen(dirname(__FILE__).'/errorlog.txt', 'w');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// debug
curl_setopt($ch, CURLOPT_STDERR, $fp);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_SSLCERT, $this->config->get('fibank_certificate_path'));
curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
curl_setopt($ch, CURLOPT_SSLCERTPASSWD, $this->config->get('fibank_certificate_pass'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
$result = curl_exec($ch);
return $result;
}
function get_client_ip(){
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
If you look at the file catalog/controller/checkout/success.php you will see the standard process that follows a successful order. If you've modified this at all, it's possible OpenCart isn't unsetting the session data. In that file, the controller checks if there is data set in the session:
if (isset($this->session->data['order_id'])) {
If it's true, the cart will be cleared with this line:
$this->cart->clear();
And, following the UserActivity logging, the session data is unset with this code:
unset($this->session->data['shipping_method']);
unset($this->session->data['shipping_methods']);
unset($this->session->data['payment_method']);
unset($this->session->data['payment_methods']);
unset($this->session->data['guest']);
unset($this->session->data['comment']);
unset($this->session->data['order_id']);
unset($this->session->data['coupon']);
unset($this->session->data['reward']);
unset($this->session->data['voucher']);
unset($this->session->data['vouchers']);
unset($this->session->data['totals']);

Webapplication stops running code after calling function from another file

My web app stops when it tries executing a function from another file. I am using a include_once to include the file where the function is. I am also pretty sure that the path is correct. (if there is anyway to check let me know). the functions which I am trying to use are written in the class.connections.php . Also as you can see I am echoing 2 test. Only the first one shows.
Invite.php
global $page_array ;
global $current_user ;
include_once(DITC_PATH."/class.friends.php");
include_once(DITC_PATH."/class.connections.php");
$process_status = $current_user->process_hotmail_contacts ;
global $page_array ;
if($page_array['url']['3'] == 'hotmail'){
$process_source = 'hotmail' ;
};
if($_GET['code']){
echo "Test 1 - ";
$access_token_json = get_hotmail_access_token();
echo "Test 2 - ";
if($access_token_json){
echo 'test';
update_user_meta($current_user->ID, 'hotmail_access_token', $access_token_json);
$taskurl = "/tasks";
$data = array();
$data['type'] = 'process_hotmail_contacts';
$data['lang'] = get_site_language();
$data['access_token'] = $access_token_json ;
$data['user_id'] = $current_user->ID ;
$options = array();
add_task($taskurl, $data, $options);
$process_status = 'busy' ;
$process_source = 'hotmail' ;
};
}
$ditc_title = _t("Invite connections") ;
get_header();
function in class.connections
function get_hotmail_access_token(){
global $hotmail_creds;
$fields=array(
'code'=> urlencode($hotmail_creds['auth_code']),
'client_id'=> urlencode($hotmail_creds['client_id']),
'client_secret'=> urlencode($hotmail_creds['client_secret']),
'redirect_uri'=> urlencode($hotmail_creds['redirect_uri']),
'grant_type'=> urlencode('authorization_code')
);
$post = '';
foreach($fields as $key=>$value) { $post .= $key.'='.$value.'&'; }
$post = rtrim($post,'&');
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,'https://login.live.com/oauth20_token.srf');
curl_setopt($curl, CURLOPT_POST,5);
curl_setopt($curl, CURLOPT_POSTFIELDS,$post);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0);
$result = curl_exec($curl);
curl_close($curl);
$response = json_decode($result);
$access_token_json = $response->access_token;
return $access_token_json;
};

curl headers multipart/form already sent

Dear Stackoverflow users,
I am running into a problem. It is as follows:
Currently i am programming a management tool for pfsense, which needs to send a multipart form that the server needs to validate and process. It should enable the voucher based acces control on the interface. However, i am getting the error that my headers are already sent. I did not sent them.
my code is as follows:
protected function doCurl($resourceID=null, $post=null)
{
//volledige url
$url = Yii::app()->params->pfsense['host'].$resourceID;
$ch = curl_init();
if($post != null)
{
$post_string = "";
foreach($post as $key=>$value)
{
if($key != 'enctype')
{
$post_string .= $key.'='.$value.'&';
}
else
{
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: multipart/form-data'
));
}
}
rtrim($post_string, '&');
//var_dump($post);
/**/
curl_setopt($ch,CURLOPT_POST, count($post));
curl_setopt($ch,CURLOPT_POSTFIELDS, $post_string);
//var_dump($post_string);
}
else
{
curl_setopt($ch, CURLOPT_HEADER, true);
}
curl_setopt($ch, CURLOPT_URL, $url);
//omdat het certificaat niet klopt zetten we de verificatie uit.
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//we setten de useragent en de timeout. Useragent omdat sommige websites iets anders voorschotelen per browser.
//timeout voor als er iets gebeurd wat niet moet
curl_setopt($ch,CURLOPT_USERAGENT,Yii::app()->params->pfsense['useragent']);
curl_setopt($ch,CURLOPT_COOKIEJAR, Yii::app()->params->pfsense['cookiepath']);
curl_setopt($ch,CURLOPT_COOKIEFILE, Yii::app()->params->pfsense['cookiepath']);
curl_setopt($ch, CURLOPT_AUTOREFERER, true );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,10);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($ch);
$result = array( 'header' => '',
'body' => '',
'http_code' => '',
'last_url' => '');
$header_size = curl_getinfo($ch,CURLINFO_HEADER_SIZE);
$result['header'] = substr($response, 0, $header_size);
$result['body'] = substr( $response, $header_size );
$result['http_code'] = curl_getinfo($ch,CURLINFO_HTTP_CODE);
$result['last_url'] = curl_getinfo($ch,CURLINFO_EFFECTIVE_URL);
//curl_close($ch);
return $result;
}
public function curl($resourceID=null, $post=null)
{
$result = $this->doCurl($resourceID, $post);
if(strpos($result['body'], 'Login') == false && $result['http_code'] != 403)
{
//echo $result['body'];
return $result;
}
else
{
$loginpost = array(
'__csrf_magic' => substr($result['body'], strpos($result['body'],'sid:') , 55),
'login' => urlencode('Login'),
'usernamefld' => urlencode(Yii::app()->params->pfsense['pfuser']),
'passwordfld' => urlencode(Yii::app()->params->pfsense['pfpass'])
);
$result = $this->doCurl('',$loginpost);
$result = $this->doCurl($resourceID, $post);
return $result;
}
}
This is the code that allows a curl request to be sent to the server. If the page that is returned is the login page, the login info needs to be sent and the original post request needs to be sent again.
the code that follows is the code to insert a zone:
public function insertZone($post)
{
$description = $post['description'];
$interface = $post['interfaces'];
$name = $post['name'];
$post=null;
$post['zone'] = $name;
$post['descr'] = $description;
$post['Submit'] = 'Continue';
$result = $this->curl(Yii::app()->params->pfsense['pfpathtoinsertzone']);
$post['__csrf_magic'] = substr($result['body'], strpos($result['body'],'sid:') , 55);
var_dump($post);
$result = $this->curl(Yii::app()->params->pfsense['pfpathtoinsertzone'], $post);
var_dump($result['body']);
//exit;
if(strpos($result['body'], 'The following input errors were detected') == false)
{
$post = null;
$post['enable'] = 'yes';
$post['interfaces'] = $interface;
$post['Submit'] = 'Save';
$post['name'] = $name;
$result = $this->editZone($post);
if($result != false)
{
$post = null;
$post['zone'] = $name;
$post['enable'] = 'yes';
$post['Submit'] = 'Save';
$result = $this->curl(Yii::app()->params->pfsense['pfpathtovoucherroll'].$name);
$post['__csrf_magic'] = substr($result['body'], strpos($result['body'],'sid:') , 55);
$doc = new DOMDocument();
$doc->loadHTML($result['body']);
$doc->preserveWhiteSpace = false;
if($childs = $doc->getElementsByTagName("textarea"))
{
foreach($childs as $child)
{
if($child->nodeType == XML_TEXT_NODE)
{
continue;
}
if(strpos(trim($child->nodeValue),'BEGIN RSA PRIVATE KEY'))
{
$post['privatekey'] = trim($child->nodeValue);
}
elseif(strpos(trim($child->nodeValue),'BEGIN PUBLIC KEY'))
{
$post['publickey'] = trim($child->nodeValue);
}
}
}
$post['charset'] = $doc->getElementById('charset')->attributes->getNamedItem('value')->nodeValue;
$post['rollbits'] = $doc->getElementById('rollbits')->attributes->getNamedItem('value')->nodeValue;
$post['ticketbits'] = $doc->getElementById('ticketbits')->attributes->getNamedItem('value')->nodeValue;
$post['checksumbits'] = $doc->getElementById('checksumbits')->attributes->getNamedItem('value')->nodeValue;
$post['magic'] = $doc->getElementById('magic')->attributes->getNamedItem('value')->nodeValue;
$result = $this->curl(Yii::app()->params->pfsense['pfpathtovoucherroll'].$name, $post);
if($result['http_code'] >= 100 && $result['http_code'] <= 299)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
public function editZone($post)
{
$zone = $post['name'];
$interfaces = $post['interfaces'];
$post = null;
//$post['localauth_priv'] = 'yes';
//$post['radiussrcip_attribute'] = strtolower($interfaces);
if(is_array($interfaces))
{
$post['cinterface[]'] = array_map('strtolower', $interfaces);
}
else
{
$post['cinterface[]'] = strtolower($interfaces);
}
$post['auth_method'] = 'local';
$post['radiussrcip_attribute'] = 'wan';
$post['radiusvendor'] = 'default';
$post['radmac_format'] = 'default';
$post['enable'] = 'yes';
$post['Submit'] = 'Save';
$post["maxprocperip"] = '';
$post["idletimeout"] = '';
$post["timeout"] = '';
$post["freelogins_count"] = '';
$post["freelogins_resettimeout"] = '';
$post["preauthurl"] = '';
$post["redirurl"] = '';
$post["blockedmacsurl"] = '';
$post["bwdefaultdn"] = '';
$post["bwdefaultup"] = '';
$post["radiusip"] = '';
$post["radiusport"] = '';
$post["radiuskey"] = '';
$post["radiusip2"] = '';
$post["radiusport2"] = '';
$post["radiuskey2"] = '';
$post["radiusip3"] = '';
$post["radiusport3"] = '';
$post["radiuskey3"] = '';
$post["radiusip4"] = '';
$post["radiusport4"] = '';
$post["reauthenticateacct"] = '';
$post["radmac_secret"] = '';
$post["radiusvendor"] = 'default';
$post["radiusnasid"] = '';
$post["radmac_format"] = 'default';
$post["httpsname"] = '';
$post['certref'] = '';
$post['enctype'] = true;
$post['zone'] = $zone;
$post['enable'] = 'yes';
$post['Submit'] = 'Save';
$result = $this->curl(Yii::app()->params->pfsense['pfpathtoupdatezone'].$zone);
//echo $result['last_url'];
$post['__csrf_magic'] = substr($result['body'], strpos($result['body'],'sid:') , 55);
//var_dump($post);
$result = $this->curl(Yii::app()->params->pfsense['pfpathtoupdatezone'].$zone, $post);
ini_set('xdebug.var_display_max_depth', -1);
ini_set('xdebug.var_display_max_children', -1);
ini_set('xdebug.var_display_max_data', -1);
var_dump($result['body']);
exit;
if($result['http_code'] >= 100 && $result['http_code'] <= 299)
{
return true;
}
else
{
//var_dump($result);
///exit;
return $result;
}
}
This code works by first inserting a zone with the name and description and then updating it to set the interface active and enabling the captive portal page to be displayed. However, if i sent the page without the multipart form(it seems to be that this is the issue) then the authentication is not set correctly. It is set, but it does not work. If i then manually change the authentication setting (it is a radio button, if i choose another radio button and then choose my original radio button it suddenly works)
has anyone have a clue about what i am doing wrong? because with the following code i get the result that my headers are already sent:
$result = $this->curl(Yii::app()->params->pfsense['pfpathtoupdatezone'].$zone, $post);
ini_set('xdebug.var_display_max_depth', -1);
ini_set('xdebug.var_display_max_children', -1);
ini_set('xdebug.var_display_max_data', -1);
var_dump($result['body']);
exit;
i would appreciate all the help i can get.
thanks in advance!
What got my request to work:
it turned out that there was no enctype needed in the request. It was however, needed that the update request was sent a 3th time. Do'nt ask me why.
If anything, anything at all, is output, e.g. echo, var_dump, you will get this error.
curl sets the headers to application/x-www-form-urlencoded. If the post data is sent as a string.
If it is sent as an array, it uses a Content-Type: multipart/form-data
If that is not it, add this to see the Request header:
Now I am not sure exactly how you fixed it, but you may have a problem.
It appears your data is in an array and then sent as a sting for some unknown reason.
It should have stayed in the array. This code is off.
The else will be executed for every foreach loop. Probably will not hurt anything it is just a mistake
foreach($post as $key=>$value)
{
if($key != 'enctype')
{
$post_string .= $key.'='.$value.'&';
}
else
{
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
}
}
Should have been:
if($key == 'enctype'){
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
}
else{
foreach($post as $key=>$value){
$post_string .= $key.'='.$value.'&';
}
}
I think you sent the data as a string, or not at all.
This is the big question: if($key != 'enctype') Why? Is this open source?
The above loop would be used only if the post data had to be sent encoded.
And this part:
if($key == 'enctype'){
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
}
Should just be:
if($key == 'enctype'){
$post_string = $post;
}
This way, because the post data is in an array curl will automatically use Content-Type: multipart/form-data
The problem is if it is sent as a string curl will use application/x-www-form-urlencoded, then you have to add this after the loop:
$post_string = urlencode($post_string);
Like this:
else{
foreach($post as $key=>$value){
$post_string .= $key.'='.$value.'&';
}
$post_string = urlencode($post_string);
}

Curl error Could not resolve host: saved_report.xml; No data record of requested type"

<?php
error_reporting(E_ALL);
$url = 'saved_report.xml';
define('XML_HEADER', '*RWRESPONSE*RESPONSE*DATA*HEADER*COLUMN');
define('XML_ROW', '*RWRESPONSE*RESPONSE*DATA*ROW*COLUMN');
$headers = array();
$rows = array();
function startTag($parser, $data) {
global $current_tag;
$current_tag .= "*$data";
}
function endTag($parser, $data) {
global $current_tag;
$tag_key = strrpos($current_tag, '*');
$current_tag = substr($current_tag, 0, $tag_key);
}
function contents($parser, $data) {
global $current_tag, $headers, $rows;
switch($current_tag) {
case XML_HEADER:
array_push($headers, $data);
break;
case XML_ROW:
array_push($rows, $data);
break;
}
}
// fetch the report
$curl_object = curl_init();
curl_setopt($curl_object, CURLOPT_URL, $url);
curl_setopt($curl_object, CURLOPT_HEADER, 0);
curl_setopt($curl_object, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_object, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl_object, CURLOPT_SSL_VERIFYHOST, 0);
$result = curl_exec($curl_object);
$error = curl_error($curl_object);
$info = curl_getinfo($curl_object);
curl_close($curl_object);
if ($error) {
die("An error occured while fetching the report\n");
}
// process the report
$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startTag", "endTag");
xml_set_character_data_handler($xml_parser, "contents");
if(!(xml_parse($xml_parser, $result))){
die("Error on line " . xml_get_current_line_number($xml_parser));
}
xml_parser_free($xml_parser);
for($i = 0; $i \n";
}
echo '';
echo "$headers[3]: $rows[3]\n";
echo "$headers[4]: $rows[4]\n";
?>
while running this script , i am getting an error
"Could not resolve host: saved_report.xml; No data record of requested type"
i am not able to resolve this .
You need to specify full path of the file, e.g.:
$url = 'http://example.com/saved_report.xml';
as curl doesn't work with relative URLs

Categories