src/Service/AuthorizeNetService.php line 43

Open in your IDE?
  1. <?php
  2. namespace App\Service;
  3. use App\Entity\AuthorizeNetErrorLog;
  4. use App\Entity\Charges;
  5. use App\Entity\Users;
  6. use App\Repository\StudentsRepository;
  7. use Psr\Log\LoggerInterface;
  8. use net\authorize\api\contract\v1 as AnetAPI;
  9. use net\authorize\api\controller as AnetController;
  10. use Symfony\Component\Config\Definition\Exception\Exception;
  11. use Symfony\Component\HttpFoundation\Response;
  12. class AuthorizeNetService
  13. {
  14. /**
  15. * @var LoggerInterface
  16. */
  17. private $logger;
  18. /**
  19. * @var ChargesService
  20. */
  21. private $pckChargesService;
  22. /**
  23. * @var AuthorizeNetErrorLogService
  24. */
  25. private $authorizeNetErrorLogService;
  26. private StudentsRepository $studentsRepository;
  27. public function __construct(
  28. LoggerInterface $logger,
  29. ChargesService $pckChargesService,
  30. AuthorizeNetErrorLogService $authorizeNetErrorLogService,
  31. CreditCardsService $creditCardsService,
  32. StudentsRepository $studentsRepository,
  33. ) {
  34. $this->logger = $logger;
  35. $this->authorizeNetPlatform = $_ENV["AUTHNET_PLATFORM"] == 'P' ? \net\authorize\api\constants\ANetEnvironment::PRODUCTION :
  36. \net\authorize\api\constants\ANetEnvironment::SANDBOX;
  37. $this->pckChargesService = $pckChargesService;
  38. $this->authorizeNetErrorLogService = $authorizeNetErrorLogService;
  39. $this->creditCardService = $creditCardsService;
  40. $this->studentsRepository = $studentsRepository;
  41. }
  42. private function getAuthentication()
  43. {
  44. $merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
  45. $merchantAuthentication->setName($_ENV["AUTHNET_LOGIN_ID"]);
  46. $merchantAuthentication->setTransactionKey($_ENV["AUTHNET_TRANSACTION_KEY"]);
  47. return $merchantAuthentication;
  48. }
  49. private function processResponse($response,$studentId,$amount,$description,$apiMethod,$userId = null){
  50. if ($response->getMessages()->getResultCode() == "Ok") {
  51. $tresponse = $response->getTransactionResponse();
  52. if ($tresponse != null && $tresponse->getMessages() != null) {
  53. $transId = $tresponse->getTransId();
  54. } else {
  55. // echo "Transaction Failed \n";
  56. if ($tresponse->getErrors() != null) {
  57. $this->logger->error('charge ERROR: ' . $tresponse->getErrors()[0]->getErrorCode() . ': ' .
  58. $tresponse->getErrors()[0]->getErrorText());
  59. $authorizeError = new AuthorizeNetErrorLog();
  60. $authorizeError->setCreateDate(new \DateTime());
  61. $authorizeError->setStudentId($studentId);
  62. $authorizeError->setUserId($userId);
  63. $authorizeError->setApiMethod($apiMethod);
  64. $authorizeError->setExceptionMsg($tresponse->getErrors()[0]->getErrorText());
  65. $authorizeError->setDetails('amount: ' . $amount . ' description: ' . $description);
  66. $this->authorizeNetErrorLogService->save($authorizeError);
  67. throw new Exception($tresponse->getErrors()[0]->getErrorText());
  68. }
  69. }
  70. } else {
  71. //echo "Transaction Failed \n";
  72. $tresponse = $response->getTransactionResponse();
  73. if ($tresponse != null && $tresponse->getErrors() != null) {
  74. $this->logger->error('charge ERROR: ' . $tresponse->getErrors()[0]->getErrorCode() . ': ' .
  75. $tresponse->getErrors()[0]->getErrorText());
  76. $authorizeError = new AuthorizeNetErrorLog();
  77. $authorizeError->setCreateDate(new \DateTime());
  78. $authorizeError->setStudentId($studentId);
  79. $authorizeError->setUserId($userId);
  80. $authorizeError->setApiMethod($apiMethod);
  81. $authorizeError->setExceptionMsg($tresponse->getErrors()[0]->getErrorText());
  82. $authorizeError->setDetails('amount: ' . $amount . ' description: ' . $description);
  83. $this->authorizeNetErrorLogService->save($authorizeError);
  84. throw new Exception($tresponse->getErrors()[0]->getErrorText());
  85. } else {
  86. $this->logger->error('charge ERROR: ' . $response->getMessages()->getMessage()[0]->getCode() . ': ' .
  87. $response->getMessages()->getMessage()[0]->getText());
  88. $authorizeError = new AuthorizeNetErrorLog();
  89. $authorizeError->setCreateDate(new \DateTime());
  90. $authorizeError->setStudentId($studentId);
  91. $authorizeError->setUserId($userId);
  92. $authorizeError->setApiMethod($apiMethod);
  93. $authorizeError->setExceptionMsg($response->getMessages()->getMessage()[0]->getText());
  94. $authorizeError->setDetails('amount: ' . $amount . ' description: ' . $description);
  95. $this->authorizeNetErrorLogService->save($authorizeError);
  96. // return new Response(json_encode($response->getMessages()->getMessage()[0]->getText()),500);
  97. throw new Exception(json_encode($response->getMessages()->getMessage()[0]->getText()));
  98. }
  99. }
  100. return [$transId,$tresponse];
  101. }
  102. // public function createCustomerProfile($email){
  103. // $merchantAuthentication = $this->getAuthentication();
  104. // // Set the transaction's refId
  105. // $refId = 'ref' . time();
  106. //
  107. // // Set credit card information for payment profile
  108. // $creditCard = new AnetAPI\CreditCardType();
  109. // $creditCard->setCardNumber("4242424242424242");
  110. // $creditCard->setExpirationDate("2038-12");
  111. // $creditCard->setCardCode("142");
  112. // $paymentCreditCard = new AnetAPI\PaymentType();
  113. // $paymentCreditCard->setCreditCard($creditCard);
  114. //
  115. // // Create a new CustomerPaymentProfile object
  116. // $paymentProfile = new AnetAPI\CustomerPaymentProfileType();
  117. // $paymentProfile->setCustomerType('individual');
  118. // $paymentProfile->setPayment($paymentCreditCard);
  119. // $paymentProfiles[] = $paymentProfile;
  120. //
  121. // // Create a new CustomerProfileType and add the payment profile object
  122. // $customerProfile = new AnetAPI\CustomerProfileType();
  123. // $customerProfile->setDescription("Customer 2 Test PHP");
  124. // $customerProfile->setMerchantCustomerId("M_" . time());
  125. // $customerProfile->setEmail($email);
  126. // $customerProfile->setpaymentProfiles($paymentProfiles);
  127. //
  128. // // Assemble the complete transaction request
  129. // $request = new AnetAPI\CreateCustomerProfileRequest();
  130. // $request->setMerchantAuthentication($merchantAuthentication);
  131. // $request->setRefId($refId);
  132. // $request->setProfile($customerProfile);
  133. //
  134. // // Create the controller and get the response
  135. // $controller = new AnetController\CreateCustomerProfileController($request);
  136. // $response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX);
  137. //
  138. // if (($response != null) && ($response->getMessages()->getResultCode() == "Ok")) {
  139. // echo "Succesfully created customer profile : " . $response->getCustomerProfileId() . "\n";
  140. // $paymentProfiles = $response->getCustomerPaymentProfileIdList();
  141. // echo "SUCCESS: PAYMENT PROFILE ID : " . $paymentProfiles[0] . "\n";
  142. // } else {
  143. // echo "ERROR : Invalid response\n";
  144. // $errorMessages = $response->getMessages()->getMessage();
  145. // echo "Response : " . $errorMessages[0]->getCode() . " " .$errorMessages[0]->getText() . "\n";
  146. // }
  147. // return $response;
  148. // }
  149. // public function chargeCreditCard($amount, $creditCardNumber, $expirationDate, $cardCode, $description, $email){
  150. // $merchantAuthentication = $this->getAuthentication();
  151. // $refId = 'ref' . time();
  152. //
  153. // // Create the payment data for a credit card
  154. // $creditCard = new AnetAPI\CreditCardType();
  155. // $creditCard->setCardNumber($creditCardNumber); //4111111111111111
  156. // $creditCard->setExpirationDate($expirationDate); //2025-12
  157. // $creditCard->setCardCode($cardCode);//123
  158. //
  159. // // Add the payment data to a paymentType object
  160. // $paymentOne = new AnetAPI\PaymentType();
  161. // $paymentOne->setCreditCard($creditCard);
  162. //
  163. // // Create order information
  164. // $order = new AnetAPI\OrderType();
  165. // //$order->setInvoiceNumber("10101");
  166. // $order->setDescription($description);
  167. //
  168. // // Set the customer's identifying information
  169. // $customerData = new AnetAPI\CustomerDataType();
  170. // $customerData->setType("individual");
  171. // $customerData->setId("99999456654");
  172. // $customerData->setEmail($email);
  173. //
  174. // $transactionRequestType = new AnetAPI\TransactionRequestType();
  175. // $transactionRequestType->setTransactionType("authCaptureTransaction");
  176. // $transactionRequestType->setAmount($amount);
  177. // $transactionRequestType->setOrder($order);
  178. // $transactionRequestType->setPayment($paymentOne);
  179. // $transactionRequestType->setCustomer($customerData);
  180. //
  181. // // Assemble the complete transaction request
  182. // $request = new AnetAPI\CreateTransactionRequest();
  183. // $request->setMerchantAuthentication($merchantAuthentication);
  184. // $request->setRefId($refId);
  185. // $request->setTransactionRequest($transactionRequestType);
  186. //
  187. // // Create the controller and get the response
  188. // $controller = new AnetController\CreateTransactionController($request);
  189. // $response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX);
  190. //
  191. // if ($response != null) {
  192. // // Check to see if the API request was successfully received and acted upon
  193. // if ($response->getMessages()->getResultCode() == "Ok") {
  194. // // Since the API request was successful, look for a transaction response
  195. // // and parse it to display the results of authorizing the card
  196. // $tresponse = $response->getTransactionResponse();
  197. //
  198. // if ($tresponse != null && $tresponse->getMessages() != null) {
  199. // echo " Successfully created transaction with Transaction ID: " . $tresponse->getTransId() . "\n";
  200. // echo " Transaction Response Code: " . $tresponse->getResponseCode() . "\n";
  201. // echo " Message Code: " . $tresponse->getMessages()[0]->getCode() . "\n";
  202. // echo " Auth Code: " . $tresponse->getAuthCode() . "\n";
  203. // echo " Description: " . $tresponse->getMessages()[0]->getDescription() . "\n";
  204. // return ['transId'=>$tresponse->getTransId(),'responseCode' => $tresponse->getResponseCode()];
  205. // } else {
  206. // echo "Transaction Failed \n";
  207. // if ($tresponse->getErrors() != null) {
  208. // echo " Error Code : " . $tresponse->getErrors()[0]->getErrorCode() . "\n";
  209. // echo " Error Message : " . $tresponse->getErrors()[0]->getErrorText() . "\n";
  210. // }
  211. // return ['failed','Error Code'=>$tresponse->getErrors()[0]->getErrorCode(),'Error Message' =>$tresponse->getErrors()[0]->getErrorText()];
  212. // }
  213. // // Or, print errors if the API request wasn't successful
  214. // } else {
  215. // echo "Transaction Failed \n";
  216. // $tresponse = $response->getTransactionResponse();
  217. //
  218. // if ($tresponse != null && $tresponse->getErrors() != null) {
  219. // echo " Error Code : " . $tresponse->getErrors()[0]->getErrorCode() . "\n";
  220. // echo " Error Message : " . $tresponse->getErrors()[0]->getErrorText() . "\n";
  221. // } else {
  222. // echo " Error Code : " . $response->getMessages()->getMessage()[0]->getCode() . "\n";
  223. // echo " Error Message : " . $response->getMessages()->getMessage()[0]->getText() . "\n";
  224. // }
  225. // return 'failed';
  226. // }
  227. // } else {
  228. // echo "No response returned \n";
  229. // }
  230. // }
  231. // public function createAnAcceptPaymentTransaction($amount,$dataDescriptor,$dataValue){
  232. // /* Create a merchantAuthenticationType object with authentication details
  233. // retrieved from the constants file */
  234. // $merchantAuthentication = $this->getAuthentication();
  235. // // Set the transaction's refId
  236. // $refId = 'ref' . time();
  237. //
  238. // // Create the payment object for a payment nonce
  239. // $opaqueData = new AnetAPI\OpaqueDataType();
  240. // $opaqueData->setDataDescriptor($dataDescriptor);
  241. // $opaqueData->setDataValue($dataValue);
  242. //
  243. //
  244. // // Add the payment data to a paymentType object
  245. // $paymentOne = new AnetAPI\PaymentType();
  246. // $paymentOne->setOpaqueData($opaqueData);
  247. //
  248. // // Create order information
  249. // $order = new AnetAPI\OrderType();
  250. // $order->setInvoiceNumber("10101");
  251. // $order->setDescription("Golf Shirts");
  252. //
  253. // // Set the customer's Bill To address
  254. // $customerAddress = new AnetAPI\CustomerAddressType();
  255. // $customerAddress->setFirstName("Ellen");
  256. // $customerAddress->setLastName("Johnson");
  257. // $customerAddress->setCompany("Souveniropolis");
  258. // $customerAddress->setAddress("14 Main Street");
  259. // $customerAddress->setCity("Pecan Springs");
  260. // $customerAddress->setState("TX");
  261. // $customerAddress->setZip("44628");
  262. // $customerAddress->setCountry("USA");
  263. //
  264. // // Set the customer's identifying information
  265. // $customerData = new AnetAPI\CustomerDataType();
  266. // $customerData->setType("individual");
  267. // $customerData->setId("99999456654");
  268. // $customerData->setEmail("EllenJohnson@example.com");
  269. //
  270. // // Add values for transaction settings
  271. // $duplicateWindowSetting = new AnetAPI\SettingType();
  272. // $duplicateWindowSetting->setSettingName("duplicateWindow");
  273. // $duplicateWindowSetting->setSettingValue("60");
  274. //
  275. //
  276. // // Create a TransactionRequestType object and add the previous objects to it
  277. // $transactionRequestType = new AnetAPI\TransactionRequestType();
  278. // $transactionRequestType->setTransactionType("authCaptureTransaction");
  279. // $transactionRequestType->setAmount($amount);
  280. // $transactionRequestType->setOrder($order);
  281. // $transactionRequestType->setPayment($paymentOne);
  282. // $transactionRequestType->setBillTo($customerAddress);
  283. // $transactionRequestType->setCustomer($customerData);
  284. // $transactionRequestType->addToTransactionSettings($duplicateWindowSetting);
  285. //
  286. // // Assemble the complete transaction request
  287. // $request = new AnetAPI\CreateTransactionRequest();
  288. // $request->setMerchantAuthentication($merchantAuthentication);
  289. // $request->setRefId($refId);
  290. // $request->setTransactionRequest($transactionRequestType);
  291. //
  292. // // Create the controller and get the response
  293. // $controller = new AnetController\CreateTransactionController($request);
  294. // $response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX);
  295. //
  296. //
  297. // if ($response != null) {
  298. // // Check to see if the API request was successfully received and acted upon
  299. // if ($response->getMessages()->getResultCode() == "Ok") {
  300. // // Since the API request was successful, look for a transaction response
  301. // // and parse it to display the results of authorizing the card
  302. // $tresponse = $response->getTransactionResponse();
  303. //
  304. // if ($tresponse != null && $tresponse->getMessages() != null) {
  305. // $transId = $tresponse->getTransId();
  306. // } else {
  307. // echo "Transaction Failed \n";
  308. // if ($tresponse->getErrors() != null) {
  309. // echo " Error Code : " . $tresponse->getErrors()[0]->getErrorCode() . "\n";
  310. // echo " Error Message : " . $tresponse->getErrors()[0]->getErrorText() . "\n";
  311. // }
  312. // }
  313. // // Or, print errors if the API request wasn't successful
  314. // } else {
  315. // echo "Transaction Failed \n";
  316. // $tresponse = $response->getTransactionResponse();
  317. //
  318. // if ($tresponse != null && $tresponse->getErrors() != null) {
  319. // echo " Error Code : " . $tresponse->getErrors()[0]->getErrorCode() . "\n";
  320. // echo " Error Message : " . $tresponse->getErrors()[0]->getErrorText() . "\n";
  321. // } else {
  322. // echo " Error Code : " . $response->getMessages()->getMessage()[0]->getCode() . "\n";
  323. // echo " Error Message : " . $response->getMessages()->getMessage()[0]->getText() . "\n";
  324. // }
  325. // }
  326. // } else {
  327. // echo "No response returned \n";
  328. // }
  329. //
  330. // return ['transaction_id'=>$transId,'authResultCode'=>$response->getMessages()->getResultCode(), 'authNetResponse'=>$tresponse->getAuthCode()];
  331. // }
  332. public function chargeCustomerProfile($customerProfileId, $paymentProfileId, $amount, $description, $email , $studentName , $studentId, $allowDuplicateTransaction = false)
  333. {
  334. $transId = '';
  335. // Set the transaction's refId
  336. $refId = 'ref' . time();
  337. $this->checkAndUpdateCustomerProfile($studentId);
  338. $profileToCharge = new AnetAPI\CustomerProfilePaymentType();
  339. $profileToCharge->setCustomerProfileId($customerProfileId);
  340. $paymentProfile = new AnetAPI\PaymentProfileType();
  341. $paymentProfile->setPaymentProfileId($paymentProfileId);
  342. $profileToCharge->setPaymentProfile($paymentProfile);
  343. // Create order information
  344. $order = new AnetAPI\OrderType();
  345. # TODO: How do we want to set the invoice number??
  346. #$order->setInvoiceNumber("10101");
  347. $order->setDescription($description);
  348. $transactionRequestType = new AnetAPI\TransactionRequestType();
  349. $transactionRequestType->setTransactionType("authCaptureTransaction");
  350. $transactionRequestType->setAmount($amount);
  351. $transactionRequestType->setOrder($order);
  352. $transactionRequestType->setProfile($profileToCharge);
  353. if ($allowDuplicateTransaction) {
  354. $duplicateWindowSetting = new AnetAPI\SettingType();
  355. $duplicateWindowSetting->setSettingName("duplicateWindow");
  356. $duplicateWindowSetting->setSettingValue("0");
  357. $transactionRequestType->addToTransactionSettings($duplicateWindowSetting);
  358. }
  359. $request = new AnetAPI\CreateTransactionRequest();
  360. $request->setMerchantAuthentication($this->getAuthentication());
  361. $request->setRefId($refId);
  362. $request->setTransactionRequest($transactionRequestType);
  363. $controller = new AnetController\CreateTransactionController($request);
  364. $response = $controller->executeWithApiResponse($this->authorizeNetPlatform);
  365. if ($response != null) {
  366. [$transId,$tresponse]=$this->processResponse($response,$studentId,$amount,$description,'chargeCustomerProfile');
  367. } else {
  368. $this->logger->error('ERROR: No Response');
  369. throw new Exception('No Response');
  370. }
  371. # Is there a specific reason why these are named differently to how they are named in accept.js?
  372. return ['transaction_id' => $transId,'authResultCode' => $response->getMessages()->getResultCode(), 'authNetResponse' => $tresponse->getAuthCode()];
  373. }
  374. public function createCustomerProfileFromAcceptNonce(
  375. $studentId,
  376. $firstName,
  377. $lastName,
  378. $cardholderName,
  379. $zipcode,
  380. $email,
  381. $acceptPaymentDescriptor,
  382. $acceptPaymentValue
  383. ) {
  384. // Set the transaction's refId
  385. $refId = 'ref' . time();
  386. // Set the payment data for the payment profile to a token obtained from Accept.js
  387. $op = new AnetAPI\OpaqueDataType();
  388. $op->setDataDescriptor($acceptPaymentDescriptor);
  389. $op->setDataValue($acceptPaymentValue);
  390. $paymentOne = new AnetAPI\PaymentType();
  391. $paymentOne->setOpaqueData($op);
  392. $billTo = $this->getBillTo($cardholderName, $zipcode);
  393. // Create a new CustomerPaymentProfile object
  394. $paymentProfile = new AnetAPI\CustomerPaymentProfileType();
  395. $paymentProfile->setCustomerType('individual');
  396. $paymentProfile->setBillTo($billTo);
  397. $paymentProfile->setPayment($paymentOne);
  398. $paymentProfiles[] = $paymentProfile;
  399. // Create a new CustomerProfileType and add the payment profile object
  400. $customerProfile = new AnetAPI\CustomerProfileType();
  401. $customerProfile->setDescription($lastName . ', ' . $firstName);
  402. $customerProfile->setMerchantCustomerId($studentId);
  403. $customerProfile->setEmail($email);
  404. $customerProfile->setPaymentProfiles($paymentProfiles);
  405. // Assemble the complete transaction request
  406. $request = new AnetAPI\CreateCustomerProfileRequest();
  407. $request->setMerchantAuthentication($this->getAuthentication());
  408. $request->setRefId($refId);
  409. $request->setProfile($customerProfile);
  410. //$request->setValidationMode('testMode');
  411. // Create the controller and get the response
  412. $controller = new AnetController\CreateCustomerProfileController($request);
  413. $response = $controller->executeWithApiResponse($this->authorizeNetPlatform);
  414. if (($response == null) || ($response->getMessages()->getResultCode() != "Ok")) {
  415. $errorMessages = $response->getMessages()->getMessage();
  416. $this->logger->error('Error: StudentId: ' . $studentId . ' - ' . $errorMessages[0]->getCode() . ': ' . $errorMessages[0]->getText());
  417. $authorizeError = new AuthorizeNetErrorLog();
  418. $authorizeError->setCreateDate(new \DateTime());
  419. $authorizeError->setStudentId($studentId);
  420. $authorizeError->setApiMethod('CreateCustomerProfileRequest');
  421. $authorizeError->setExceptionMsg($errorMessages[0]->getText());
  422. $this->authorizeNetErrorLogService->save($authorizeError);
  423. //$authorizeError->setRequestBody($request);
  424. throw new Exception($errorMessages[0]->getCode() . ': ' . $errorMessages[0]->getText());
  425. }
  426. return array('customerProfileId' => $response->getCustomerProfileId(),
  427. 'paymentProfileId' => $response->getCustomerPaymentProfileIdList()[0]);
  428. }
  429. private function getBillTo($cardholderName, $zipcode)
  430. {
  431. $cardholderNameArray = explode(" ", $cardholderName);
  432. $lastName = array_pop($cardholderNameArray);
  433. $firstName = implode(" ", $cardholderNameArray);
  434. // Create the Bill To info for new payment type
  435. $billTo = new AnetAPI\CustomerAddressType();
  436. $billTo->setFirstName($firstName);
  437. $billTo->setLastName($lastName);
  438. $billTo->setZip($zipcode);
  439. return $billTo;
  440. }
  441. public function createCustomerPaymentProfileFromAcceptNonce(
  442. $customerProfileId,
  443. $cardholderName,
  444. $zipcode,
  445. $email,
  446. $acceptPaymentDescriptor,
  447. $acceptPaymentValue,
  448. $studentName ,
  449. $studentId
  450. ) {
  451. // Set the transaction's refId
  452. $refId = 'ref' . time();
  453. // Set the payment data for the payment profile to a token obtained from Accept.js
  454. $op = new AnetAPI\OpaqueDataType();
  455. $op->setDataDescriptor($acceptPaymentDescriptor);
  456. $op->setDataValue($acceptPaymentValue);
  457. $paymentOne = new AnetAPI\PaymentType();
  458. $paymentOne->setOpaqueData($op);
  459. $billTo = $this->getBillTo($cardholderName, $zipcode);
  460. // Create a new CustomerPaymentProfile object
  461. $paymentProfile = new AnetAPI\CustomerPaymentProfileType();
  462. $paymentProfile->setCustomerType('individual');
  463. $paymentProfile->setBillTo($billTo);
  464. $paymentProfile->setPayment($paymentOne);
  465. $paymentProfiles[] = $paymentProfile;
  466. // Assemble the complete transaction request
  467. $request = new AnetAPI\CreateCustomerPaymentProfileRequest();
  468. $request->setMerchantAuthentication($this->getAuthentication());
  469. // Add an existing profile id to the request
  470. $request->setCustomerProfileId($customerProfileId);
  471. $request->setPaymentProfile($paymentProfile);
  472. //$request->setValidationMode('testMode');
  473. // Create the controller and get the response
  474. $controller = new AnetController\CreateCustomerPaymentProfileController($request);
  475. $response = $controller->executeWithApiResponse($this->authorizeNetPlatform);
  476. if (($response == null) || ($response->getMessages()->getResultCode() != "Ok")) {
  477. $errorMessages = $response->getMessages()->getMessage();
  478. $this->logger->error('Error: ' . $errorMessages[0]->getCode() . ': ' . $errorMessages[0]->getText());
  479. $authorizeError = new AuthorizeNetErrorLog();
  480. $authorizeError->setCreateDate(new \DateTime());
  481. $authorizeError->setStudentId($studentId);
  482. $authorizeError->setApiMethod('CreateCustomerPaymentProfileController');
  483. $authorizeError->setExceptionMsg($errorMessages[0]->getText());
  484. $this->authorizeNetErrorLogService->save($authorizeError);
  485. throw new Exception($errorMessages[0]->getCode() . ': ' . $errorMessages[0]->getText());
  486. }
  487. return $response->getCustomerPaymentProfileId();
  488. }
  489. public function refundTransaction(Charges $charge, $amount)
  490. {
  491. $this->checkAndUpdateCustomerProfile($charge->getStudentid());
  492. $merchantAuthentication = $this->getAuthentication();
  493. $cc = $this->creditCardService->find($charge->getCcid());
  494. // Set the transaction's refId
  495. $refId = 'ref' . time();
  496. // Create the payment data for a credit card
  497. $creditCard = new AnetAPI\CreditCardType();
  498. //$creditCard->setCardNumber("1111");
  499. $creditCard->setCardNumber($cc->getCc4digits());//$charge->getCcLast4()
  500. $creditCard->setExpirationDate($cc->getCcexpmonth() . $cc->getCcexpyear());//$charge->getCcExp()
  501. $paymentOne = new AnetAPI\PaymentType();
  502. $paymentOne->setCreditCard($creditCard);
  503. //create a transaction
  504. $transactionRequest = new AnetAPI\TransactionRequestType();
  505. $transactionRequest->setTransactionType("refundTransaction");
  506. $transactionRequest->setAmount($amount);
  507. $transactionRequest->setPayment($paymentOne);
  508. $transactionRequest->setRefTransId($charge->getTransid());
  509. $request = new AnetAPI\CreateTransactionRequest();
  510. $request->setMerchantAuthentication($merchantAuthentication);
  511. $request->setRefId($refId);
  512. $request->setTransactionRequest($transactionRequest);
  513. $controller = new AnetController\CreateTransactionController($request);
  514. $response = $controller->executeWithApiResponse($this->authorizeNetPlatform);
  515. return $response;
  516. }
  517. public function voidTransaction($transactionid,$studentId)
  518. {
  519. $this->checkAndUpdateCustomerProfile($studentId);
  520. $merchantAuthentication = $this->getAuthentication();
  521. $refId = 'ref' . time();
  522. $transactionRequestType = new AnetAPI\TransactionRequestType();
  523. $transactionRequestType->setTransactionType("voidTransaction");
  524. $transactionRequestType->setRefTransId($transactionid);
  525. $request = new AnetAPI\CreateTransactionRequest();
  526. $request->setMerchantAuthentication($merchantAuthentication);
  527. $request->setRefId($refId);
  528. $request->setTransactionRequest($transactionRequestType);
  529. $controller = new AnetController\CreateTransactionController($request);
  530. $response = $controller->executeWithApiResponse($this->authorizeNetPlatform);
  531. return $response;
  532. }
  533. private function checkAndUpdateCustomerProfile($studentId)
  534. {
  535. // $student = $this->student
  536. $student = $this->studentsRepository->find($studentId);
  537. if(!$student->getAuthnetProfileUpdated()){
  538. $response = $this->updateCustomerProfile($student);
  539. if($response->getMessages()->getResultCode() == "Ok"){
  540. $student->setAuthnetProfileUpdated(new \DateTime());
  541. $this->studentsRepository->save($student);
  542. }
  543. }
  544. }
  545. function updateCustomerProfile($student)
  546. {
  547. $merchantAuthentication = $this->getAuthentication();
  548. // Update an existing customer profile
  549. $updatecustomerprofile = new AnetAPI\CustomerProfileExType();
  550. $updatecustomerprofile->setCustomerProfileId($student->getCimId());
  551. $updatecustomerprofile->setDescription($student->getLastname() . ', ' . $student->getFirstname());
  552. $updatecustomerprofile->setMerchantCustomerId($student->getId());
  553. $updatecustomerprofile->setEmail($student->getEmail());
  554. $request = new AnetAPI\UpdateCustomerProfileRequest();
  555. $request->setMerchantAuthentication($merchantAuthentication);
  556. $request->setProfile($updatecustomerprofile);
  557. $controller = new AnetController\UpdateCustomerProfileController($request);
  558. $response = $controller->executeWithApiResponse($this->authorizeNetPlatform);
  559. return $response;
  560. }
  561. public function chargeCustomerWithNewProfile(
  562. $student,
  563. $acceptPaymentDescriptor,
  564. $acceptPaymentValue,
  565. $amount,
  566. $ccName,
  567. $ccLast4,
  568. $ccExpMonth,
  569. $ccExpYear,
  570. $billingZipCode,
  571. $ccType,
  572. $chargeDescription,
  573. $toCharge = true
  574. ) {
  575. if (!$student->getCimid()) {
  576. $profileIds = $this->createCustomerProfileFromAcceptNonce(
  577. $student->getId(),
  578. $student->getFirstname(),
  579. $student->getLastname(),
  580. $ccName,
  581. $billingZipCode,
  582. $student->getEmail(),
  583. $acceptPaymentDescriptor,
  584. $acceptPaymentValue
  585. );
  586. $customerProfileId = $profileIds['customerProfileId'];
  587. $student->setCimid($customerProfileId);
  588. $this->studentsRepository->save($student);
  589. $paymentProfileId = $profileIds['paymentProfileId'];
  590. } else {
  591. $paymentProfileId = $this->createCustomerPaymentProfileFromAcceptNonce(
  592. $student->getCimid(),
  593. $ccName,
  594. $billingZipCode,
  595. $student->getEmail(),
  596. $acceptPaymentDescriptor,
  597. $acceptPaymentValue,
  598. $student->getLastname() . ', ' . $student->getFirstname(),
  599. $student->getId()
  600. );
  601. }
  602. if ($toCharge) {
  603. $response = $this->chargeCustomerProfile(
  604. $student->getCimid(),
  605. $paymentProfileId,
  606. $amount,
  607. $chargeDescription,
  608. $student->getEmail(),
  609. $student->getLastname() . ', ' . $student->getFirstname(),
  610. $student->getId()
  611. );
  612. }
  613. $cc = $this->creditCardService->addCreditCard(
  614. $student->getId(),
  615. $paymentProfileId,
  616. $ccName,
  617. $ccLast4,
  618. $ccExpMonth,
  619. $ccExpYear,
  620. $billingZipCode,
  621. $ccType
  622. );
  623. $response['ccId'] = $cc->getId();
  624. $response['paymentProfileId'] = $paymentProfileId;
  625. return $response;
  626. }
  627. public function getTransactionDetails($transactionId)
  628. {
  629. $merchantAuthentication = $this->getAuthentication();
  630. $request = new AnetAPI\GetTransactionDetailsRequest();
  631. $request->setMerchantAuthentication($merchantAuthentication);
  632. $request->setTransId($transactionId);
  633. $controller = new AnetController\GetTransactionDetailsController($request);
  634. $response = $controller->executeWithApiResponse($this->authorizeNetPlatform);
  635. return $response;
  636. }
  637. public function singlePaymentFromAcceptNonce($acceptPaymentDescriptor,$acceptPaymentValue,$amount,Users $user,$description,$schoolName){
  638. $op = new AnetAPI\OpaqueDataType();
  639. $op->setDataDescriptor($acceptPaymentDescriptor);
  640. $op->setDataValue($acceptPaymentValue);
  641. $paymentOne = new AnetAPI\PaymentType();
  642. $paymentOne->setOpaqueData($op);
  643. // Create order information
  644. $order = new AnetAPI\OrderType();
  645. $order->setDescription($description);
  646. // Set the customer's Bill To address
  647. $customerAddress = new AnetAPI\CustomerAddressType();
  648. // $customerAddress->setFirstName("Ellen");
  649. // $customerAddress->setLastName("Johnson");
  650. $customerAddress->setCompany($schoolName);
  651. // Set the customer's identifying information
  652. $customerData = new AnetAPI\CustomerDataType();
  653. $customerData->setEmail($user->getEmail());
  654. $transactionRequestType = new AnetAPI\TransactionRequestType();
  655. $transactionRequestType->setTransactionType("authCaptureTransaction");
  656. $transactionRequestType->setAmount($amount);
  657. $transactionRequestType->setOrder($order);
  658. $transactionRequestType->setPayment($paymentOne);
  659. $transactionRequestType->setBillTo($customerAddress);
  660. $transactionRequestType->setCustomer($customerData);
  661. $request = new AnetAPI\CreateTransactionRequest();
  662. $merchantAuthentication = $this->getAuthentication();
  663. $refId = 'ref' . time();
  664. $request->setMerchantAuthentication($merchantAuthentication);
  665. $request->setRefId($refId);
  666. $request->setTransactionRequest($transactionRequestType);
  667. $controller = new AnetController\CreateTransactionController($request);
  668. $response = $controller->executeWithApiResponse($this->authorizeNetPlatform);
  669. if ($response != null) {
  670. [$transId,$tresponse]=$this->processResponse($response,null,$amount,$description,'singlePaymentFromAcceptNonce',$user->getId());
  671. } else {
  672. $this->logger->error('ERROR: No Response');
  673. throw new Exception('No Response');
  674. }
  675. return ['transaction_id' => $transId,'authResultCode' => $response->getMessages()->getResultCode(), 'authNetResponse' => $tresponse->getAuthCode()];
  676. }
  677. }