Yii Framework and Authorize.net Create profile - php

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";
}

Related

Response issue in codeigniter & MongoDB

I have a set up that I require a count on a collection, I just keep getting an error of
{"status":false}
My model looks like:
public function count_users() {
$query = $this->mongo_db->get('users');
$row_count = count($query);
$data = $row_count;
$return = [
'status' => true,
'data' => $data
];
}
and my controller is such :
// **
// ** List Todays Stats for Admin Panel
// **
public function todaysstats_get() {
//Validate user - logged in as admin -- session required
$this->session_model->check_session();
//Count Users
$data = $this->admin_model->count_users();
$http = $this->data_model->status_to_http_response($data['status']);
$data['status'] = $http['status'];
$http_response = $http['http_response'];
$this->set_response($data, $http_response);
}
I'm using a GET method to get the simple count return number
$route['v1/admin/todaysstats'] = 'v1/admin/todaysstats';
I have tried a few different ways but it just doesn't seem to change the status on the REST request.
The method for $http = $this->data_model->status_to_http_response($data['status']);
public function status_to_http_response($status) {
// Select appropriate HTTP Response code, based on "status"
// true ---> 200
// false ---> 422 (usually a validation error)
// else ---> use the value in "status" and set "status" to false.
$status = intval($status);
// If "true" send back a 200
if ($status == 1) {
$http = REST_Controller::HTTP_OK;
$status = true;
}
// If "false" send back a 422
elseif ($status == 0) {
$http = REST_Controller::HTTP_UNPROCESSABLE_ENTITY;
$status = false;
}
// Otherwise use the status code given
else {
$http = $status;
$status = false;
}
return [
'http_response' => $http,
'status' => $status,
];
}

How to add a custom payment gateway to Social Engine

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>";

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.

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']

Error #520009 - Account is restricted

I get a 520009 error (Account xx#xx.com is restricted) when trying to make a parallel payment. My code worked fine using the sandbox but I switched to the live endpoint and it began failing. The account in question is a valid paypal account and I am using "feespayer=SENDER". Am I missing something? Shouldn't the pay call go through even if the payee is a basic account? Why would this occur?
Here is my code for reference
function deposit($config) {
try {
if (isset($config['return_url']))
$this->return_url = $config['return_url'];
else
return 'Return URL should be set';
if (isset($config['return_url']))
$this->cancel_url = $config['cancel_url'];
else
return 'Cancel URL should be set';
if (isset($config['email']))
$this->sender_email = $config['email'];
else
return 'Email should be defined';
if (isset($config['amount']))
$this->amount = $config['amount'];
else
return 'Amount should be defined';
$returnURL = $this->return_url;
$cancelURL = $this->cancel_url;
$currencyCode = 'USD';
$memo = 'Deposit to ' . $this->ci->config->item('site_name');
$feesPayer = 'SENDER';
$payRequest = new PayRequest();
$payRequest->actionType = "PAY";
$payRequest->cancelUrl = $cancelURL;
$payRequest->returnUrl = $returnURL;
$payRequest->clientDetails = new ClientDetailsType();
$payRequest->clientDetails->applicationId = $this->ci->config->item('application_id');
$payRequest->clientDetails->deviceId = $this->ci->config->item('device_id');
$payRequest->clientDetails->ipAddress = $this->ci->input->ip_address();
$payRequest->currencyCode = $currencyCode;
//$payRequest->senderEmail = $this->sender_email;
$payRequest->requestEnvelope = new RequestEnvelope();
$payRequest->requestEnvelope->errorLanguage = "en_US";
$receivers = array();
$receiver = new receiver();
$receiver->email = $this->ci->config->item('moneyfan_account');
$receiver->amount = $this->amount;
$receiver->primary = 'false';
$receivers[] = $receiver;
$payRequest->receiverList = $receivers;
$payRequest->feesPayer = $feesPayer;
$payRequest->memo = $memo;
$ap = new AdaptivePayments();
$response = $ap->Pay($payRequest);
if (strtoupper($ap->isSuccess) == 'FAILURE') {
$this->ci->session->set_userdata('FAULTMSG', $ap->getLastError());
return json_encode(array('status' => 'false', 'msg' => $ap->getLastError()->error->errorId .' : '. $ap->getLastError()->error->message));
//redirect(site_url('home/api_error'));
} else {
$this->ci->session->set_userdata('payKey', $response->payKey);
if ($response->paymentExecStatus == "COMPLETED") {
redirect($returnURL);
} else {
$token = $response->payKey;
$payPalURL = PAYPAL_REDIRECT_URL . '_ap-payment&paykey=' . $token;
return json_encode(array('status' => 'true', 'msg' => $payPalURL));
//header("Location: " . $payPalURL);
}
}
} catch (Exception $ex) {
$fault = new FaultMessage();
$errorData = new ErrorData();
$errorData->errorId = $ex->getFile();
$errorData->message = $ex->getMessage();
$fault->error = $errorData;
$this->ci->session->set_userdata('FAULTMSG', $fault);
redirect(site_url('home/api_error'));
}
}
No! You cannot do that with a basic account.
For API to work you need to have a VERIFIED Business Account.
In their API it says:
NOTE:
The application owner must have a PayPal Business account.
There are two sources of reference for the PayPal API:
cms.paypal.com pages like the one referenced by Mihai Iorga, and
www.x.com pages like this one:
https://www.x.com/developers/paypal/documentation-tools/going-live-with-your-application
On x.com, it says you must have a verified business account, even though it is unclear from cms.paypal.com that this is the case.

Categories