Re: [PHP] Newbie Question - Parse XML with PHP...

[email protected] (dealTek)
Newsgroups php.general
Message-ID <[email protected]>
On Apr 19, 2013, at 3:32 PM, tamouse mailing lists <[email protected]> wrote:

>> 
>> page1.php is sending out to credit card company - getting processed - then coming back to the *same page1.php* with the XML data listed below...
> 
> Please expand what you mean by "sending out" and "coming back" - is
> this a REST or SOAP API call? In that case, the response body is
> likely to be the XML.
> 
>> 
>> - so I'm not going to some other page to get it - it is coming to me to the same page I am on..........
>> 
>> so - after the XML result comes in - I need to assign the php to the XML somehow...
> 
> How do you recognize the "XML result com(ing) in" ?
> 

Hi tamouse,

with my untrained eye - it appears that this  is what is 'sending out'


 $data = sendXMLviaCurl($xmlRequest,$gatewayURL);


and this might be what is 'responding back' on the same page


    $gwResponse = @new SimpleXMLElement((string)$data);


you can see these lines towards the bottom at - // Process Step Three...


---



the page code is long - so i cut out some extra lines - but this is
=======================


all page code - with edits...

<?php





// API Setup Parameters

$gatewayURL = 'https://secure.webxxx.com/api/test';

$APIKey = 'xxxxxxx';





// If there is no POST data or a token-id, print the initial shopping cart form to get ready for Step One.

if (empty($_POST['DO_STEP_1'])&& empty($_GET['token-id'])) {



    print '  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';

    print '

    <html>

      <head>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

        <title>Collect non-sensitive Customer Info </title>

      </head>

      <body>

      <p><h2>Step One: Collect non-sensitive payment information.<br /></h2></p>



      <h3> Customer Information</h3>

      <h4> Billing Details</h4>



        <form action="" method="post">

          <table>

          <tr><td>Company</td><td><input type="text" name="billing-address-company" value="Acme, Inc."></td></tr>

         
		 
		 --- more



		  <tr><td><h4><br /> Shipping Details</h4>

          
		  
		  --more
		  

          <tr><td colspan="2">&nbsp;</td>

	      <tr><td colspan="2" align=center>Total Amount $12.00 </td></tr>

          <tr><td colspan="2" align=center><input type="submit" value="Submit Step One"><input type="hidden" name ="DO_STEP_1" value="true"></td></tr>

          </table>



        </form>

      </body>

    </html>



    ';

}else if (!empty($_POST['DO_STEP_1'])) {



    // Initiate Step One: Now that we've collected the non-sensitive payment information, we can combine other order information and build the XML format.

    $xmlRequest = new DOMDocument('1.0','UTF-8');



    $xmlRequest->formatOutput = true;

    $xmlSale = $xmlRequest->createElement('sale');



    // Amount, authentication, and Redirect-URL are typically the bare mininum.

    appendXmlNode($xmlSale,'api-key',$APIKey);

    appendXmlNode($xmlSale,'redirect-url',$_SERVER['HTTP_REFERER']);

    appendXmlNode($xmlSale, 'amount', '12.00');

    appendXmlNode($xmlSale, 'ip-address', $_SERVER["REMOTE_ADDR"]);

    //appendXmlNode($xmlSale, 'processor-id' , 'processora');

    appendXmlNode($xmlSale, 'currency', 'USD');

    //appendXmlNode($xmlSale, 'dup-seconds' , '2');



    // Some additonal fields may have been previously decided by user

    appendXmlNode($xmlSale, 'order-id', '1234');

    appendXmlNode($xmlSale, 'order-description', 'Small Order');

    appendXmlNode($xmlSale, 'merchant-defined-field-1' , 'Red');

    appendXmlNode($xmlSale, 'merchant-defined-field-2', 'Medium');

    appendXmlNode($xmlSale, 'tax-amount' , '2.00');

    appendXmlNode($xmlSale, 'shipping-amount' , '0.00');



    /*if(!empty($_POST['customer-vault-id'])) {

        appendXmlNode($xmlSale, 'customer-vault-id' , $_POST['customer-vault-id']);

    }else {

         $xmlAdd = $xmlRequest->createElement('add-customer');

         appendXmlNode($xmlAdd, 'customer-vault-id' ,411);

         $xmlSale->appendChild($xmlAdd);

    }*/





    // Set the Billing & Shipping from what was collected on initial shopping cart form

    $xmlBillingAddress = $xmlRequest->createElement('billing');

    appendXmlNode($xmlBillingAddress,'first-name', $_POST['billing-address-first-name']);

    //-more
	
	
    //billing-address-email

    appendXmlNode($xmlBillingAddress,'country', $_POST['billing-address-country']);

    appendXmlNode($xmlBillingAddress,'email', $_POST['billing-address-email']);

//more

    $xmlSale->appendChild($xmlBillingAddress);





    $xmlShippingAddress = $xmlRequest->createElement('shipping');

    appendXmlNode($xmlShippingAddress,'first-name', $_POST['shipping-address-first-name']);

    appendXmlNode($xmlShippingAddress,'last-name', $_POST['shipping-address-last-name']);

    // more

    appendXmlNode($xmlShippingAddress,'fax', $_POST['shipping-address-fax']);

    $xmlSale->appendChild($xmlShippingAddress);





    // Products already chosen by user

    $xmlProduct = $xmlRequest->createElement('product');

    appendXmlNode($xmlProduct,'product-code' , 'SKU-123456');

   
   
   
   // more

    appendXmlNode($xmlProduct,'alternate-tax-id' , '12345');



    $xmlSale->appendChild($xmlProduct);



    $xmlProduct = $xmlRequest->createElement('product');

    appendXmlNode($xmlProduct,'product-code' , 'SKU-123456');

    appendXmlNode($xmlProduct,'description' , 'test 2 product description');

    
	
	//more

    appendXmlNode($xmlProduct,'alternate-tax-id' , '12345');



    $xmlSale->appendChild($xmlProduct);



    $xmlRequest->appendChild($xmlSale);



	// Process Step One: Submit all transaction details to the Payment Gateway except the customer's sensitive payment information.

	// The Payment Gateway will return a variable form-url.

    $data = sendXMLviaCurl($xmlRequest,$gatewayURL);



	// Parse Step One's XML response

    $gwResponse = @new SimpleXMLElement($data);

    if ((string)$gwResponse->result ==1 ) {

        // The form url for used in Step Two below

        $formURL = $gwResponse->{'form-url'};

    } else {

        throw New Exception(print " Error, received " . $data);

    }



	// Initiate Step Two: Create an HTML form that collects the customer's sensitive payment information

	// and use the form-url that the Payment Gateway returns as the submit action in that form.

    print '  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';





    print '



        <html>

        <head>

            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

			<title>Collect sensitive Customer Info </title>

        </head>

        <body>';

	// Uncomment the line below if you would like to print Step One's response

	// print '<pre>' . (htmlentities($data)) . '</pre>';

	print '

        <p><h2>Step Two:<br /></h2></p>



        <form action="'.$formURL. '" method="POST">

		<h3> Payment Information</h3>

            <table>

                <tr><td>Credit Card Number</td><td><INPUT type ="text" name="billing-cc-number" value="1111xxx"> </td></tr>

                <tr><td>Expiration Date</td><td><INPUT type ="text" name="billing-cc-exp" value="0118"> </td></tr>

                <tr><td>CVV</td><td><INPUT type ="text" name="cvv" > </td></tr>

                <tr><Td colspan="2" align=center><INPUT type ="submit" value="Submit Step Two"></td> </tr>

            </table>

        </form>

        </body>

        </html>

        ';



} elseif (!empty($_GET['token-id'])) {



	// Step Three: Once the browser has been redirected, we can obtain the token-id and complete

	// the transaction through another XML HTTPS POST including the token-id which abstracts the

	// sensitive payment information that was previously collected by the Payment Gateway.

    $tokenId = $_GET['token-id'];

    $xmlRequest = new DOMDocument('1.0','UTF-8');

    $xmlRequest->formatOutput = true;

    $xmlCompleteTransaction = $xmlRequest->createElement('complete-action');

    appendXmlNode($xmlCompleteTransaction,'api-key',$APIKey);

    appendXmlNode($xmlCompleteTransaction,'token-id',$tokenId);

    $xmlRequest->appendChild($xmlCompleteTransaction);





	// Process Step Three

    $data = sendXMLviaCurl($xmlRequest,$gatewayURL);





    $gwResponse = @new SimpleXMLElement((string)$data);

    print '  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';

    print '

    <html>

      <head>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

        <title>Step Three - Complete Transaciton</title>

      </head>

      <body>';



	print "

        <p><h2>Step Three: Script automatically completes the transaction <br /></h2></p>";



    if ((string)$gwResponse->result == 1 ) {

        print " <p><h3> Transaction was Approved, XML response was:</h3></p>\n";

		print '<pre>' . (htmlentities($data)) . '</pre>';



    } elseif((string)$gwResponse->result == 2)  {

        print " <p><h3> Transaction was Declined.</h3>\n";

        print " Decline Description : " . (string)$gwResponse->{'result-text'} ." </p>";

		print " <p><h3>XML response was:</h3></p>\n";

		print '<pre>' . (htmlentities($data)) . '</pre>';

    } else {

        print " <p><h3> Transaction caused an Error.</h3>\n";

        print " Error Description: " . (string)$gwResponse->{'result-text'} ." </p>";

        print " <p><h3>XML response was:</h3></p>\n";

		print '<pre>' . (htmlentities($data)) . '</pre>';

    }

    print "</body></html>";







} else {

  print "ERROR IN SCRIPT<BR>";

}





  function sendXMLviaCurl($xmlRequest,$gatewayURL) {

   // helper function demonstrating how to send the xml with curl





    $ch = curl_init(); // Initialize curl handle

    curl_setopt($ch, CURLOPT_URL, $gatewayURL); // Set POST URL



    $headers = array();

    $headers[] = "Content-type: text/xml";

    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // Add http headers to let it know we're sending XML

    $xmlString = $xmlRequest->saveXML();

    curl_setopt($ch, CURLOPT_FAILONERROR, 1); // Fail on errors

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // Allow redirects

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Return into a variable

    curl_setopt($ch, CURLOPT_PORT, 443); // Set the port number

    curl_setopt($ch, CURLOPT_TIMEOUT, 15); // Times out after 15s

    curl_setopt($ch, CURLOPT_POST, 1);

    curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlString); // Add XML directly in POST



    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);





    // This should be unset in production use. With it on, it forces the ssl cert to be valid

    // before sending info.

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);



    if (!($data = curl_exec($ch))) {

        print  "curl error =>" .curl_error($ch) ."\n";

        throw New Exception(" CURL ERROR :" . curl_error($ch));



    }

    curl_close($ch);



    return $data;

  }



  // Helper function to make building xml dom easier

  function appendXmlNode($parentNode,$name, $value) {

        $tempNode = new DOMElement($name,$value);

        $parentNode->appendChild($tempNode);

  }



?>






--
Thanks,
Dave - DealTek
[email protected]
[db-3]
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.