How to add a custom payment gateway to Social Engine - php

I need to integrate a new payment gateway to our corporate website, which is based on Social Engine. There is an extension for this CMS called Advanced Payment Gateways which allows integration of new gateways. In fact, it gets your gateway name and generates a skeleton structure zipped as a file so you can unzip and upload to your server and thus merge with the application directory.
I'm going to explain how I implement my gateway without Social Engine, and I hope someone can tell me how I can incorporate that into Social Engine.
First I connect to my PSP service:
$client = new nusoap_client('https://example.com/pgwchannel/services/pgw?wsdl');
I prepare the following parameters in an array to send to bpPayRequest:
$parameters = array(
'terminalId' => $terminalId,
'userName' => $userName,
'userPassword' => $userPassword,
'orderId' => $orderId,
'amount' => $amount,
'localDate' => $localDate,
'localTime' => $localTime,
'additionalData' => $additionalData,
'callBackUrl' => $callBackUrl,
'payerId' => $payerId);
// Call the SOAP method
$result = $client->call('bpPayRequest', $parameters, $namespace);
If payment request is accepted, the result is a comma separated string, with the first element being 0.
Then we can send the second element (reference id) to payment
gateway as follows via POST method:
echo "<script language='javascript' type='text/javascript'>postRefId('" . $res[1] . "');</script>";
<script language="javascript" type="text/javascript">
function postRefId (refIdValue) {
var form = document.createElement("form");
form.setAttribute("method", "POST");
form.setAttribute("action", "https://example.com/pgwchannel/startpay");
form.setAttribute("target", "_self");
var hiddenField = document.createElement("input");
hiddenField.setAttribute("name", "RefId");
hiddenField.setAttribute("value", refIdValue);
form.appendChild(hiddenField);
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
}
</script>
The gateway will return the following parameters via POST method to the call back URL that we provided in payment request:
RefId (reference id as produced in previous steps)
ResCode (Result of payment: 0 denotes success)
saleOrderId (order id as passed during payment request)
SaleReferenceId (sale reference code is given by PSP to the merchant)
If ResCode in the previous step was 0, then we'd need to pass the call bpVerifyRequest with the following parameters to verify payment, otherwise the payment will be canceled.
$parameters = array(
'terminalId' => $terminalId,
'userName' => $userName,
'userPassword' => $userPassword,
'orderId' => $orderId,
'saleOrderId' => $verifySaleOrderId,
'saleReferenceId' => $verifySaleReferenceId);
// Call the SOAP method
$result = $client->call('bpVerifyRequest', $parameters, $namespace);
In case the result of bpVerifyRequest is zero, payment is certain and the merchant has to provide goods or services purchased. However, there is an optional method bpSettleRequest, which is used to request a settlement. It is called as follows:
$parameters = array(
'terminalId' => $terminalId,
'userName' => $userName,
'userPassword' => $userPassword,
'orderId' => $orderId,
'saleOrderId' => $settleSaleOrderId,
'saleReferenceId' => $settleSaleReferenceId);
// Call the SOAP method
$result = $client->call('bpSettleRequest', $parameters, $namespace);
I get confused by looking at default gateways in the Payment Gateways plugin e.g. PayPal, Stripe, 2Checkout, etc. How am I incorporate this code logic into the newly created gateway skeleton? (the structure is shown below):
You can check out the complete source code here:
default.php
callback.php

I solved this by adding the payment code inside the Engine_Payment_Gateway_MyGateway class:
Once the user confirms on the SocialEngine page that they want to pay, the method processTransaction() inside the mentioned class is called and the user is redirected to the PSP's payment secure page. Once they are done with the payment, i.e. paid successfully or failed or canceled the transaction, they PSP's page redirects them to the page we had sent to it earlier as a parameter called callBackUrl. There, you will receive PSP-specific parameters which helps you decide whether the payment was successful and to ask the PSP with another SOAP call to confirm the payment and then optionally ask it to settle (deposit money ASAP into the seller's account):
Add to processTransaction():
$data = array();
$rawData = $transaction->getRawData();
//Save order ID for later
$this->_orderId = $rawData['vendor_order_id'];
$this->_grandTotal = $rawData['AMT'];
$client = new nusoap_client('https://example.com/pgwchannel/services/pgw?wsdl');
$namespace = 'http://interfaces.core.sw.example.com/';
// Check for an error
$err = $client->getError();
if ($err) {
echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
die();
}
/* Set variables */
//Get price from SEAO
//$order_ids = Engine_Api::_()->getDbTable('orders','sitestoreproduct')->getOrderIds($this->parent_id);
//$price = Engine_Api::_()->getDbTable('orders','sitestoreproduct')->getGrandTotal($this->parent_id);
$terminalId = '1111111';
$userName = 'username';
$userPassword = '1111111';
$orderId = $rawData['vendor_order_id'];
$amount = $rawData['AMT'];
$localDate = date("Y") . date("m") . date("d");
$localTime = date("h") . date("i") . date("s");
$additionalData = $rawData['return_url'];
$callBackUrl = 'https://example.com/pgateway/pay/callback';
$payerId = '0';
/* Define parameters array */
$parameters = array(
'terminalId' => $terminalId,
'userName' => $userName,
'userPassword' => $userPassword,
'orderId' => $orderId,
'amount' => $amount,
'localDate' => $localDate,
'localTime' => $localTime,
'additionalData' => $additionalData,
'callBackUrl' => $callBackUrl,
'payerId' => $payerId
);
$result = $client->call('bpPayRequest', $parameters, $namespace);
if ($client->fault) {
echo '<h2>Fault</h2><pre>';
print_r($result);
echo '</pre>';
die();
} else { //Check for errors
$error = $client->getError();
if ($error) {
echo "An error occurred: ";
print_r($error);
die();
} else {
//break the code
$resultSegmts = explode(',', $result);
$ResCode = $resultSegmts [0];
if ($ResCode == "0") {
//Notify admin of the order
echo '<h3>Redirecting you to the payment page. Please wait...</h3><br/>';
echo '<script language="javascript" type="text/javascript">
postRefId("' . $resultSegmts[1] . '");
</script>';
} elseif ($ResCode == "25") {
echo "<h3>Purchase successful</h3>";
} else {
echo "<h3>PSP response is: $ResCode</h3>";
}
}
}
Add to your callBack action:
$this->view->message = 'This is callback action for PayController';
$RefId = $_POST['RefId'];
$ResCode = $_POST['ResCode'];
$saleOrderId = $_POST['SaleOrderId'];
$saleReferenceId = $_POST['SaleReferenceId'];
$this->_orderId = $saleOrderId;
$this->view->RefId = $RefId;
$this->view->saleOlderId = $saleOrderId;
$this->view->saleReferenceId = $saleReferenceId;
}
if ($ResCode == "0") {
try {
$client = new nusoap_client('https://example.com/pgwchannel/services/pgw?wsdl');
} catch (Exception $e) {
die($e->getMessage());
}
$namespace = 'http://interfaces.core.sw.example.com/';
$terminalId = "111111";
$userName = "username";
$userPassword = "11111111";
$parameters = array(
'terminalId' => $terminalId,
'userName' => $userName,
'userPassword' => $userPassword,
'orderId' => $saleOrderId,
'saleOrderId' => $saleOrderId,
'saleReferenceId' => $saleReferenceId
);
$resVerify = $client->call('bpVerifyRequest', $parameters, $namespace);
if ($resVerify->fault) { //Check for fault
echo "<h1>Fault: </h1>";
print_r($result);
die();
} else { //No fault: check for errors now
$err = $client->getError();
if ($err) {
echo "<h1>Error: " . $err . " </h1>";
} else {
if ($resVerify == "0") {//Check verification response: if 0, then purchase was successful.
echo "<div class='center content green'>Payment successful. Thank you for your order.</div>";
$this->view->message = $this->_translate('Thanks for your purchase.');
$this->dbSave(); //update database table
} else
echo "<script language='javascript' type='text/javascript'>alert( 'Verification Response: " . $resVerify . "');</script>";
}
}
//Note that we need to send bpSettleRequest to PSP service to request settlement once we have verified the payment
if ($resVerify == "0") {
// Update table, Save RefId
//Create parameters array for settle
$this->sendEmail();
$this->sendSms();
$resSettle = $client->call('bpSettleRequest', $parameters, $namespace);
//Check for fault
if ($resSettle->fault) {
echo "<h1>Fault: </h1><br/><pre>";
print_r($resSettle);
echo "</pre>";
die();
} else { //No fault in bpSettleRequest result
$err = $client->getError();
if ($err) {
echo "<h1>Error: </h1><pre>" . $err . "</pre>";
die();
} else {
if ($resSettle == "0" || $resSettle == "45") {//Settle request successful
// echo "<script language='javascript' type='text/javascript'>alert('Payment successful');</script>";
}
}
}
}
} else {
echo "<div class='center content error'>Payment failed. Please try again later.</div> ";
// log error in app
// Update table, log the error
// Show proper message to user
}
$returnUrl = 'https://example.com/stores/products'; //Go to store home for now. Later I'll set this to the last page
echo "<div class='center'>";
echo "<form action=$returnUrl method='POST'>";
echo "<input class='center' id='returnstore' type='submit' value='Return to store'/>";
echo "</form>";
echo "</div>";

Related

Yii Framework and Authorize.net Create profile

I have a little problem with authorize.net and yiiframework
I need to create a customer account in authorize.net system with data from my webiste with api.
I'm using this extension https://www.yiiframework.com/extension/authorize-net-cim-yii-extension , but without success.
Share with you what I'm trying to do
ajax return is with code 500
The variable error should return error or success, but actually return nothing
thanks in advance
$userInfo = [
'type' => 'Payment', //Payment OR Withdraw
'user_id' => 12314,
'profile_id' => 1231231,
'email' => $this->data['email_address'],
];
echo Yii::app()->authorizenetCIM->authNetCreateProfile($userInfo);
// $result = Yii::app()->authorizenetCIM->authNetCreateProfile($userInfo);
if ($result != "error") {
$this->msg = t("success");
return ;
} else {
$this->msg=t("error");
return ;
}
public function authNetCreateProfile($data) //$type = Payment OR Withdraw
{
//build xml to post
$content =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" .
"<createCustomerProfileRequest xmlns=\"AnetApi/xml/v1/schema/AnetApiSchema.xsd\">" .
$this->getMerchantAuthenticationBlock().
"<profile>".
"<merchantCustomerId>" . CHtml::encode(strip_tags($data['type']))."-".CHtml::encode(strip_tags($data['user_id']))."-".CHtml::encode(strip_tags($data['profile_id'])) ."</merchantCustomerId>". // Your own identifier for the customer.
"<description></description>".
"<email>" . CHtml::encode(strip_tags($data['email'])) . "</email>".
"</profile>".
"</createCustomerProfileRequest>";
$response = $this->sendXMLRequest($content);
$parsedresponse = $this->parseAPIResponse($response);
if ("Ok" == $parsedresponse->messages->resultCode) {
return htmlspecialchars($parsedresponse->customerProfileId);
}
return "error";
}

Adding more details to webhook

I am using Instamojo for my laravel app.
I have a form with input name like vtype, vname, name, phone, date, price.
My instamojo index.php looks like this --
<?php
use App\Vname;
$vname = Vname::find($request->vname);
$api = new Instamojo\Instamojo(config('instamojo.api_key'), config('instamojo.auth_token'), 'https://test.instamojo.com/api/1.1/');
try {
$response = $api->paymentRequestCreate(array(
"purpose" => "Online Vazhipad",
"amount" => $vname->price,
"buyer_name" => $request->name,
"phone" => $request->phone,
"send_email" => true,
"email" => Auth::user()->email,
"allow_repeated_payments" => false,
"redirect_url" => url('/online_vazhipad/thankyou')
"webhook" => url('/online_vazhipad/webhook')
));
$pay_ulr = $response['longurl'];
header("Location: $pay_ulr");
exit();
}
catch (Exception $e) {
print('Error: ' . $e->getMessage());
}
?>
and my webhook file looks like this -
<?php
$data = $_POST;
$mac_provided = $data['mac'];
unset($data['mac']);
$ver = explode('.', phpversion());
$major = (int) $ver[0];
$minor = (int) $ver[1];
if($major >= 5 and $minor >= 4){
ksort($data, SORT_STRING | SORT_FLAG_CASE);
}
else{
uksort($data, 'strcasecmp');
}
$mac_calculated = hash_hmac("sha1", implode("|", $data), config('instamojo.private_salt'));
if($mac_provided == $mac_calculated){
echo "MAC is fine";
if($data['status'] == "Credit"){
// Payment was successful my database code will be placed here
}
else{
return 'failed';
}
}
else{
echo "Invalid MAC passed";
}
?>
I wanted to add more information to my database like vtype and vname, but I dont know how to get the data from the form to here.
From the documentation i came to know that, the post request we get from instamojo only contains this much.
Please help me.

Passing Form data from outside to CodeIgniter

I am trying to pass a form data like name, email from simple html page to a CodeIgniter application.
Direcotry Structute:
SampleDir
CodeIgniterApp
Form.html
I am trying to pass form (POST) and recieve inside the CodeIgniter. I am new to CodeIgniter and trying to connect my app to third party app. From what I searched CodeIgniter has controllers and views. Controllers being called first which inturn load up the view.
I tried
$view = array (
'available_services' => $available_services,
'available_providers' => $available_providers,
'company_name' => $company_name,
'manage_mode' => $manage_mode,
'appointment_data' => $appointment,
'provider_data' => $provider,
'customer_data' => $customer,
'post_data' => json_decode($_POST)
);
and passing it to view, but it does not shows up.
HTML Code:
<form action="/appointment" method="POST" target="_blank">
<div style="display:none!important;">
<input type="text" placeholder="name" name="name" id="name" ng-model="cust.name">
<input type="text" placeholder="email" name="email" id="email" ng-model="cust.email">
<input type="text" placeholder="telephone" name="phone" id="phone" ng-model="cust.phone">
</div>
<div class="text-center btn-toolbar" style="margin-top: 30px;">
<button class="btn btn-primary" ng-click="cancel()" style="font-size: 20px;">OK</button>
<button type="submit" name="process" class="btn btn-success" style="font-size: 20px;">Schedule a Call</button>
</div>
</form>
Controller Code:
public function index($appointment_hash = '') {
// echo $this->input->post('email');
var_dump($_SERVER['REQUEST_METHOD']);
if (!$this->check_installation()) return;
$this->load->model('appointments_model');
$this->load->model('providers_model');
$this->load->model('services_model');
$this->load->model('customers_model');
$this->load->model('settings_model');
if (strtoupper($_SERVER['REQUEST_METHOD']) !== 'POST') {
try {
$available_services = $this->services_model->get_available_services();
$available_providers = $this->providers_model->get_available_providers();
$company_name = $this->settings_model->get_setting('company_name');
// If an appointment hash is provided then it means that the customer
// is trying to edit a registered appointment record.
if ($appointment_hash !== ''){
// Load the appointments data and enable the manage mode of the page.
$manage_mode = TRUE;
$results = $this->appointments_model->get_batch(array('hash' => $appointment_hash));
if (count($results) === 0) {
// The requested appointment doesn't exist in the database. Display
// a message to the customer.
$view = array(
'message_title' => $this->lang->line('appointment_not_found'),
'message_text' => $this->lang->line('appointment_does_not_exist_in_db'),
'message_icon' => $this->config->item('base_url')
. '/assets/img/error.png'
);
$this->load->view('appointments/message', $view);
return;
}
$appointment = $results[0];
$provider = $this->providers_model->get_row($appointment['id_users_provider']);
$customer = $this->customers_model->get_row($appointment['id_users_customer']);
} else {
// The customer is going to book a new appointment so there is no
// need for the manage functionality to be initialized.
$manage_mode = FALSE;
$appointment = array();
$provider = array();
$customer = array();
}
// Load the book appointment view.
$view = array (
'available_services' => $available_services,
'available_providers' => $available_providers,
'company_name' => $company_name,
'manage_mode' => $manage_mode,
'appointment_data' => $appointment,
'provider_data' => $provider,
'customer_data' => $customer,
'post_data' => json_decode($_POST)
);
} catch(Exception $exc) {
$view['exceptions'][] = $exc;
}
$this->load->view('appointments/book', $view);
} else {
// The page is a post-back. Register the appointment and send notification emails
// to the provider and the customer that are related to the appointment. If google
// sync is enabled then add the appointment to the provider's account.
try {
$post_data = json_decode($_POST['post_data'], true);
$appointment = $post_data['appointment'];
$customer = $post_data['customer'];
if ($this->customers_model->exists($customer))
$customer['id'] = $this->customers_model->find_record_id($customer);
$customer_id = $this->customers_model->add($customer);
$appointment['id_users_customer'] = $customer_id;
$appointment['id'] = $this->appointments_model->add($appointment);
$appointment['hash'] = $this->appointments_model->get_value('hash', $appointment['id']);
$provider = $this->providers_model->get_row($appointment['id_users_provider']);
$service = $this->services_model->get_row($appointment['id_services']);
$company_settings = array(
'company_name' => $this->settings_model->get_setting('company_name'),
'company_link' => $this->settings_model->get_setting('company_link'),
'company_email' => $this->settings_model->get_setting('company_email')
);
// :: SYNCHRONIZE APPOINTMENT WITH PROVIDER'S GOOGLE CALENDAR
// The provider must have previously granted access to his google calendar account
// in order to sync the appointment.
try {
$google_sync = $this->providers_model->get_setting('google_sync',
$appointment['id_users_provider']);
if ($google_sync == TRUE) {
$google_token = json_decode($this->providers_model
->get_setting('google_token', $appointment['id_users_provider']));
$this->load->library('google_sync');
$this->google_sync->refresh_token($google_token->refresh_token);
if ($post_data['manage_mode'] === FALSE) {
// Add appointment to Google Calendar.
$google_event = $this->google_sync->add_appointment($appointment, $provider,
$service, $customer, $company_settings);
$appointment['id_google_calendar'] = $google_event->id;
$this->appointments_model->add($appointment);
} else {
// Update appointment to Google Calendar.
$appointment['id_google_calendar'] = $this->appointments_model
->get_value('id_google_calendar', $appointment['id']);
$this->google_sync->update_appointment($appointment, $provider,
$service, $customer, $company_settings);
}
}
} catch(Exception $exc) {
$view['exceptions'][] = $exc;
}
// :: SEND NOTIFICATION EMAILS TO BOTH CUSTOMER AND PROVIDER
try {
$this->load->library('Notifications');
$send_provider = $this->providers_model
->get_setting('notifications', $provider['id']);
if (!$post_data['manage_mode']) {
$customer_title = $this->lang->line('appointment_booked');
$customer_message = $this->lang->line('thank_you_for_appointment');
$customer_link = $this->config->item('base_url') . '/index.php/appointments/index/'
. $appointment['hash'];
$provider_title = $this->lang->line('appointment_added_to_your_plan');
$provider_message = $this->lang->line('appointment_link_description');
$provider_link = $this->config->item('base_url') . '/index.php/backend/index/'
. $appointment['hash'];
} else {
$customer_title = $this->lang->line('appointment_changes_saved');
$customer_message = '';
$customer_link = $this->config->item('base_url') . '/index.php/appointments/index/'
. $appointment['hash'];
$provider_title = $this->lang->line('appointment_details_changed');
$provider_message = '';
$provider_link = $this->config->item('base_url') . '/index.php/backend/index/'
. $appointment['hash'];
}
$this->notifications->send_appointment_details($appointment, $provider,
$service, $customer,$company_settings, $customer_title,
$customer_message, $customer_link, $customer['email']);
if ($send_provider == TRUE) {
$this->notifications->send_appointment_details($appointment, $provider,
$service, $customer, $company_settings, $provider_title,
$provider_message, $provider_link, $provider['email']);
}
} catch(Exception $exc) {
$view['exceptions'][] = $exc;
}
// :: LOAD THE BOOK SUCCESS VIEW
$view = array(
'appointment_data' => $appointment,
'provider_data' => $provider,
'service_data' => $service,
'company_name' => $company_settings['company_name']
);
} catch(Exception $exc) {
$view['exceptions'][] = $exc;
}
$this->load->view('appointments/book_success', $view);
}
}
$this->load->view('appointments/book', $view);
To be more precise, this the the app I am trying to connect to https://github.com/alextselegidis/easyappointments
If the root src folder is appointment, then http://localhost/appointment takes me to appointment/application/views/appointments/book.php and appointment/application/controllers/appointments.php
Have a look and suggest what to do.
I have this trouble too, you have to add this line on your code:
$_POST = json_decode(file_get_contents("php://input"), true);
that would let you use json on code igniter post so after that line you can do
$this->input->post('yourkey')
and you will get the things you want :)

how can i stop a second php function from implementing if a first php function throws an exception

hello i am working on a project where by, data is collected from a form, this data is posted from the form to a webservice and a database.
they both work properly, but i need to put some checks in place.
i am try to halt the process flow of my functions based on when ever the first function fails.
the first function is the one that posts the data collected to a webservice. below :
<?php
require_once('includes/nusoap.php');
$wsdlfile = "https://niid.autoreglive.org/nia_api/service.asmx?wsdl";
$wsdlfile = "https://www.niid.org/NIA_API/Service.asmx?wsdl";
//$wsdlfile = "http://localhost:82/cscart/service/index.php";
$msg = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>
<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">
<Username>name</Username>
<Password>pass</Password>
<NiaNaicomID>nnn</NiaNaicomID>
<PolicyNo>TP/1/1</PolicyNo>
<InsuredName>Sunky Yaki</InsuredName>
<ContactAddress>Yaba Lagos</ContactAddress>
<GSMNo>08021231234</GSMNo>
<Email>a#b.c</Email>
<EffectiveCoverDate>2013-09-20</EffectiveCoverDate>
<ExpirationDate>2014-09-19</ExpirationDate>
<TypeOfCover>Comprehensive</TypeOfCover
><VehicleCategory>Saloon</VehicleCategory>
<EngineNo>uhdu</EngineNo>
<ChasisNo>dksdj</ChasisNo>
<VehicleColor>green</VehicleColor>
<YearofMake>1999</YearofMake>
<VehicleMake>Toyota</VehicleMake>
<RegistrationNo>gg11jj</RegistrationNo>
<OldRegistrationNo>11122</OldRegistrationNo>
<VehicleType>Saloon</VehicleType>
<EngineCapacity>4</EngineCapacity>
<VehicleModel>Camry</VehicleModel>
<SumAssured>233300</SumAssured>
<Premium>230</Premium>
<CoverNoteNo>1211</CoverNoteNo>
<CertificateNo>test 2</CertificateNo>
<GeographicalZone>North East</GeographicalZone>
</soap:Envelope>
";
$Username = '******';
$Password = '******';
$NiaNaicomID = '******';
$PolicyNo = $_POST['Policy_Number'];
$InsuredName = $_POST['Insured_Name'];
$ContactAddress = $_POST['Residential_Address'];
$GSMNo = $_POST['phone'];
$Email = $_POST['Email'];
$EffectiveCoverDate = $_POST['Date'];
$ExpirationDate = $_POST['Date_Expiry'];
$TypeOfCover = $_POST['Type_Of_Insurance'];
$VehicleCategory = 'null';
$EngineNo = $_POST['Engine_Number'];
$ChasisNo = $_POST['Chassis_Number'];
$VehicleColor = $_POST['Colour'];
$YearofMake = '2004';
$VehicleMake = $_POST['Make_Of_Car'];
$RegistrationNo = $_POST['Registeration_Number'];
$VehicleType = $_POST['Vehicle_Class'];
$EngineCapacity = '';
$VehicleModel = 'Model';
$SumAssured = 2.3;
$Premium = '2.3';
$CoverNoteNo = 'No note';
$CertificateNo = 'No certificate No';
$GeographicalZone = '6';
$params = array('Username' => $Username,
'Password' => $Password,
'NiaNaicomID' => $NiaNaicomID,
'PolicyNo' => $PolicyNo,
'InsuredName' => $InsuredName,
'ContactAddress' => $ContactAddress,
'GSMNo' => $GSMNo,
'Email' => $Email,
'EffectiveCoverDate' => $EffectiveCoverDate,
'ExpirationDate' => $ExpirationDate,
'TypeOfCover' => $TypeOfCover,
'VehicleCategory' => $VehicleCategory,
'EngineNo' => $EngineNo,
'ChasisNo' => $ChasisNo,
'VehicleColor' => $VehicleColor,
'YearofMake' => $YearofMake,
'VehicleMake' => $VehicleMake,
'RegistrationNo' => $RegistrationNo,
'VehicleType' => $VehicleType,
'EngineCapacity' => $EngineCapacity,
'VehicleModel' => $VehicleModel,
'SumAssured' => $SumAssured,
'Premium' => $Premium,
'CoverNoteNo' => $CoverNoteNo,
'CertificateNo' => $CertificateNo,
'GeographicalZone' => $GeographicalZone
);
$s = new nusoap_client($wsdlfile, 'wsdl');
//$s = new nusoap_client($wsdlfile);
// if (empty($proxyhost))
// {
// }else
// {
// $s->setHTTPProxy($proxyhost,$proxyport,$proxyusr,$proxypassword);
// }
$result = $s->call('Vehicle_Policy_Push', $params, '', '', false, true);
if($result){
print_r($result);
echo '<META HTTP-EQUIV="Refresh" Content="3; URL=account.php">';
}else{
echo '<META HTTP-EQUIV="Refresh" Content="3; URL=policy_active.php">';
}
?>
and this is the second function that i want to be halted whenever my first function fails below :
<?php
$con=mysqli_connect
("localhost","*******","*******","*******");
//Checkconnection
if(mysqli_connect_errno())
{
echo"FailedtoconnecttoMySQL:".mysqli_connect_error();
}
$check="SELECT * FROM transactions WHERE year_find = '$_POST[year_find]'";
$rs = mysqli_query($con,$check);
$data = mysqli_fetch_array($rs, MYSQLI_NUM);
if($data[0] > 1) {
echo '<META HTTP-EQUIV="Refresh" Content="3; URL=policy_active.php">';
}
else
{
$sql="INSERT INTO transactions(month_search,month,year_search,year,year_find,Username,Insured_Name,combined,Residential_Address,Telephone,Email,Make_Of_Car,Model,Engine_Number,Year_Of_Manufacture,Chassis_Number,Vehicle_Class,Colour,Registeration_Number,Product_Type,Premium,Policy_Number,Start_Date,Expiry_Date,Date_Begin,Type_Of_Insurance,Status, Transaction_id)VALUES('$_POST[month_search]','$_POST[month]','$_POST[year_year]','$_POST[newyear]','$_POST[year_find]','$_POST[Username]','$_POST[Insured_Name]','$_POST[combined]','$_POST[Residential_Address]','$_POST[phone]','$_POST[Email]','$_POST[Make_Of_Car]','$_POST[Model]','$_POST[Engine_Number]','$_POST[Year_Of_Manufacture]','$_POST[Chassis_Number]','$_POST[Vehicle_Class]','$_POST[Colour]','$_POST[Registeration_Number]','$_POST[Product_Type]','$_POST[Premium]','$_POST[Policy_Number]','$_POST[Date]','$_POST[Date_Expiry]','$_POST[Date_Begin]','$_POST[Type_Of_Insurance]','$_POST[Status]','$_POST[Transaction_id]')";
}
if(!mysqli_query($con,$sql))
{
die('Error:'.mysqli_error
($con));
}
echo '<META HTTP-EQUIV="Refresh" Content="3; URL=account.php">';
mysqli_close($con);
?>
the second function submits the data to a database.
ordinary i was hoping the second function would fail to run when the first function failed, but imwas wrong, it moved on to the other function, which then submitted the unwanted data to the database.
so am wondering how i can halt the second function based on the failure of the first.
You should try using a try...catch block. Second function will be called only when first doesn't throw an exception.
function postData(){
// code to post data here
// throw exception when something fails
throw new Exception('I am an exception message');
}
function saveData(){
// code to save data here
}
try{
postData();
saveData();
}
catch( Exception $e ){
echo $e->getMessage();
}
Read more about exceptions at php.net

Yii radioButtonList: always takes the default value as the selected value

I have Yii radio button list as follows.
forgotpassword1.php
<?php echo $form->radioButtonList($model, 'send_option', $email_exist); ?>
This is the action for forgotpassword1.
public function actionForgotpwd2() {
$model = new User;
$email_exist = array('mobile' => 'Send SMS to Mobile');
$model -> setScenario('forgotpwd2');
$model -> send_option='mobile';
$postvars = array('conn' => Yii::app()->session['mobile']);
$postRes = SCAppUtils::getInstance()->post_request('accounts', 'CheckAccount', $postvars);
$out_arr = json_decode($postRes, true);
//print_r($out_arr);
if ($out_arr['success'] == true && $out_arr['email'] == true) {
$email_exist['email'] = 'Send an E-mail';// = array('mobile' => 'Send SMS to Mobile', 'email' => '');
} else if ($out_arr['success'] == false) {
Yii::app()->user->setFlash('error', $out_arr['error']);
$this->redirect(array('forgotpwd1'));
}
if (!empty($_POST['User'])) {
$model->attributes = $_POST['User'];
echo Yii::app()->session['mobile'];
//print_r($_POST);
if(isset($_POST['User']['send_option'])) {
//Yii::app()->session['send_option'] = $model->send_option;
echo Yii::app()->session['send_option'];
$postvars = array('conn' => Yii::app()->session['mobile'], 'send_type' => $model->send_option);
$postRes = SCAppUtils::getInstance()->post_request('accounts', 'ChangePassword', $postvars);
$out_arr = json_decode($postRes, true);
// print_r($out_arr);
if ($out_arr['success'] == true) {
$this->redirect(array('forgotpwd3'));
} else {
Yii::app()->user->setFlash('error', $out_arr['error']);
}
}
}
$this->render('forgotpwd2', array(
'model' => $model, 'email_exist' => $email_exist
));
}
Here I call a function named "ChangePassword()" from my backend application. One of the parameters passed to the backend is send_type: mobile or email. The problem is it will always takes mobile as the send_type.
I've used
$model -> send_option='mobile';
to set the default value as mobile.
Why it always takes mobile as the send type.
Any suggestions are appreciated.
Thank you in advance
Try with this :
<?=$form->radioButtonList($model,'send_option',array(1=>'Mobile',2=>'Email'))?>
In your Acion :
To set the default value :
$model -> send_option=1;
To get the checked value (check whether it's 1 or 2) :
$_POST['send_option']

Categories