Adding more details to webhook - php

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.

Related

How to check if value exist in json file using php?

<?php
if(isset($_POST['submit']))
{
$file = 'entries.json';
$json_file = file_get_contents($file);
$parsed_json = json_decode($json_file, true);
$email = $_POST['email'];
$flag = false;
foreach ($parsed_json as $key => $value)
{
if ($value['email'] == $email)
{
$flag = true;
break;
}
}
if ($flag)
{
$arr = array(
"centre" => $_POST['centre'],
"name" => $_POST['name'],
"email" => $_POST['email'],
"phone" => $_POST['phone'],
"city" => $_POST['city'],
"course" => $_POST['course']
);
$json_string = json_encode($arr);
$success = file_put_contents($file, $json_string);
if($success == true)
{
echo "<p class='text-success'>Thank you for showing interest. Please contact your counsellor for Unique Registration Number (URN)<p>";
}
}
else
{
echo "<p class='text-danger'>Email already exist.<p>";
}
}
?>
In the above code I am trying to validate with email id already exist when we post form data in json format. Here, Json format working perfectly but it always show thank you message. If email exist or not.
When I click on submit then all data post and convert in json successfully and I am fetching this data in other website but I want to show here that email id already exist. So, How can I do this? Please help me.
Thank You

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

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

PHP YouTube API, get upload status

I'm having a heck of a time trying to get the status of a uploaded video to YouTube. I've followed the bellow URL to setup a CRON job that would send videos to YouTube, get a response; preferably with the YouTube ID so I can save this in a database. Down side is I can not get this to work.
http://framework.zend.com/manual/1.12/en/zend.gdata.youtube.html
My Code: (Which is basically copy and past from the above URL)
function upload($filename, $options = array()) {
$default = array_merge(
array(
'username' => 'USERNAME',
'password' => 'PASSWORD',
'service' => 'youtube',
'client' => null,
'source' => 'YouTube Component',
'loginToken' => null,
'loginCaptcha' => null,
'authenticationURL' => 'https://www.google.com/accounts/ClientLogin',
'applicationId' => 'YouTube Component',
'clientId' => 'YouTube Component',
'developerKey' => 'DEVELOPERS-KEY',
'content_type' => 'video/quicktime',
'title' => null,
'description' => null,
'category' => null,
'tags' => null,
),
(array)$options
);
extract($default);
$this->controller->Zend->loadClass('Zend_Gdata_YouTube');
$this->controller->Zend->loadClass('Zend_Gdata_ClientLogin');
$httpClient = Zend_Gdata_ClientLogin::getHttpClient(
$username,
$password,
$service,
$client,
$source,
$loginToken,
$loginCaptcha,
$authenticationURL
);
$yt = new Zend_Gdata_YouTube($httpClient, $applicationId, $clientId, $developerKey);
$myVideoEntry = new Zend_Gdata_YouTube_VideoEntry();
$filesource = $yt->newMediaFileSource($filename);
$filesource->setContentType($content_type);
$filesource->setSlug($filename);
$myVideoEntry->setMediaSource($filesource);
$myVideoEntry->setVideoTitle($title);
$myVideoEntry->setVideoDescription($description);
$myVideoEntry->setVideoCategory($category);
$myVideoEntry->SetVideoTags($tags);
$myVideoEntry->setVideoPrivate();
$uploadUrl = 'http://uploads.gdata.youtube.com/feeds/api/users/default/uploads';
try {
$newEntry = $yt->insertEntry($myVideoEntry, $uploadUrl, 'Zend_Gdata_YouTube_VideoEntry');
} catch (Zend_Gdata_App_HttpException $httpException) {
echo $httpException->getRawResponseBody();
} catch (Zend_Gdata_App_Exception $e) {
echo $e->getMessage();
}
try {
$control = $myVideoEntry->getControl();
} catch (Zend_Gdata_App_Exception $e) {
echo $e->getMessage();
}
if ($control instanceof Zend_Gdata_App_Extension_Control) {
if ($control->getDraft() != null && $control->getDraft()->getText() == 'yes') {
$state = $myVideoEntry->getVideoState();
if ($state instanceof Zend_Gdata_YouTube_Extension_State) {
print 'Upload status: ' . $state->getName() .' '. $state->getText();
} else {
print 'Not able to retrieve the video status information' .' yet. ' . "Please try again shortly.\n";
}
}
}
}
The above works in every way, minus the fact that I always get "Not able to retrieve the video status information...". What am I doing wrong? I've been staring at this for hours so I imagine its something simple that I've missed.
I wasn't to terribly far off with completing this. The answer was to replace all of the return code with (customized a bit because I need a return value as this is a CakePHP component.):
$state = $newEntry->getVideoState();
if ($state) {
$response['id'] = $newEntry->getVideoId();
} else {
$response['error'] = "Not able to retrieve the video status information yet. " .
"Please try again later.\n";
}
return $response;

eWay Payment Gateway

I'm trying to implement the recurring web service from eway(australia).How ever I could not get it to work.
I keep on getting the messeage
"The element 'rebillCustomerCreate' in namespace 'http://www.eway.com.au/gateway/rebill/manageRebill' has incomplete content. List of possible elements expected: 'CustomerRef'."
This is the WSDL: https://www.eway.com.au/gateway/rebill/test/manageRebill_test.asmx?wsdl
I am new to SOAP. Trying to implement it in PHP. Can anyone please point out what I did wrong?
Here is my php Code:
<?php
$URL = "https://www.eway.com.au/gateway/rebill/test/manageRebill_test.asmx?wsdl";
$option = array("trace"=>true);
$client = new SOAPClient($URL, $option);
$functions = $client->__getFunctions();
$headeroptions =array('eWAYCustomerID'=>"87654321",'Username'=>"test#eway.com.au","Password"=>"test");
$header = new SOAPHeader('http://www.eway.com.au/gateway/rebill/manageRebill', 'eWAYHeader',$headeroptions);
$bodyoptions = array(
"customerTitle" => "Mr",
"customerFirstName" => "firstname",
"customerLastName" => "lastname",
"customerAddress" => "address",
"customerSuburb" => "someniceplace",
"customerState" => "somenicestate",
"customerCompany" => "somecompany",
"customerPostCode" => "411026",
"customerCountry" => "australia",
"customerEmail" => "test#eway.com",
"customerFax" => "123456",
"customerPhone1" => "123456",
"customerPhone2" => "123456",
"customerRef" => "abc123",
"customerJobDesc" => "Developer",
"customerComments" => "Make it work",
"customerURL" => "www.nicesite.com"
);
try{
$response = $client->__soapCall("CreateRebillCustomer", $bodyoptions,NULL,$header,$outputHeader);
echo $client->__getLastRequest();
//$response = $client->CreateRebillCustomer($bodyoptions);
var_dump($response);
} catch(SOAPFault $e){
print $e;
}
?>
What I tried to create eWay recurring billing and customer,
hope it will help for others new :)
<?php
$URL = "https://www.eway.com.au/gateway/rebill/test/manageRebill_test.asmx?wsdl";
$option = array("trace"=>true);
$client = new SOAPClient($URL, $option);
$functions = $client->__getFunctions();
$headeroptions =array('eWAYCustomerID'=>"87654321",'Username'=>"test#eway.com.au","Password"=>"test123");
$header = new SOAPHeader('http://www.eway.com.au/gateway/rebill/manageRebill', 'eWAYHeader',$headeroptions);
$bodyoptions = array(
"CreateRebillCustomer" => array(
"customerTitle" => "Mr",
"customerFirstName"=>"Muhammad",
"customerLastName"=>"Shahzad",
"customerAddress"=>"cust ome rAddress",
"customerSuburb"=>"customer Suburb",
"customerState"=>"ACT",
"customerCompany"=>"customer Company",
"customerPostCode"=>"2345",
"customerCountry"=>">Australia",
"customerEmail"=>"test#gamil.com",
"customerFax"=>"0298989898",
"customerPhone1"=>"0297979797",
"customerPhone2"=>"0297979797",
"customerRef"=>"Ref123",
"customerJobDesc"=>"customerJobDesc",
"customerComments"=>"customerComments",
"customerURL" => "http://www.acme.com.au"
)
);
try{
$response = $client->__soapCall("CreateRebillCustomer", $bodyoptions,NULL,$header,$outputHeader);
//echo $client->__getLastRequest();
//$response = $client->CreateRebillCustomer($bodyoptions);
//echo "<pre>";echo "<br/>";
// print_r($response);
echo $result = $response->CreateRebillCustomerResult->Result;echo "<br/>";
echo $customerId = $response->CreateRebillCustomerResult->RebillCustomerID;echo "<br/>";
echo "<br/>";
if($result=='Success' AND $customerId){
echo 'Member Created at eWay Successfully!...<br/>';
echo 'Creating Recurring Billing Cycle on eWay,Please wait......<br/>';
//$UpdateRebillCustomer = CreateRebillEvent($customerId);
//print_r($UpdateRebillCustomer);
}
else{
echo $ErrorSeverity = $response->CreateRebillCustomerResult->ErrorSeverity;echo "<br/>";
echo $ErrorDetails = $response->CreateRebillCustomerResult->ErrorDetails;echo "<br/>";
}
}
catch(SOAPFault $e){
print $e;
}
if($customerId){
$bodyoptions2 = array(
"CreateRebillEvent " => array(
"RebillCustomerID" => $customerId,
"RebillInvRef" => "Ref123",
"RebillInvDes"=>"description",
"RebillCCName"=>"Mr Andy Person",
"RebillCCNumber"=>"4444333322221111",
"RebillCCExpMonth"=>"12",
"RebillCCExpYear"=>"15",
"RebillInitAmt"=>"100",
"RebillInitDate"=>date('d/m/Y'),
"RebillRecurAmt"=>"200",
"RebillStartDate"=>date('d/m/Y'),
"RebillInterval"=>"31",
"RebillIntervalType"=>"1",
"RebillEndDate"=>"31/12/2013",
)
);
try{
$response = $client->__soapCall("CreateRebillEvent", $bodyoptions2,NULL,$header,$outputHeader);
//echo $client->__getLastRequest();
//print_r($response);
echo "<br/>";
echo $result2 = $response->CreateRebillEventResult->Result;echo "<br/>";
echo $RebillCustomerID = $response->CreateRebillEventResult->RebillCustomerID;echo "<br/>";
if($result2=='Success'){
echo 'Recurring Cycle Created Successfully at eWay!...<br/>';
echo 'Member Id is ===>'.$RebillCustomerID;
//$UpdateRebillCustomer = CreateRebillEvent($customerId);
//print_r($UpdateRebillCustomer);
}
else{
echo $ErrorSeverity = $response->CreateRebillEventResult->ErrorSeverity;echo "<br/>";
echo $ErrorDetails = $response->CreateRebillEventResult->ErrorDetails;echo "<br/>";
}
}
catch(SOAPFault $e){
print $e;
}
}
?>
I suggest you to use the library and sample provided by eWay.
Go to this page. Go to "Source Code" tab. The, download PHP source code. There is instruction also.
2 years later, I've just had the very same issue !
Might be useful to someone:
$bodyoptions = array(
"CreateRebillCustomer" => array(
"customerTitle" => "Mr",
...
)
);

Categories