<?php
namespace App\Service;
use App\Entity\AuthorizeNetErrorLog;
use App\Entity\Charges;
use App\Entity\Users;
use App\Repository\StudentsRepository;
use Psr\Log\LoggerInterface;
use net\authorize\api\contract\v1 as AnetAPI;
use net\authorize\api\controller as AnetController;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\Response;
class AuthorizeNetService
{
/**
* @var LoggerInterface
*/
private $logger;
/**
* @var ChargesService
*/
private $pckChargesService;
/**
* @var AuthorizeNetErrorLogService
*/
private $authorizeNetErrorLogService;
private StudentsRepository $studentsRepository;
public function __construct(
LoggerInterface $logger,
ChargesService $pckChargesService,
AuthorizeNetErrorLogService $authorizeNetErrorLogService,
CreditCardsService $creditCardsService,
StudentsRepository $studentsRepository,
) {
$this->logger = $logger;
$this->authorizeNetPlatform = $_ENV["AUTHNET_PLATFORM"] == 'P' ? \net\authorize\api\constants\ANetEnvironment::PRODUCTION :
\net\authorize\api\constants\ANetEnvironment::SANDBOX;
$this->pckChargesService = $pckChargesService;
$this->authorizeNetErrorLogService = $authorizeNetErrorLogService;
$this->creditCardService = $creditCardsService;
$this->studentsRepository = $studentsRepository;
}
private function getAuthentication()
{
$merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
$merchantAuthentication->setName($_ENV["AUTHNET_LOGIN_ID"]);
$merchantAuthentication->setTransactionKey($_ENV["AUTHNET_TRANSACTION_KEY"]);
return $merchantAuthentication;
}
private function processResponse($response,$studentId,$amount,$description,$apiMethod,$userId = null){
if ($response->getMessages()->getResultCode() == "Ok") {
$tresponse = $response->getTransactionResponse();
if ($tresponse != null && $tresponse->getMessages() != null) {
$transId = $tresponse->getTransId();
} else {
// echo "Transaction Failed \n";
if ($tresponse->getErrors() != null) {
$this->logger->error('charge ERROR: ' . $tresponse->getErrors()[0]->getErrorCode() . ': ' .
$tresponse->getErrors()[0]->getErrorText());
$authorizeError = new AuthorizeNetErrorLog();
$authorizeError->setCreateDate(new \DateTime());
$authorizeError->setStudentId($studentId);
$authorizeError->setUserId($userId);
$authorizeError->setApiMethod($apiMethod);
$authorizeError->setExceptionMsg($tresponse->getErrors()[0]->getErrorText());
$authorizeError->setDetails('amount: ' . $amount . ' description: ' . $description);
$this->authorizeNetErrorLogService->save($authorizeError);
throw new Exception($tresponse->getErrors()[0]->getErrorText());
}
}
} else {
//echo "Transaction Failed \n";
$tresponse = $response->getTransactionResponse();
if ($tresponse != null && $tresponse->getErrors() != null) {
$this->logger->error('charge ERROR: ' . $tresponse->getErrors()[0]->getErrorCode() . ': ' .
$tresponse->getErrors()[0]->getErrorText());
$authorizeError = new AuthorizeNetErrorLog();
$authorizeError->setCreateDate(new \DateTime());
$authorizeError->setStudentId($studentId);
$authorizeError->setUserId($userId);
$authorizeError->setApiMethod($apiMethod);
$authorizeError->setExceptionMsg($tresponse->getErrors()[0]->getErrorText());
$authorizeError->setDetails('amount: ' . $amount . ' description: ' . $description);
$this->authorizeNetErrorLogService->save($authorizeError);
throw new Exception($tresponse->getErrors()[0]->getErrorText());
} else {
$this->logger->error('charge ERROR: ' . $response->getMessages()->getMessage()[0]->getCode() . ': ' .
$response->getMessages()->getMessage()[0]->getText());
$authorizeError = new AuthorizeNetErrorLog();
$authorizeError->setCreateDate(new \DateTime());
$authorizeError->setStudentId($studentId);
$authorizeError->setUserId($userId);
$authorizeError->setApiMethod($apiMethod);
$authorizeError->setExceptionMsg($response->getMessages()->getMessage()[0]->getText());
$authorizeError->setDetails('amount: ' . $amount . ' description: ' . $description);
$this->authorizeNetErrorLogService->save($authorizeError);
// return new Response(json_encode($response->getMessages()->getMessage()[0]->getText()),500);
throw new Exception(json_encode($response->getMessages()->getMessage()[0]->getText()));
}
}
return [$transId,$tresponse];
}
// public function createCustomerProfile($email){
// $merchantAuthentication = $this->getAuthentication();
// // Set the transaction's refId
// $refId = 'ref' . time();
//
// // Set credit card information for payment profile
// $creditCard = new AnetAPI\CreditCardType();
// $creditCard->setCardNumber("4242424242424242");
// $creditCard->setExpirationDate("2038-12");
// $creditCard->setCardCode("142");
// $paymentCreditCard = new AnetAPI\PaymentType();
// $paymentCreditCard->setCreditCard($creditCard);
//
// // Create a new CustomerPaymentProfile object
// $paymentProfile = new AnetAPI\CustomerPaymentProfileType();
// $paymentProfile->setCustomerType('individual');
// $paymentProfile->setPayment($paymentCreditCard);
// $paymentProfiles[] = $paymentProfile;
//
// // Create a new CustomerProfileType and add the payment profile object
// $customerProfile = new AnetAPI\CustomerProfileType();
// $customerProfile->setDescription("Customer 2 Test PHP");
// $customerProfile->setMerchantCustomerId("M_" . time());
// $customerProfile->setEmail($email);
// $customerProfile->setpaymentProfiles($paymentProfiles);
//
// // Assemble the complete transaction request
// $request = new AnetAPI\CreateCustomerProfileRequest();
// $request->setMerchantAuthentication($merchantAuthentication);
// $request->setRefId($refId);
// $request->setProfile($customerProfile);
//
// // Create the controller and get the response
// $controller = new AnetController\CreateCustomerProfileController($request);
// $response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX);
//
// if (($response != null) && ($response->getMessages()->getResultCode() == "Ok")) {
// echo "Succesfully created customer profile : " . $response->getCustomerProfileId() . "\n";
// $paymentProfiles = $response->getCustomerPaymentProfileIdList();
// echo "SUCCESS: PAYMENT PROFILE ID : " . $paymentProfiles[0] . "\n";
// } else {
// echo "ERROR : Invalid response\n";
// $errorMessages = $response->getMessages()->getMessage();
// echo "Response : " . $errorMessages[0]->getCode() . " " .$errorMessages[0]->getText() . "\n";
// }
// return $response;
// }
// public function chargeCreditCard($amount, $creditCardNumber, $expirationDate, $cardCode, $description, $email){
// $merchantAuthentication = $this->getAuthentication();
// $refId = 'ref' . time();
//
// // Create the payment data for a credit card
// $creditCard = new AnetAPI\CreditCardType();
// $creditCard->setCardNumber($creditCardNumber); //4111111111111111
// $creditCard->setExpirationDate($expirationDate); //2025-12
// $creditCard->setCardCode($cardCode);//123
//
// // Add the payment data to a paymentType object
// $paymentOne = new AnetAPI\PaymentType();
// $paymentOne->setCreditCard($creditCard);
//
// // Create order information
// $order = new AnetAPI\OrderType();
// //$order->setInvoiceNumber("10101");
// $order->setDescription($description);
//
// // Set the customer's identifying information
// $customerData = new AnetAPI\CustomerDataType();
// $customerData->setType("individual");
// $customerData->setId("99999456654");
// $customerData->setEmail($email);
//
// $transactionRequestType = new AnetAPI\TransactionRequestType();
// $transactionRequestType->setTransactionType("authCaptureTransaction");
// $transactionRequestType->setAmount($amount);
// $transactionRequestType->setOrder($order);
// $transactionRequestType->setPayment($paymentOne);
// $transactionRequestType->setCustomer($customerData);
//
// // Assemble the complete transaction request
// $request = new AnetAPI\CreateTransactionRequest();
// $request->setMerchantAuthentication($merchantAuthentication);
// $request->setRefId($refId);
// $request->setTransactionRequest($transactionRequestType);
//
// // Create the controller and get the response
// $controller = new AnetController\CreateTransactionController($request);
// $response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX);
//
// if ($response != null) {
// // Check to see if the API request was successfully received and acted upon
// if ($response->getMessages()->getResultCode() == "Ok") {
// // Since the API request was successful, look for a transaction response
// // and parse it to display the results of authorizing the card
// $tresponse = $response->getTransactionResponse();
//
// if ($tresponse != null && $tresponse->getMessages() != null) {
// echo " Successfully created transaction with Transaction ID: " . $tresponse->getTransId() . "\n";
// echo " Transaction Response Code: " . $tresponse->getResponseCode() . "\n";
// echo " Message Code: " . $tresponse->getMessages()[0]->getCode() . "\n";
// echo " Auth Code: " . $tresponse->getAuthCode() . "\n";
// echo " Description: " . $tresponse->getMessages()[0]->getDescription() . "\n";
// return ['transId'=>$tresponse->getTransId(),'responseCode' => $tresponse->getResponseCode()];
// } else {
// echo "Transaction Failed \n";
// if ($tresponse->getErrors() != null) {
// echo " Error Code : " . $tresponse->getErrors()[0]->getErrorCode() . "\n";
// echo " Error Message : " . $tresponse->getErrors()[0]->getErrorText() . "\n";
// }
// return ['failed','Error Code'=>$tresponse->getErrors()[0]->getErrorCode(),'Error Message' =>$tresponse->getErrors()[0]->getErrorText()];
// }
// // Or, print errors if the API request wasn't successful
// } else {
// echo "Transaction Failed \n";
// $tresponse = $response->getTransactionResponse();
//
// if ($tresponse != null && $tresponse->getErrors() != null) {
// echo " Error Code : " . $tresponse->getErrors()[0]->getErrorCode() . "\n";
// echo " Error Message : " . $tresponse->getErrors()[0]->getErrorText() . "\n";
// } else {
// echo " Error Code : " . $response->getMessages()->getMessage()[0]->getCode() . "\n";
// echo " Error Message : " . $response->getMessages()->getMessage()[0]->getText() . "\n";
// }
// return 'failed';
// }
// } else {
// echo "No response returned \n";
// }
// }
// public function createAnAcceptPaymentTransaction($amount,$dataDescriptor,$dataValue){
// /* Create a merchantAuthenticationType object with authentication details
// retrieved from the constants file */
// $merchantAuthentication = $this->getAuthentication();
// // Set the transaction's refId
// $refId = 'ref' . time();
//
// // Create the payment object for a payment nonce
// $opaqueData = new AnetAPI\OpaqueDataType();
// $opaqueData->setDataDescriptor($dataDescriptor);
// $opaqueData->setDataValue($dataValue);
//
//
// // Add the payment data to a paymentType object
// $paymentOne = new AnetAPI\PaymentType();
// $paymentOne->setOpaqueData($opaqueData);
//
// // Create order information
// $order = new AnetAPI\OrderType();
// $order->setInvoiceNumber("10101");
// $order->setDescription("Golf Shirts");
//
// // Set the customer's Bill To address
// $customerAddress = new AnetAPI\CustomerAddressType();
// $customerAddress->setFirstName("Ellen");
// $customerAddress->setLastName("Johnson");
// $customerAddress->setCompany("Souveniropolis");
// $customerAddress->setAddress("14 Main Street");
// $customerAddress->setCity("Pecan Springs");
// $customerAddress->setState("TX");
// $customerAddress->setZip("44628");
// $customerAddress->setCountry("USA");
//
// // Set the customer's identifying information
// $customerData = new AnetAPI\CustomerDataType();
// $customerData->setType("individual");
// $customerData->setId("99999456654");
// $customerData->setEmail("EllenJohnson@example.com");
//
// // Add values for transaction settings
// $duplicateWindowSetting = new AnetAPI\SettingType();
// $duplicateWindowSetting->setSettingName("duplicateWindow");
// $duplicateWindowSetting->setSettingValue("60");
//
//
// // Create a TransactionRequestType object and add the previous objects to it
// $transactionRequestType = new AnetAPI\TransactionRequestType();
// $transactionRequestType->setTransactionType("authCaptureTransaction");
// $transactionRequestType->setAmount($amount);
// $transactionRequestType->setOrder($order);
// $transactionRequestType->setPayment($paymentOne);
// $transactionRequestType->setBillTo($customerAddress);
// $transactionRequestType->setCustomer($customerData);
// $transactionRequestType->addToTransactionSettings($duplicateWindowSetting);
//
// // Assemble the complete transaction request
// $request = new AnetAPI\CreateTransactionRequest();
// $request->setMerchantAuthentication($merchantAuthentication);
// $request->setRefId($refId);
// $request->setTransactionRequest($transactionRequestType);
//
// // Create the controller and get the response
// $controller = new AnetController\CreateTransactionController($request);
// $response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX);
//
//
// if ($response != null) {
// // Check to see if the API request was successfully received and acted upon
// if ($response->getMessages()->getResultCode() == "Ok") {
// // Since the API request was successful, look for a transaction response
// // and parse it to display the results of authorizing the card
// $tresponse = $response->getTransactionResponse();
//
// if ($tresponse != null && $tresponse->getMessages() != null) {
// $transId = $tresponse->getTransId();
// } else {
// echo "Transaction Failed \n";
// if ($tresponse->getErrors() != null) {
// echo " Error Code : " . $tresponse->getErrors()[0]->getErrorCode() . "\n";
// echo " Error Message : " . $tresponse->getErrors()[0]->getErrorText() . "\n";
// }
// }
// // Or, print errors if the API request wasn't successful
// } else {
// echo "Transaction Failed \n";
// $tresponse = $response->getTransactionResponse();
//
// if ($tresponse != null && $tresponse->getErrors() != null) {
// echo " Error Code : " . $tresponse->getErrors()[0]->getErrorCode() . "\n";
// echo " Error Message : " . $tresponse->getErrors()[0]->getErrorText() . "\n";
// } else {
// echo " Error Code : " . $response->getMessages()->getMessage()[0]->getCode() . "\n";
// echo " Error Message : " . $response->getMessages()->getMessage()[0]->getText() . "\n";
// }
// }
// } else {
// echo "No response returned \n";
// }
//
// return ['transaction_id'=>$transId,'authResultCode'=>$response->getMessages()->getResultCode(), 'authNetResponse'=>$tresponse->getAuthCode()];
// }
public function chargeCustomerProfile($customerProfileId, $paymentProfileId, $amount, $description, $email , $studentName , $studentId, $allowDuplicateTransaction = false)
{
$transId = '';
// Set the transaction's refId
$refId = 'ref' . time();
$this->checkAndUpdateCustomerProfile($studentId);
$profileToCharge = new AnetAPI\CustomerProfilePaymentType();
$profileToCharge->setCustomerProfileId($customerProfileId);
$paymentProfile = new AnetAPI\PaymentProfileType();
$paymentProfile->setPaymentProfileId($paymentProfileId);
$profileToCharge->setPaymentProfile($paymentProfile);
// Create order information
$order = new AnetAPI\OrderType();
# TODO: How do we want to set the invoice number??
#$order->setInvoiceNumber("10101");
$order->setDescription($description);
$transactionRequestType = new AnetAPI\TransactionRequestType();
$transactionRequestType->setTransactionType("authCaptureTransaction");
$transactionRequestType->setAmount($amount);
$transactionRequestType->setOrder($order);
$transactionRequestType->setProfile($profileToCharge);
if ($allowDuplicateTransaction) {
$duplicateWindowSetting = new AnetAPI\SettingType();
$duplicateWindowSetting->setSettingName("duplicateWindow");
$duplicateWindowSetting->setSettingValue("0");
$transactionRequestType->addToTransactionSettings($duplicateWindowSetting);
}
$request = new AnetAPI\CreateTransactionRequest();
$request->setMerchantAuthentication($this->getAuthentication());
$request->setRefId($refId);
$request->setTransactionRequest($transactionRequestType);
$controller = new AnetController\CreateTransactionController($request);
$response = $controller->executeWithApiResponse($this->authorizeNetPlatform);
if ($response != null) {
[$transId,$tresponse]=$this->processResponse($response,$studentId,$amount,$description,'chargeCustomerProfile');
} else {
$this->logger->error('ERROR: No Response');
throw new Exception('No Response');
}
# Is there a specific reason why these are named differently to how they are named in accept.js?
return ['transaction_id' => $transId,'authResultCode' => $response->getMessages()->getResultCode(), 'authNetResponse' => $tresponse->getAuthCode()];
}
public function createCustomerProfileFromAcceptNonce(
$studentId,
$firstName,
$lastName,
$cardholderName,
$zipcode,
$email,
$acceptPaymentDescriptor,
$acceptPaymentValue
) {
// Set the transaction's refId
$refId = 'ref' . time();
// Set the payment data for the payment profile to a token obtained from Accept.js
$op = new AnetAPI\OpaqueDataType();
$op->setDataDescriptor($acceptPaymentDescriptor);
$op->setDataValue($acceptPaymentValue);
$paymentOne = new AnetAPI\PaymentType();
$paymentOne->setOpaqueData($op);
$billTo = $this->getBillTo($cardholderName, $zipcode);
// Create a new CustomerPaymentProfile object
$paymentProfile = new AnetAPI\CustomerPaymentProfileType();
$paymentProfile->setCustomerType('individual');
$paymentProfile->setBillTo($billTo);
$paymentProfile->setPayment($paymentOne);
$paymentProfiles[] = $paymentProfile;
// Create a new CustomerProfileType and add the payment profile object
$customerProfile = new AnetAPI\CustomerProfileType();
$customerProfile->setDescription($lastName . ', ' . $firstName);
$customerProfile->setMerchantCustomerId($studentId);
$customerProfile->setEmail($email);
$customerProfile->setPaymentProfiles($paymentProfiles);
// Assemble the complete transaction request
$request = new AnetAPI\CreateCustomerProfileRequest();
$request->setMerchantAuthentication($this->getAuthentication());
$request->setRefId($refId);
$request->setProfile($customerProfile);
//$request->setValidationMode('testMode');
// Create the controller and get the response
$controller = new AnetController\CreateCustomerProfileController($request);
$response = $controller->executeWithApiResponse($this->authorizeNetPlatform);
if (($response == null) || ($response->getMessages()->getResultCode() != "Ok")) {
$errorMessages = $response->getMessages()->getMessage();
$this->logger->error('Error: StudentId: ' . $studentId . ' - ' . $errorMessages[0]->getCode() . ': ' . $errorMessages[0]->getText());
$authorizeError = new AuthorizeNetErrorLog();
$authorizeError->setCreateDate(new \DateTime());
$authorizeError->setStudentId($studentId);
$authorizeError->setApiMethod('CreateCustomerProfileRequest');
$authorizeError->setExceptionMsg($errorMessages[0]->getText());
$this->authorizeNetErrorLogService->save($authorizeError);
//$authorizeError->setRequestBody($request);
throw new Exception($errorMessages[0]->getCode() . ': ' . $errorMessages[0]->getText());
}
return array('customerProfileId' => $response->getCustomerProfileId(),
'paymentProfileId' => $response->getCustomerPaymentProfileIdList()[0]);
}
private function getBillTo($cardholderName, $zipcode)
{
$cardholderNameArray = explode(" ", $cardholderName);
$lastName = array_pop($cardholderNameArray);
$firstName = implode(" ", $cardholderNameArray);
// Create the Bill To info for new payment type
$billTo = new AnetAPI\CustomerAddressType();
$billTo->setFirstName($firstName);
$billTo->setLastName($lastName);
$billTo->setZip($zipcode);
return $billTo;
}
public function createCustomerPaymentProfileFromAcceptNonce(
$customerProfileId,
$cardholderName,
$zipcode,
$email,
$acceptPaymentDescriptor,
$acceptPaymentValue,
$studentName ,
$studentId
) {
// Set the transaction's refId
$refId = 'ref' . time();
// Set the payment data for the payment profile to a token obtained from Accept.js
$op = new AnetAPI\OpaqueDataType();
$op->setDataDescriptor($acceptPaymentDescriptor);
$op->setDataValue($acceptPaymentValue);
$paymentOne = new AnetAPI\PaymentType();
$paymentOne->setOpaqueData($op);
$billTo = $this->getBillTo($cardholderName, $zipcode);
// Create a new CustomerPaymentProfile object
$paymentProfile = new AnetAPI\CustomerPaymentProfileType();
$paymentProfile->setCustomerType('individual');
$paymentProfile->setBillTo($billTo);
$paymentProfile->setPayment($paymentOne);
$paymentProfiles[] = $paymentProfile;
// Assemble the complete transaction request
$request = new AnetAPI\CreateCustomerPaymentProfileRequest();
$request->setMerchantAuthentication($this->getAuthentication());
// Add an existing profile id to the request
$request->setCustomerProfileId($customerProfileId);
$request->setPaymentProfile($paymentProfile);
//$request->setValidationMode('testMode');
// Create the controller and get the response
$controller = new AnetController\CreateCustomerPaymentProfileController($request);
$response = $controller->executeWithApiResponse($this->authorizeNetPlatform);
if (($response == null) || ($response->getMessages()->getResultCode() != "Ok")) {
$errorMessages = $response->getMessages()->getMessage();
$this->logger->error('Error: ' . $errorMessages[0]->getCode() . ': ' . $errorMessages[0]->getText());
$authorizeError = new AuthorizeNetErrorLog();
$authorizeError->setCreateDate(new \DateTime());
$authorizeError->setStudentId($studentId);
$authorizeError->setApiMethod('CreateCustomerPaymentProfileController');
$authorizeError->setExceptionMsg($errorMessages[0]->getText());
$this->authorizeNetErrorLogService->save($authorizeError);
throw new Exception($errorMessages[0]->getCode() . ': ' . $errorMessages[0]->getText());
}
return $response->getCustomerPaymentProfileId();
}
public function refundTransaction(Charges $charge, $amount)
{
$this->checkAndUpdateCustomerProfile($charge->getStudentid());
$merchantAuthentication = $this->getAuthentication();
$cc = $this->creditCardService->find($charge->getCcid());
// Set the transaction's refId
$refId = 'ref' . time();
// Create the payment data for a credit card
$creditCard = new AnetAPI\CreditCardType();
//$creditCard->setCardNumber("1111");
$creditCard->setCardNumber($cc->getCc4digits());//$charge->getCcLast4()
$creditCard->setExpirationDate($cc->getCcexpmonth() . $cc->getCcexpyear());//$charge->getCcExp()
$paymentOne = new AnetAPI\PaymentType();
$paymentOne->setCreditCard($creditCard);
//create a transaction
$transactionRequest = new AnetAPI\TransactionRequestType();
$transactionRequest->setTransactionType("refundTransaction");
$transactionRequest->setAmount($amount);
$transactionRequest->setPayment($paymentOne);
$transactionRequest->setRefTransId($charge->getTransid());
$request = new AnetAPI\CreateTransactionRequest();
$request->setMerchantAuthentication($merchantAuthentication);
$request->setRefId($refId);
$request->setTransactionRequest($transactionRequest);
$controller = new AnetController\CreateTransactionController($request);
$response = $controller->executeWithApiResponse($this->authorizeNetPlatform);
return $response;
}
public function voidTransaction($transactionid,$studentId)
{
$this->checkAndUpdateCustomerProfile($studentId);
$merchantAuthentication = $this->getAuthentication();
$refId = 'ref' . time();
$transactionRequestType = new AnetAPI\TransactionRequestType();
$transactionRequestType->setTransactionType("voidTransaction");
$transactionRequestType->setRefTransId($transactionid);
$request = new AnetAPI\CreateTransactionRequest();
$request->setMerchantAuthentication($merchantAuthentication);
$request->setRefId($refId);
$request->setTransactionRequest($transactionRequestType);
$controller = new AnetController\CreateTransactionController($request);
$response = $controller->executeWithApiResponse($this->authorizeNetPlatform);
return $response;
}
private function checkAndUpdateCustomerProfile($studentId)
{
// $student = $this->student
$student = $this->studentsRepository->find($studentId);
if(!$student->getAuthnetProfileUpdated()){
$response = $this->updateCustomerProfile($student);
if($response->getMessages()->getResultCode() == "Ok"){
$student->setAuthnetProfileUpdated(new \DateTime());
$this->studentsRepository->save($student);
}
}
}
function updateCustomerProfile($student)
{
$merchantAuthentication = $this->getAuthentication();
// Update an existing customer profile
$updatecustomerprofile = new AnetAPI\CustomerProfileExType();
$updatecustomerprofile->setCustomerProfileId($student->getCimId());
$updatecustomerprofile->setDescription($student->getLastname() . ', ' . $student->getFirstname());
$updatecustomerprofile->setMerchantCustomerId($student->getId());
$updatecustomerprofile->setEmail($student->getEmail());
$request = new AnetAPI\UpdateCustomerProfileRequest();
$request->setMerchantAuthentication($merchantAuthentication);
$request->setProfile($updatecustomerprofile);
$controller = new AnetController\UpdateCustomerProfileController($request);
$response = $controller->executeWithApiResponse($this->authorizeNetPlatform);
return $response;
}
public function chargeCustomerWithNewProfile(
$student,
$acceptPaymentDescriptor,
$acceptPaymentValue,
$amount,
$ccName,
$ccLast4,
$ccExpMonth,
$ccExpYear,
$billingZipCode,
$ccType,
$chargeDescription,
$toCharge = true
) {
if (!$student->getCimid()) {
$profileIds = $this->createCustomerProfileFromAcceptNonce(
$student->getId(),
$student->getFirstname(),
$student->getLastname(),
$ccName,
$billingZipCode,
$student->getEmail(),
$acceptPaymentDescriptor,
$acceptPaymentValue
);
$customerProfileId = $profileIds['customerProfileId'];
$student->setCimid($customerProfileId);
$this->studentsRepository->save($student);
$paymentProfileId = $profileIds['paymentProfileId'];
} else {
$paymentProfileId = $this->createCustomerPaymentProfileFromAcceptNonce(
$student->getCimid(),
$ccName,
$billingZipCode,
$student->getEmail(),
$acceptPaymentDescriptor,
$acceptPaymentValue,
$student->getLastname() . ', ' . $student->getFirstname(),
$student->getId()
);
}
if ($toCharge) {
$response = $this->chargeCustomerProfile(
$student->getCimid(),
$paymentProfileId,
$amount,
$chargeDescription,
$student->getEmail(),
$student->getLastname() . ', ' . $student->getFirstname(),
$student->getId()
);
}
$cc = $this->creditCardService->addCreditCard(
$student->getId(),
$paymentProfileId,
$ccName,
$ccLast4,
$ccExpMonth,
$ccExpYear,
$billingZipCode,
$ccType
);
$response['ccId'] = $cc->getId();
$response['paymentProfileId'] = $paymentProfileId;
return $response;
}
public function getTransactionDetails($transactionId)
{
$merchantAuthentication = $this->getAuthentication();
$request = new AnetAPI\GetTransactionDetailsRequest();
$request->setMerchantAuthentication($merchantAuthentication);
$request->setTransId($transactionId);
$controller = new AnetController\GetTransactionDetailsController($request);
$response = $controller->executeWithApiResponse($this->authorizeNetPlatform);
return $response;
}
public function singlePaymentFromAcceptNonce($acceptPaymentDescriptor,$acceptPaymentValue,$amount,Users $user,$description,$schoolName){
$op = new AnetAPI\OpaqueDataType();
$op->setDataDescriptor($acceptPaymentDescriptor);
$op->setDataValue($acceptPaymentValue);
$paymentOne = new AnetAPI\PaymentType();
$paymentOne->setOpaqueData($op);
// Create order information
$order = new AnetAPI\OrderType();
$order->setDescription($description);
// Set the customer's Bill To address
$customerAddress = new AnetAPI\CustomerAddressType();
// $customerAddress->setFirstName("Ellen");
// $customerAddress->setLastName("Johnson");
$customerAddress->setCompany($schoolName);
// Set the customer's identifying information
$customerData = new AnetAPI\CustomerDataType();
$customerData->setEmail($user->getEmail());
$transactionRequestType = new AnetAPI\TransactionRequestType();
$transactionRequestType->setTransactionType("authCaptureTransaction");
$transactionRequestType->setAmount($amount);
$transactionRequestType->setOrder($order);
$transactionRequestType->setPayment($paymentOne);
$transactionRequestType->setBillTo($customerAddress);
$transactionRequestType->setCustomer($customerData);
$request = new AnetAPI\CreateTransactionRequest();
$merchantAuthentication = $this->getAuthentication();
$refId = 'ref' . time();
$request->setMerchantAuthentication($merchantAuthentication);
$request->setRefId($refId);
$request->setTransactionRequest($transactionRequestType);
$controller = new AnetController\CreateTransactionController($request);
$response = $controller->executeWithApiResponse($this->authorizeNetPlatform);
if ($response != null) {
[$transId,$tresponse]=$this->processResponse($response,null,$amount,$description,'singlePaymentFromAcceptNonce',$user->getId());
} else {
$this->logger->error('ERROR: No Response');
throw new Exception('No Response');
}
return ['transaction_id' => $transId,'authResultCode' => $response->getMessages()->getResultCode(), 'authNetResponse' => $tresponse->getAuthCode()];
}
}