Reply
Highlighted
Member
Posts: 9
Registered: ‎07-28-2017

Accept Hosted PHP Implementation

Hello.  I'm attempting to implement the Accept Hosted instead of SIM, like many others, but am having a lot of initial issues getting things working.

 

I'm trying to focus on a simple example first, and simply grabbing this file to see the token printed out that is received.

 

https://github.com/AuthorizeNet/sample-code-php/blob/master/PaymentTransactions/get-an-accept-paymen...

 

I want to paste my exact code so that it's obvious below.  Right now my error is:

 

Fatal error: Class 'net\authorize\api\contract\v1\GetHostedPaymentPageRequest' not found in /home/xxxxxxxxxxxx/pay/sdk-php-1.9.3/get-an-accept-payment-page.php on line 42

 

Similar to this thread:  https://community.developer.authorize.net/t5/Integration-and-Testing/Class-GetHostedPaymentPageReque...

 

<?php
	ini_set('display_errors', 1);
	ini_set('display_startup_errors', 1);
	error_reporting(E_ALL);
	
	require 'autoload.php'; //this file is IN the SDK folder v1.9.3.
	
  use net\authorize\api\contract\v1 as AnetAPI;
  use net\authorize\api\controller as AnetController;

  define("AUTHORIZENET_LOG_FILE", "phplog");
  
function getAnAcceptPaymentPage(){
    /* Create a merchantAuthenticationType object with authentication details
       retrieved from the constants file */
    $merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
    $merchantAuthentication->setName("XXXXXXXXX");
    $merchantAuthentication->setTransactionKey("YYYYYYYY");
    
    // Set the transaction's refId
    $refId = 'ref' . time();

    //create a transaction
    $transactionRequestType = new AnetAPI\TransactionRequestType();
    $transactionRequestType->setTransactionType("authCaptureTransaction"); 
    $transactionRequestType->setAmount("12.23"); // To be defined through form field.

    // Set Hosted Form options    
    $setting1 = new AnetAPI\SettingType();
    $setting1->setSettingName("hostedPaymentButtonOptions");
    $setting1->setSettingValue("{\"text\": \"Pay\"}");

    $setting2 = new AnetAPI\SettingType();
    $setting2->setSettingName("hostedPaymentOrderOptions");
    $setting2->setSettingValue("{\"show\": false}");

    $setting3 = new AnetAPI\SettingType();
    $setting3->setSettingName("hostedPaymentReturnOptions");
    $setting3->setSettingValue("{\"url\": \"https://mysite.com/receipt\", \"cancelUrl\": \"https://mysite.com/cancel\", \"showReceipt\": true}");

    // Build transaction request    
    $request = new AnetAPI\GetHostedPaymentPageRequest();
    $request->setMerchantAuthentication($merchantAuthentication);
    $request->setTransactionRequest($transactionRequestType);

    $request->addToHostedPaymentSettings($setting1);
    $request->addToHostedPaymentSettings($setting2);
    $request->addToHostedPaymentSettings($setting3);
    
    //execute request
    $controller = new AnetController\GetHostedPaymentPageController($request);
    $response = $controller->executeWithApiResponse( \net\authorize\api\constants\ANetEnvironment::PRODUCTION);
    
    if (($response != null) && ($response->getMessages()->getResultCode() == "Ok") )
    {
      echo $response->getToken()."\n";
     }
    else
    {
      echo "ERROR :  Failed to get hosted payment page token\n";
      $errorMessages = $response->getMessages()->getMessage();
      echo "RESPONSE : " . $errorMessages[0]->getCode() . "  " .$errorMessages[0]->getText() . "\n";
    }
    return $response;
  }
  if(!defined('DONT_RUN_SAMPLES'))
      getAnAcceptPaymentPage();
?>
Highlighted
Posts: 459
Topics: 0
Kudos: 92
Blog Posts: 0
Ideas: 0
Solutions: 36
Registered: ‎04-28-2017

Re: Accept Hosted PHP Implementation

The main path for the autoloading is the location of the composer.json file, so if that lives in /var/www/src/MyApp/, the autoloading will use that as a base.

 

If using Composer on Windows, when a global install of a library / package is done, composer stores the package in a Composer directory inside Windows' application data folders which by default is "C:\Users{user name}\AppData\Roaming".

 

To change this folder to, for example, "C:\php\composer", create a COMPOSER_HOME environmental variable with the value set to "C:\php\composer".

 

Alternatively, there is custom SPL autoloader for you to reference from within your PHP file:

require 'path/to/anet_php_sdk/autoload.php';

This autoloader still requires the vendor directory and all of its dependencies to exist. However, this is a possible solution for cases where composer can't be run on a given system. You can run composer locally or on another system to build the directory, then copy the vendor directory to the desired system.

 

With that being said, you don't need to use the SDK. In fact, if you are just getting started it may cloud your perspective, because unless you have looked through and fully understand what every function does, then you are working in the dark. But fear not, because working with Authorize.net's API is very easy,  they have done and continue to do a great job, implementing and documenting the many excellent features of the API, making it very powerful and functional for you and your clients. 

 

To get an Accept Hosted page, it is just a matter of posting the XML or JSON similar to the following, to the appropriate end point ...,

Sandbox URL: https://apitest.authorize.net/xml/v1/request.api

Production URL: https://api.authorize.net/xml/v1/request.api

retreiving the token and populating your form's "token" input with this value.

 

<getHostedPaymentPageRequest xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
	<merchantAuthentication>
		<name>YOUR_LOGIN</name>
		<transactionKey>YOUR_TRANSACTION_KEY</transactionKey>
	</merchantAuthentication>
	<transactionRequest>
		<transactionType>authCaptureTransaction</transactionType>
		<amount>20.00</amount>
	</transactionRequest>
	<hostedPaymentSettings>
		<setting>
			<settingName>hostedPaymentBillingAddressOptions</settingName>
			<settingValue>{"show": true, "required":true}</settingValue>
		</setting>
		<setting>
			<settingName>hostedPaymentButtonOptions</settingName>
			<settingValue>{"text": "Pay"}</settingValue>
		</setting>
		<setting>
			<settingName>hostedPaymentReturnOptions</settingName>
			<settingValue>{"url":"https://YOUR_SITE.com/good","urlText":"Continue","cancelUrl":"https://YOUR_SITE.com/cancel","cancelUrlText":"Cancel"}</settingValue>
		</setting>
	</hostedPaymentSettings>
</getHostedPaymentPageRequest>

JSON version:

{
	"getHostedPaymentPageRequest": {
		"merchantAuthentication": {
			"name": "YOUR_API_LOGIN",
			"transactionKey": "YOUR_TRANSACTION_KEY"
		},
		"transactionRequest": {
			"transactionType": "authCaptureTransaction",
			"amount": "20.00",
			"customer": {
				"email": "goodCustomer@gmail.com"
			},
			"billTo": {
				"firstName": "Mary",
				"lastName": "Watson",
				"company": "Souveniropolis",
				"address": "Park Avenue",
				"city": "New York",
				"state": "NY",
				"zip": "10154",
				"country": "USA"
			}
		},
		"hostedPaymentSettings": {
			"setting": [{
				"settingName": "hostedPaymentBillingAddressOptions",
				"settingValue": "{\"show\": true, \"required\":true}"
			}, {
				"settingName": "hostedPaymentButtonOptions",
				"settingValue": "{\"text\": \"Pay\"}"
			}, {
				"settingName": "hostedPaymentCustomerOptions",
				"settingValue": "{\"showEmail\":true,\"requiredEmail\":true}"
			}, {
				"settingName": "hostedPaymentPaymentOptions",
				"settingValue": "{\"cardCodeRequired\":true}"
			}, {
				"settingName": "hostedPaymentReturnOptions",
				"settingValue": "{\"url\":\"https://YOUR_SITE.com/continue\",\"urlText\":\"Continue\",\"cancelUrl\":\"https://YOUR_SITE.com/cancel\",\"cancelUrlText\":\"Cancel\"}"
			}, {
				"settingName": "hostedPaymentSecurityOptions",
				"settingValue": "{\"captcha\": false}"
			}, {
				"settingName": "hostedPaymentShippingAddressOptions",
				"settingValue": "{\"show\":false,\"required\":true}"
			}, {
				"settingName": "hostedPaymentStyleOptions",
				"settingValue": "{\"bgColor\": \"EE00EE\"}"
			}]
		}
	}
}

Once you have the token, the form post urls:
Sandbox: https://test.authorize.net/payment/payment

Production: https://accept.authorize.net/payment/payment

 

 

Reference: https://developer.authorize.net/api/reference/features/accept_hosted.html

 

Powered by NexWebSites.com -
Certified Authorize.net developers
Highlighted
Member
Posts: 9
Registered: ‎07-28-2017

Re: Accept Hosted PHP Implementation

Hmmmm.

So I did not use composer, and therefore included the path to the autoload.php file within the SDK.  I do not have the vendor folder + its dependancies however - where would I get that for my info without copmoser?

 

Secondly, how would I post the XML or JSON data to receive the token using PHP?

Highlighted
Member
Posts: 9
Registered: ‎07-28-2017

Re: Accept Hosted PHP Implementation

[ Edited ]

Just to give some background, here's what I've tried:

 

PHP:

<?PHP
error_reporting( E_ALL );
ini_set('display_errors', 1);

$input_xml = '<getHostedPaymentPageRequest xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<merchantAuthentication>
<name>xxxxxx</name>
<transactionKey>xxxxx</transactionKey>
</merchantAuthentication>
<transactionRequest>
<transactionType>authCaptureTransaction</transactionType>
<amount>1.00</amount>
</transactionRequest>
<hostedPaymentSettings>
<setting>
<settingName>hostedPaymentBillingAddressOptions</settingName>
<settingValue>{"show": true, "required":true}</settingValue>
</setting>
<setting>
<settingName>hostedPaymentButtonOptions</settingName>
<settingValue>{"text": "Pay"}</settingValue>
</setting>
<setting>
<settingName>hostedPaymentReturnOptions</settingName>
<settingValue>{"url":"https://www.mystore.com/good","urlText":"Continue","cancelUrl":"https://www.mystore.com/cancel","cancelUrlText":"Cancel"}</settingValue>
</setting>
</hostedPaymentSettings>
</getHostedPaymentPageRequest>';


$url = "https://accept.authorize.net/payment/payment";

//setting the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml'));
// Following line is compulsary to add as it is:
curl_setopt($ch, CURLOPT_POSTFIELDS,
"xmlRequest=" . $input_xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1); //for production, set value to true or 1
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); //for production, set value to 2
$data = curl_exec($ch);
curl_close($ch);

//convert the XML result into array
//$array_data = json_decode(json_encode(simplexml_load_string($data)), true);

print_r($data);


?>

 

 

When I load the PHP file on my browser, I expect to see the XML response, but instead I see this (this is shown on the browser):

 

 
<?xml version="1.0" encoding="utf-8"?><ErrorResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd"><messages><resultCode>Error</resultCode><message><code>E00003</code><text>Data at the root level is invalid. Line 1, position 1.</text></message></messages></ErrorResponse>

 

 

Highlighted
Posts: 459
Topics: 0
Kudos: 92
Blog Posts: 0
Ideas: 0
Solutions: 36
Registered: ‎04-28-2017

Re: Accept Hosted PHP Implementation

[ Edited ]

Change

$url = "https://api.authorize.net/xml/v1/request.api"; // For live 

and 

curl_setopt($ch, CURLOPT_POSTFIELDS, $input_xml);

Generate a new Transaction Key,  and don't share it.  I see that you subsequently x'd it out, good, but the real one one was visible for a time and maybe cached.

 

Powered by NexWebSites.com -
Certified Authorize.net developers
Highlighted
Member
Posts: 9
Registered: ‎07-28-2017

Re: Accept Hosted PHP Implementation

=).  I did immediately when I realized!  Thanks.  

 

This worked, I actually realied the URL was wrong earlier and got another error, but once I edited my postfields as you noted it worked flawlessly to get the transaction key.  Thank you!

 

So now it says to "redirect the customer to the payment form by sending an HTML form post to our URL - https://accept.authorize.net/payment/payment"

 

 

I have not found any example of this, is there one available?  Thank you!

Highlighted
Posts: 459
Topics: 0
Kudos: 92
Blog Posts: 0
Ideas: 0
Solutions: 36
Registered: ‎04-28-2017

Re: Accept Hosted PHP Implementation

[ Edited ]

Very good. Below is an example of the form posting to the SandBox targeting an iframe. 

<form target="payframe" id="send_hptoken" action="https://test.authorize.net/payment/payment" method="post">
<input type="hidden" name="token" value="PUT_YOUR_TOKEN_HERE"/><input type="submit" value="Get Accept Hosted page"/>
</form>

<iframe style="height:700px;width:100%;border-style: none;" name="payframe" id="payframe"></iframe>

 

 

Powered by NexWebSites.com -
Certified Authorize.net developers
Highlighted
Member
Posts: 9
Registered: ‎07-28-2017

Re: Accept Hosted PHP Implementation

Hm, so I guess I'm wondering why I would have my users click a button that says "get accept hosted page" - instead of just displaying the form for them to enter their info in immediately?  Am I missing the point here, or can I bypass this step for the user and show them the payment screen immediately?

Highlighted
Posts: 459
Topics: 0
Kudos: 92
Blog Posts: 0
Ideas: 0
Solutions: 36
Registered: ‎04-28-2017

Re: Accept Hosted PHP Implementation

[ Edited ]

You could easily check for a token with Jquery and if found, automatically submit the form :

 <form id="frmGetPayment" target="payframe" id="send_hptoken" action="https://test.authorize.net/payment/payment" method="post">
<input id="token" type="hidden" name="token" value=""><input type="submit" id="btnGetPage" value="Get Accept Hosted page">
</form>
<iframe style="width:100%;border-style: none;" name="payframe" id="payframe"></iframe>
<script>
window.onload = function(){
    var token = $('#token').val();
          if (token > 0) {
            $('#frmGetPayment').submit();
        } else {
         alert("No token");
        }
         }
    </script>

Powered by NexWebSites.com -
Certified Authorize.net developers
Highlighted
Member
Posts: 9
Registered: ‎07-28-2017

Re: Accept Hosted PHP Implementation

What if I don't want to relay on jquery/javascript - is it possible to CURL the post in an expected format for authorize.net - and then take the HTML response and print that to any part of the page I want, for example?  Any sample code for this available?

 

Thanks!!