Jump to content

Orionsbelter

Members
  • Posts

    493
  • Joined

  • Last visited

Posts posted by Orionsbelter

  1. Okay, so I have a table in my database with a field to input a weight, the row will have an ID field which is the primary key. 

     

    The issue is I need to generate a form which I'm doing as a while loop, this form will have a textfield for each record in the table 

     

    I then need the user to fill our the form and submit the weights. 

     

    How would I then go about creating the code to deal with the text fields as am unsure how many rows will be extracted from the table as they will differ from time to time. 

     

     

  2. Hi there, 

     

    Am submitting an excel spread sheet via an upload php script I check in the do loop to see if the info already exists in my selected database using the info below

     

     

     
     $check_for_duped_person=mysql_num_rows(mysql_query("SELECT `id` FROM `delivery_information` WHERE `contact_name`='$recipient_name' AND `post_code`='$ship_postal_code'"));
     
     if($check_for_duped_person="1"){echo"error $check_for_duped_person $recipent_name";}else{
     
    

     

    It always seems to return 1 when even when the table delivery_information is empty.

     

    I need to make sure that the duplicated rows in the CSV file aren't submitted twice. This can only be done by the upload script and the above coding.

     

    I can not do it via excel as it will be user submitted  

     

    any help will be greatly appreciated

     

     

  3. okay so I'm struggling to find what the issue is here the form tags are okay as this is one submit of many in a tournament update form where each match there is two submits for teams and two for scores then a submit button 

     

    to save publishing the 1300 lines of code i have added the affected coded 

    if($_POST['sub_16_1']){
    $teamA_16_1_name=$_POST['teamA_16_1_name'];
    $teamB_16_1_name=$_POST['teamB_16_1_name'];
    $teamA_16_1_score=$_POST['teamA_16_1_score'];
    $teamB_16_1_score=$_POST['teamB_16_1_score'];
    mysql_query("UPDATE `teamResults` set `teamAName`='$teamA_16_1_name', `teamBName`='$teamB_16_1_name', `scoreA`='$teamA_16_1_score', `scoreB`='$teamB_16_1_score' WHERE `match`='1' AND `round`='16'");
    if($teamA_16_1_score > $teamB_16_1_score){ 
    $winner="$teamA_16_1_name"; $loser="$teamB_16_1_name"; }else{ $winner="$teamB_16_1_name"; $loser="$teamA_16_1_name"; }
    $text="$winner defeats $loser in the Golden 8 Ball";
    mysql_query("INSERT INTO `live-result` (`id` ,`text` ,`type`)VALUES ('' ,  '$text',  'score');"); $response = $tmhOAuth->request('POST', $tmhOAuth->url('1.1/statuses/update'), array('status' => ''.$text.''));
     mysql_query("UPDATE `teamResults` SET `teamAName`='$winner' WHERE `match`='1' AND `round`='8'");
    header("Location: edit-main-team-scores.php");
    }
    
    

    and 

       <tr bgcolor="#999999">
            <td><div align="center">1:
              <input name="teamA_16_1_name" type="text" id="teamA_16_1_name" value="<?php echo"$round_16_1->teamAName"; ?>" />
            </div></td>
            <td><div align="center"><span class="text">
              <input name="teamA_16_1_score" type="text" id="teamA_16_1_score" value="<?php echo"$round_16_1->scoreA";?>" size="4" maxlength="2" />
            </span></div></td>
            <td><div align="center" class="text"><strong>:</strong></div></td>
            <td><div align="center"><span class="text">
              <input name="teamB_16_1_score" type="text" id="teamB_16_1_score" value="<?php echo"$round_16_1->scoreB";?>" size="4" maxlength="2" />
            </span></div></td>
            <td><div align="center">
              <input name="teamB_16_1_name" type="text" id="teamB_16_1_name" value="<?php echo"$round_16_1->teamBName"; ?>" />
            </div></td>
            <td><div align="center">
              <label>
                <input type="submit" name="sub_16_1" id="sub_16_1" value="Update Score" />
              </label>
    
    

    am struggling to work out why the textfield are submitting blank even though it it submitting the form. please help

  4. hey i am new to JS and can not understand why this isn't working, i'm trying to create a checkbox onClick it runs code and takes values from textfeilds and populates others. 

    I tested the code and the function is been run however the code inside isn't doing as i've asked. 

     

     

     
    function managerDetails(){
    document.form1.capName.value = document.form1.manName.value;
    document.form1.capAddress.value = document.form1.manAddress.value;
    document.form1.capTown.value = document.form1.manTown.value;
    document.form1.capPost.value = document.form1.manPost.value;
    document.form1.capTele.value = document.form1.manTele.value;
    document.form1.capEmail.value = document.form1.manEmail.value;
    }
    
  5. Hey all, so i have an image upload script i use however i would like to change the script so that instead of getting the file from an uploaded file it gets it from a url.

     

    what would i need to change?

     

    
    <?php
    session_start();
    $username=$_SESSION['username'];
    include_once"../includes/db_connect.php";
    $id=$_POST['id'];
    $imageNum=$_POST['imageNum'];
    //define a maxim size for the uploaded images in Kb
    define ("MAX_SIZE","300"); 
    
    //This function reads the extension of the file. It is used to determine if the file  is an image by checking the extension.
    function getExtension($str) {
            $i = strrpos($str,".");
            if (!$i) { return ""; }
            $l = strlen($str) - $i;
            $ext = substr($str,$i+1,$l);
            return $ext;
    }
    //get the extension of the file in a lower case format
          $filename = stripslashes($_FILES['Image1']['name']);
      $extension = getExtension($filename);
     $extension = strtolower($extension);
    
     define( 'DESIRED_IMAGE_WIDTH', 902 );
     define( 'DESIRED_IMAGE_HEIGHT', 677 );
    
     $source_path = $_FILES[ 'Image1' ][ 'tmp_name' ];
    
    //get the extension of the file and check if it is support or not
    if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) 
     {die('This file type is not support, you may only use PNG GIF and JPG files.');}
    
    $size=filesize($_FILES['image']['tmp_name']);
    
    if ($size > MAX_SIZE*1024){ die('The File Size Is Too Large!'); }
    
     //
     // Add file validation code here
     //
    
     list( $source_width, $source_height, $source_type ) = getimagesize( $source_path );
    
     switch ( $source_type )
     {
       case IMAGETYPE_GIF:
         $source_gdim = imagecreatefromgif( $source_path );
         break;
    
       case IMAGETYPE_JPEG:
         $source_gdim = imagecreatefromjpeg( $source_path );
         break;
    
       case IMAGETYPE_PNG:
         $source_gdim = imagecreatefrompng( $source_path );
         break;
     }
    
     $source_aspect_ratio = $source_width / $source_height;
     $desired_aspect_ratio = DESIRED_IMAGE_WIDTH / DESIRED_IMAGE_HEIGHT;
    
     if ( $source_aspect_ratio > $desired_aspect_ratio )
     {
       //
       // Triggered when source image is wider
       //
       $temp_height = DESIRED_IMAGE_HEIGHT;
       $temp_width = ( int ) ( DESIRED_IMAGE_HEIGHT * $source_aspect_ratio );
     }
     else
     {
       //
       // Triggered otherwise (i.e. source image is similar or taller)
       //
       $temp_width = DESIRED_IMAGE_WIDTH;
       $temp_height = ( int ) ( DESIRED_IMAGE_WIDTH / $source_aspect_ratio );
     }
    
     //
     // Resize the image into a temporary GD image
     //
    
     $temp_gdim = imagecreatetruecolor( $temp_width, $temp_height );
     imagecopyresampled(
       $temp_gdim,
       $source_gdim,
       0, 0,
       0, 0,
       $temp_width, $temp_height,
       $source_width, $source_height
     );
    
     //
     // Copy cropped region from temporary image into the desired GD image
     //
    
     $x0 = ( $temp_width - DESIRED_IMAGE_WIDTH ) / 2;
     $y0 = ( $temp_height - DESIRED_IMAGE_HEIGHT ) / 2;
    
     $desired_gdim = imagecreatetruecolor( DESIRED_IMAGE_WIDTH, DESIRED_IMAGE_HEIGHT );
     imagecopy(
       $desired_gdim,
       $temp_gdim,
       0, 0,
       $x0, $y0,
       DESIRED_IMAGE_WIDTH, DESIRED_IMAGE_HEIGHT
     );
    
     //
     // Render the image
     // Alternatively, you can save the image in file-system or database
     //
     $rand=rand(1000,100000);
    $newname="$filename";
     if($extension == "jpg"){imagejpeg( $desired_gdim, "../images/products/$newname.jpg", 100);}
     if($extension == "gif"){imagegif( $desired_gdim, "../images/products/$newname.gif", 100);}
     if($extension == "png"){imagepng( $desired_gdim, "../images/products/$newname.png", 100);}
     mysql_query("UPDATE `products` SET $imageNum='$newname.$extension' WHERE id='$id'");
    header("Location: upload.php?tn=1&id=$id");
     //
     // Add clean-up code here
     //
    
    ?>
    

  6. I'm currently trying to use the following code:

     

    
    $arrResult = array();
    $arrLines = file('ProductAll.csv');
    foreach($arrLines as $line) {
    $arrResult[] = explode( ',', $line);
    $name=$arrResult[0];
    $description=$arrResult[1];
    $brand=$arrResult[2];
    $price=$arrResult[3];
    $RRP=$arrResult[4];
    $hidden=$arrResult[5];
    $Image1Address=$arrResult[6];
    $Image2Address=$arrResult[7];
    $Image3Address=$arrResult[8];
    $Image4Address=$arrResult[9];
    $Image5Address=$arrResult[10];
    

     

    However i just get the result "Array"

     

    where am i going wrong?

  7. Please help i don't get why this is kicking out and error

     

        echo"Monday: ".startAv($fetchAv->mon_start)." - ".finAv($fetchAv->mon_finish)."<br>
             Tuesday: ".startAv($fetchAv->tue_start)." - ".finAv($fetchAv->tue_finish)."<br> 
    		 Wednesday: ".startAv($fetchAv->wed_start)." - ".finAv($fetchAv->wed_finish)."<br>
    		 Thursday: ".startAv($fetchAv->thu_start)." - ".finAv($fetchAv->thu_finish)."<br>
    		 Friday: ".startAv($fetchAv->fri_start)." - ".finAv($fetchAv->fri_finish."<br>
    		 Saturday: ".startAv($fetchAv->sat_start)." - ".finAv($fetchAv->sat_finish)."<br>
    		 Sunday: ".startAv($fetchAv->sun_start)." - ".finAv($fetchAv->sun_finish)."<br>";
    

  8. I'm trying to code a small part using javascript where if the user selects an option with the value of '0' on a html menu it will automatically select a value of '0' on another menu on the page

     

    how could this been done? i'm new to javascript and i'm struggling

     

    any help would be apperciated.

     

    thanks

  9. also th sendmail code

    
    <?PHP
    sendmail('tester','tester','test','test');
    function sendmail($to,$from,$subject,$body){
    $from="contact@cuescues.co.uk";
    $to="$to";
    $font1s.= "MIME-Version: 1.0\r\n";
    $font1s.= "Content-type: text/html; ";
    $font1s.= "charset=iso-8859-1\r\n";
    $font1s.= "From: $from";
    $subject = "$subject";
    
    $body = "<HTML><BODY>
    $body
    </BODY></HTML>
    ";
    
    mail($to,$subject,$body,$font1s);
    }
    ?>
    


  10. hi there i'm currently using paypals IPN to send details back to my script where it handles the info and send and instant email that will include details of how to download thier products. However the script is not sending the email with the details. And i don't get any errors, it does however send a test email each time so i do know the sendmail function works below is all supporting code:

     

     
    
    <?PHP
    $req = 'cmd=_notify-validate';
    
    foreach ($_POST as $key => $value) {
            $value = urlencode(stripslashes($value));
            $req .= "&$key=$value";
    }
    
    $header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
    $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
    
    $fp = fsockopen ('www.paypal.com', 80, $errno, $errstr, 30);
    
    if (!$fp) { } else {
            fputs ($fp, $header . $req);
            while (!feof($fp)) {
                    $res = fgets ($fp, 1024);
                    if (strcmp ($res, "VERIFIED") == 0) {}
                    else if (strcmp ($res, "INVALID") == 0) {}
                    }
            fclose ($fp);
            }
    //-------
    
    if ($_POST['mc_currency'] == USD)
            $gross = $_POST['payment_gross'];
    else
            $gross = $_POST['mc_gross'];
    //----------------------------------
    
    
    ?>
    
    <?PHP
    include 'include/mysql.php';
    include 'include/global.php';
    include 'library/sendmail.php';
    
    $SQL = "SELECT * FROM `PRODUCTS` WHERE `TITLE` '$_POST[item_number]'"; $result = @mysql_query( $SQL ); $row = @mysql_fetch_array( $result );
    
    $hour   = date("G:i");
    $day    = date("d");
    $month  = date("m");
    $year   = date("Y");
    
    $get_id = $row[iD];
    if (empty($get_id)) die();
    //---------------------------------------
    
    if ($_POST[payment_status] != Completed) {
    
            $sql            = "UPDATE ORDERS SET
            PAYMENT_STATUS  = '$_POST[payment_status]',
            REASON_CODE     = '$_POST[reason_code]' WHERE TXN_ID = '$_POST[parent_txn_id]'";
            $query          = mysql_query($sql);
    
    } else {
            $sql            = "INSERT INTO ORDERS SET
            PRODUCT         = '$_POST[item_name]',
            ITEM_NUMBER     = '$row[iD]',
            PAYER_EMAIL     = '$_POST[payer_email]',
            DLC             = '0',
            H               = '$hour',
            D               = '$day',
            M               = '$month',
            Y               = '$year',
    
            ADDRESS_COUNTRY = '$_POST[address_country]',
    
            GROSS           = '$gross',
    
            PAYMENT_STATUS  = '$_POST[payment_status]',
            PAYMENT_TYPE    = '$_POST[payment_type]',
            PAYER_STATUS    = '$_POST[payer_status]',
    
            STATUS          = '$status',
            TXN_ID          = '$_POST[txn_id]'";
            $query          = mysql_query($sql);
    }
    
    $SQL = "SELECT * from USERS WHERE EMAIL = '$_POST[payer_email]' AND STATUS != '1'"; $result = @mysql_query( $SQL ); $row = @mysql_fetch_array( $result );
    if ($row[email] == $nil && $_POST[payer_email] != $nil) {
            $sql            = "INSERT INTO USERS SET
            EMAIL           = '$_POST[payer_email]',
            PASSWORD        = '$_POST[txn_id]',
            ADDRESS_COUNTRY = '$_POST[address_country]',
            CITY            = '$_POST[address_city]',
            FIRSTNAME      = '$_POST[first_name]',
            LASTNAME       = '$_POST[last_name]'";
            $query          = mysql_query($sql);
    } else {
            $sql            = "UPDATE USERS SET
            PASSWORD        = '$_POST[txn_id]'
            WHERE EMAIL     = '$_POST[payer_email]' AND STATUS !='1'";
            $query          = mysql_query($sql);
    }
    
    $SQL = "SELECT * from PRODUCTS WHERE ID = '$get_id'"; $result = @mysql_query( $SQL ); $row = @mysql_fetch_array( $result );
    
    if ($row[FILE_URL] != $nil) $dlinfo = "<BR><BR>Your download username is : ".$_POST[payer_email]."<BR>Your download password is : ".$_POST[txn_id]."<BR><BR>Visit http://f.cuescues.com/download.php to download";
    
    $SQL = "SELECT * from EMAIL_TEMPLATES WHERE ID = '$row[email_TEMPLATES]'"; $result = @mysql_query( $SQL ); $row = @mysql_fetch_array( $result );
    $email_body = preg_replace("/\n/","\n<BR>",$row[bODY]);
    
    sendmail("$_POST[payer_email]", "HIDDEN","$row[sUBJECT]","$email_body$dlinfo<BR><BR>$rowxxx[sIGNATURE]");
    sendmail("HIDDEN", "HIDDEN","$row[sUBJECT]","$email_body$dlinfo<BR><BR>$rowxxx[sIGNATURE]");
    echo"$dlinfo";
    ?>
    [code]
    
    sendmail.php
    
    [code]
    
    <?PHP
    sendmail('bengriffiths2009@gmail.com','contact@cuescues.co.uk','hi','hi');
    function sendmail($to,$from,$subject,$body){
    $from="contact@cuescues.co.uk";
    $to="$to";
    $font1s.= "MIME-Version: 1.0\r\n";
    $font1s.= "Content-type: text/html; ";
    $font1s.= "charset=iso-8859-1\r\n";
    $font1s.= "From: $from";
    $subject = "$subject";
    
    $body = "<HTML><BODY>
    $body
    </BODY></HTML>
    ";
    
    mail($to,$subject,$body,$font1s);
    }
    ?>
    

     

    global.php

     

    
    <?php
    
    if(stristr($_SERVER['SERVER_SOFTWARE'],'microsoft'))
             error_reporting("E_ALL");
    
    //----------------------------------------------------------------------------------
    
    $script_title = "";
    $version = "3.0";
    @$SQLxxx = "SELECT * from SETTINGS"; $resultxxx = @mysql_query( $SQLxxx ); $rowxxx = @mysql_fetch_array( $resultxxx );
    
    //----------------------------------------------------------------------------------
    
    if ($rowxxx[AFFID] != '') $aff = "?xyz=$rowxxx[AFFID]";
    
    $by = "Sell eBooks on Ebay";
    
    if (empty($_GET

    ) || $_GET

     == home)
    $by = "Sell eBooks on Ebay";
    
    
    //----------------------------------------------------------------------------------
    
    if (empty($rowxxx[PHOTOSIZE])) $rowxxx[PHOTOSIZE] = 550;
    if (empty($rowxxx[THUMBSIZE])) $rowxxx[THUMBSIZE] = 115;
    
    //----------------------------------------------------------------------------------
    
    if ($rowxxx[CURRENCY] == USD) {$cname = 'US Dollars'; $csymbol = '$';}
    if ($rowxxx[CURRENCY] == CAD) {$cname = 'Canadia Dollars'; $csymbol = '$';}
    if ($rowxxx[CURRENCY] == EUR) {$cname = 'Euros'; $csymbol = '€';}
    if ($rowxxx[CURRENCY] == GBP) {$cname = 'Pounds Sterling'; $csymbol = '£';}
    if ($rowxxx[CURRENCY] == JYN) {$cname = 'Yen'; $csymbol = '¥';}
    if ($rowxxx[CURRENCY] == AUD) {$cname = 'Australian'; $csymbol = '$';}
    
    //----------------------------------------------------------------------------------
    
    ?>
    

     

    please help as this is soo stressing me out :(

  11. hi i'm trying to create a php file from a script but i dont seem to be getting it right the file doesn't exist already am trying to create it.

     

    <title>test</title> <?php 
    include_once"includes/db_connect.php";
    
    $sql=mysql_query("SELECT `urlName` FROM `products` WHERE `category`='1'");
    while($fetch=mysql_fetch_object($sql)){
    $File = "".$fetch->urlName.".php"; 
    $handle = fopen($File, 'w');
    fclose($handle);
    }
    ?>
    

  12. i have found a free script that allows me to create an xml data feed file for googles products search however i don't know how to build the function

     

    getProducts

     

    to get the product info from my table can anyone help?

     

    // Gets the array of product data, replace this with the correct function for your CMS...
    $products = $productClass->getProducts('subcategory,category,name');
    // Now loop through each product
    foreach ($products as $key => $value) {
    // Check Stock level and set the required stock msg, again replace this with the correct function for your CMS...
    $stockMsg = 'in stock';
    // Swap your category names for the relevent Google Taxonomy Term detailed in their documentation
    if ($value['subcategory'] == '19')
    {
    $googleCategory = '> Billiard Balls';
    }
    else if ($value['subcategory'] == '20')
    {
    

  13. OKs i have two tables. One contains a userID this is in table 'info' and the other contain a totalPrice in table 'payment' for an order. Both tables are linked by the ID field. I'm trying to find a way using PHP to look at the database and find the top 5 customers; this means i have to look into the database and find all orders add up total price of all users orders and find out whos spent the most money from thier order(s).

     

     

     

     

  14. How can i break down strings for example i have a simple search database for products where as a user searches a term this can be one, two three words and so on.

     

    I'm using a wildcard; but i want the best way to get the possible search so i would like to break down the string into separate words and then use that to search the database using wildcards

     

    is this possible?

     

    Thanks for reading. 

  15. why do i keep getting this error from line 7?

     

    Object of class stdClass could not be converted to string

    <?php
    include_once"../includes/db_connect.php";
    $item_number="2";
    $custom="54298";
    $query=mysql_query("SELECT `prodID`, `quanity` FROM `cart` WHERE `sessID`='$custom'") or mysql_error();
    while($cart=mysql_fetch_object($query)){
    mysql_query("INSERT INTO  `orderItems` (  `id` ,  `orderInfoID` ,  `productID` ,  `quanity` ) VALUES ('',  '$item_number',  '$cart-> prodID',  '$cart->quanity');");
    }
    mysql_query("UPDATE `cart` SET `show`='1' WHERE `sessID`='$custom'");
    
    ?>
    

     

  16. Does anyone know how to pass the description of the goods in purchase using the scripts supplied by paypal.

     

    <?php
    /********************************************
    PayPal API Module
    
    Defines all the global variables and the wrapper functions 
    ********************************************/
    $PROXY_HOST = '127.0.0.1'; 
    $PROXY_PORT = '808';
    
    $SandboxFlag = false;
    
    //'------------------------------------
    //' PayPal API Credentials
    //' Replace <API_USERNAME> with your API Username
    //' Replace <API_PASSWORD> with your API Password
    //' Replace <API_SIGNATURE> with your Signature
    //'------------------------------------
    $API_UserName="";
    $API_Password="";
    $API_Signature="";
    
    // BN Code 	is only applicable for partners
    $sBNCode = "PP-ECWizard";
    
    
    /*	
    ' Define the PayPal Redirect URLs.  
    ' 	This is the URL that the buyer is first sent to do authorize payment with their paypal account
    ' 	change the URL depending if you are testing on the sandbox or the live PayPal site
    '
    ' For the sandbox, the URL is       https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=
    ' For the live site, the URL is        https://www.paypal.com/webscr&cmd=_express-checkout&token=
    */
    
    if ($SandboxFlag == true) 
    {
    	$API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp";
    	$PAYPAL_URL = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=";
    }
    else
    {
    	$API_Endpoint = "https://api-3t.paypal.com/nvp";
    	$PAYPAL_URL = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=";
    }
    
    $USE_PROXY = false;
    $version="64";
    
    if (session_id() == "") 
    	session_start();
    
    /* An express checkout transaction starts with a token, that
       identifies to PayPal your transaction
       In this example, when the script sees a token, the script
       knows that the buyer has already authorized payment through
       paypal.  If no token was found, the action is to send the buyer
       to PayPal to first authorize payment
       */
    
    /*   
    '-------------------------------------------------------------------------------------------------------------------------------------------
    ' Purpose: 	Prepares the parameters for the SetExpressCheckout API Call.
    ' Inputs:  
    '		paymentAmount:  	Total value of the shopping cart
    '		currencyCodeType: 	Currency code value the PayPal API
    '		paymentType: 		paymentType has to be one of the following values: Sale or Order or Authorization
    '		returnURL:			the page where buyers return to after they are done with the payment review on PayPal
    '		cancelURL:			the page where buyers return to when they cancel the payment review on PayPal
    '--------------------------------------------------------------------------------------------------------------------------------------------	
    */
    function CallShortcutExpressCheckout( $paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL) 
    {
    	//------------------------------------------------------------------------------------------------------------------------------------
    	// Construct the parameter string that describes the SetExpressCheckout API call in the shortcut implementation
    
    	$nvpstr="&PAYMENTREQUEST_0_AMT=". $paymentAmount;
    	$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_PAYMENTACTION=" . $paymentType;
    	$nvpstr = $nvpstr . "&RETURNURL=" . $returnURL;
    	$nvpstr = $nvpstr . "&CANCELURL=" . $cancelURL;
    	$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_CURRENCYCODE=" . $currencyCodeType;
    
    	$_SESSION["currencyCodeType"] = $currencyCodeType;	  
    	$_SESSION["PaymentType"] = $paymentType;
    
    	//'--------------------------------------------------------------------------------------------------------------- 
    	//' Make the API call to PayPal
    	//' If the API call succeded, then redirect the buyer to PayPal to begin to authorize payment.  
    	//' If an error occured, show the resulting errors
    	//'---------------------------------------------------------------------------------------------------------------
        $resArray=hash_call("SetExpressCheckout", $nvpstr);
    	$ack = strtoupper($resArray["ACK"]);
    	if($ack=="SUCCESS" || $ack=="SUCCESSWITHWARNING")
    	{
    		$token = urldecode($resArray["TOKEN"]);
    		$_SESSION['TOKEN']=$token;
    	}
    	   
        return $resArray;
    }
    
    /*   
    '-------------------------------------------------------------------------------------------------------------------------------------------
    ' Purpose: 	Prepares the parameters for the SetExpressCheckout API Call.
    ' Inputs:  
    '		paymentAmount:  	Total value of the shopping cart
    '		currencyCodeType: 	Currency code value the PayPal API
    '		paymentType: 		paymentType has to be one of the following values: Sale or Order or Authorization
    '		returnURL:			the page where buyers return to after they are done with the payment review on PayPal
    '		cancelURL:			the page where buyers return to when they cancel the payment review on PayPal
    '		shipToName:		the Ship to name entered on the merchant's site
    '		shipToStreet:		the Ship to Street entered on the merchant's site
    '		shipToCity:			the Ship to City entered on the merchant's site
    '		shipToState:		the Ship to State entered on the merchant's site
    '		shipToCountryCode:	the Code for Ship to Country entered on the merchant's site
    '		shipToZip:			the Ship to ZipCode entered on the merchant's site
    '		shipToStreet2:		the Ship to Street2 entered on the merchant's site
    '		phoneNum:			the phoneNum  entered on the merchant's site
    '--------------------------------------------------------------------------------------------------------------------------------------------	
    */
    function CallMarkExpressCheckout( $paymentAmount, $currencyCodeType, $paymentType, $returnURL, 
    								  $cancelURL, $shipToName, $shipToStreet, $shipToCity, $shipToState,
    								  $shipToCountryCode, $shipToZip, $shipToStreet2, $phoneNum
    								) 
    {
    	//------------------------------------------------------------------------------------------------------------------------------------
    	// Construct the parameter string that describes the SetExpressCheckout API call in the shortcut implementation
    
    	$nvpstr="&PAYMENTREQUEST_0_AMT=". $paymentAmount;
    	$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_PAYMENTACTION=" . $paymentType;
    	$nvpstr = $nvpstr . "&RETURNURL=" . $returnURL;
    	$nvpstr = $nvpstr . "&CANCELURL=" . $cancelURL;
    	$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_CURRENCYCODE=" . $currencyCodeType;
    	$nvpstr = $nvpstr . "&ADDROVERRIDE=1";
    	$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTONAME=" . $shipToName;
    	$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOSTREET=" . $shipToStreet;
    	$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOSTREET2=" . $shipToStreet2;
    	$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOCITY=" . $shipToCity;
    	$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOSTATE=" . $shipToState;
    	$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE=" . $shipToCountryCode;
    	$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOZIP=" . $shipToZip;
    	$nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOPHONENUM=" . $phoneNum;
    
    	$_SESSION["currencyCodeType"] = $currencyCodeType;	  
    	$_SESSION["PaymentType"] = $paymentType;
    
    	//'--------------------------------------------------------------------------------------------------------------- 
    	//' Make the API call to PayPal
    	//' If the API call succeded, then redirect the buyer to PayPal to begin to authorize payment.  
    	//' If an error occured, show the resulting errors
    	//'---------------------------------------------------------------------------------------------------------------
        $resArray=hash_call("SetExpressCheckout", $nvpstr);
    	$ack = strtoupper($resArray["ACK"]);
    	if($ack=="SUCCESS" || $ack=="SUCCESSWITHWARNING")
    	{
    		$token = urldecode($resArray["TOKEN"]);
    		$_SESSION['TOKEN']=$token;
    	}
    	   
        return $resArray;
    }
    
    /*
    '-------------------------------------------------------------------------------------------
    ' Purpose: 	Prepares the parameters for the GetExpressCheckoutDetails API Call.
    '
    ' Inputs:  
    '		None
    ' Returns: 
    '		The NVP Collection object of the GetExpressCheckoutDetails Call Response.
    '-------------------------------------------------------------------------------------------
    */
    function GetShippingDetails( $token )
    {
    	//'--------------------------------------------------------------
    	//' At this point, the buyer has completed authorizing the payment
    	//' at PayPal.  The function will call PayPal to obtain the details
    	//' of the authorization, incuding any shipping information of the
    	//' buyer.  Remember, the authorization is not a completed transaction
    	//' at this state - the buyer still needs an additional step to finalize
    	//' the transaction
    	//'--------------------------------------------------------------
       
        //'---------------------------------------------------------------------------
    	//' Build a second API request to PayPal, using the token as the
    	//'  ID to get the details on the payment authorization
    	//'---------------------------------------------------------------------------
        $nvpstr="&TOKEN=" . $token;
    
    	//'---------------------------------------------------------------------------
    	//' Make the API call and store the results in an array.  
    	//'	If the call was a success, show the authorization details, and provide
    	//' 	an action to complete the payment.  
    	//'	If failed, show the error
    	//'---------------------------------------------------------------------------
        $resArray=hash_call("GetExpressCheckoutDetails",$nvpstr);
        $ack = strtoupper($resArray["ACK"]);
    	if($ack == "SUCCESS" || $ack=="SUCCESSWITHWARNING")
    	{	
    		$_SESSION['payer_id'] =	$resArray['PAYERID'];
    	} 
    	return $resArray;
    }
    
    /*
    '-------------------------------------------------------------------------------------------------------------------------------------------
    ' Purpose: 	Prepares the parameters for the GetExpressCheckoutDetails API Call.
    '
    ' Inputs:  
    '		sBNCode:	The BN code used by PayPal to track the transactions from a given shopping cart.
    ' Returns: 
    '		The NVP Collection object of the GetExpressCheckoutDetails Call Response.
    '--------------------------------------------------------------------------------------------------------------------------------------------	
    */
    function ConfirmPayment( $FinalPaymentAmt )
    {
    	/* Gather the information to make the final call to
    	   finalize the PayPal payment.  The variable nvpstr
    	   holds the name value pairs
    	   */
    
    
    	//Format the other parameters that were stored in the session from the previous calls	
    	$token 				= urlencode($_SESSION['TOKEN']);
    	$paymentType 		= urlencode($_SESSION['PaymentType']);
    	$currencyCodeType 	= urlencode($_SESSION['currencyCodeType']);
    	$payerID 			= urlencode($_SESSION['payer_id']);
    
    	$serverName 		= urlencode($_SERVER['SERVER_NAME']);
    
    	$nvpstr  = '&TOKEN=' . $token . '&PAYERID=' . $payerID . '&PAYMENTREQUEST_0_PAYMENTACTION=' . $paymentType . '&PAYMENTREQUEST_0_AMT=' . $FinalPaymentAmt;
    	$nvpstr .= '&PAYMENTREQUEST_0_CURRENCYCODE=' . $currencyCodeType . '&IPADDRESS=' . $serverName; 
    
    	 /* Make the call to PayPal to finalize payment
    	    If an error occured, show the resulting errors
    	    */
    	$resArray=hash_call("DoExpressCheckoutPayment",$nvpstr);
    
    	/* Display the API response back to the browser.
    	   If the response from PayPal was a success, display the response parameters'
    	   If the response was an error, display the errors received using APIError.php.
    	   */
    	$ack = strtoupper($resArray["ACK"]);
    
    	return $resArray;
    }
    
    /*
    '-------------------------------------------------------------------------------------------------------------------------------------------
    ' Purpose: 	This function makes a DoDirectPayment API call
    '
    ' Inputs:  
    '		paymentType:		paymentType has to be one of the following values: Sale or Order or Authorization
    '		paymentAmount:  	total value of the shopping cart
    '		currencyCode:	 	currency code value the PayPal API
    '		firstName:			first name as it appears on credit card
    '		lastName:			last name as it appears on credit card
    '		street:				buyer's street address line as it appears on credit card
    '		city:				buyer's city
    '		state:				buyer's state
    '		countryCode:		buyer's country code
    '		zip:				buyer's zip
    '		creditCardType:		buyer's credit card type (i.e. Visa, MasterCard ... )
    '		creditCardNumber:	buyers credit card number without any spaces, dashes or any other characters
    '		expDate:			credit card expiration date
    '		cvv2:				Card Verification Value 
    '		
    '-------------------------------------------------------------------------------------------
    '		
    ' Returns: 
    '		The NVP Collection object of the DoDirectPayment Call Response.
    '--------------------------------------------------------------------------------------------------------------------------------------------	
    */
    
    
    function DirectPayment( $paymentType, $paymentAmount, $creditCardType, $creditCardNumber,
    						$expDate, $cvv2, $firstName, $lastName, $street, $city, $state, $zip, 
    						$countryCode, $currencyCode )
    {
    	//Construct the parameter string that describes DoDirectPayment
    	$nvpstr = "&AMT=" . $paymentAmount;
    	$nvpstr = $nvpstr . "&CURRENCYCODE=" . $currencyCode;
    	$nvpstr = $nvpstr . "&PAYMENTACTION=" . $paymentType;
    	$nvpstr = $nvpstr . "&CREDITCARDTYPE=" . $creditCardType;
    	$nvpstr = $nvpstr . "&ACCT=" . $creditCardNumber;
    	$nvpstr = $nvpstr . "&EXPDATE=" . $expDate;
    	$nvpstr = $nvpstr . "&CVV2=" . $cvv2;
    	$nvpstr = $nvpstr . "&FIRSTNAME=" . $firstName;
    	$nvpstr = $nvpstr . "&LASTNAME=" . $lastName;
    	$nvpstr = $nvpstr . "&STREET=" . $street;
    	$nvpstr = $nvpstr . "&CITY=" . $city;
    	$nvpstr = $nvpstr . "&STATE=" . $state;
    	$nvpstr = $nvpstr . "&COUNTRYCODE=" . $countryCode;
    	$nvpstr = $nvpstr . "&IPADDRESS=" . $_SERVER['REMOTE_ADDR'];
    
    	$resArray=hash_call("DoDirectPayment", $nvpstr);
    
    	return $resArray;
    }
    
    
    /**
      '-------------------------------------------------------------------------------------------------------------------------------------------
      * hash_call: Function to perform the API call to PayPal using API signature
      * @methodName is name of API  method.
      * @nvpStr is nvp string.
      * returns an associtive array containing the response from the server.
      '-------------------------------------------------------------------------------------------------------------------------------------------
    */
    function hash_call($methodName,$nvpStr)
    {
    	//declaring of global variables
    	global $API_Endpoint, $version, $API_UserName, $API_Password, $API_Signature;
    	global $USE_PROXY, $PROXY_HOST, $PROXY_PORT;
    	global $gv_ApiErrorURL;
    	global $sBNCode;
    
    	//setting the curl parameters.
    	$ch = curl_init();
    	curl_setopt($ch, CURLOPT_URL,$API_Endpoint);
    	curl_setopt($ch, CURLOPT_VERBOSE, 1);
    
    	//turning off the server and peer verification(TrustManager Concept).
    	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    
    	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    	curl_setopt($ch, CURLOPT_POST, 1);
    
        //if USE_PROXY constant set to TRUE in Constants.php, then only proxy will be enabled.
       //Set proxy name to PROXY_HOST and port number to PROXY_PORT in constants.php 
    	if($USE_PROXY)
    		curl_setopt ($ch, CURLOPT_PROXY, $PROXY_HOST. ":" . $PROXY_PORT); 
    
    	//NVPRequest for submitting to server
    	$nvpreq="METHOD=" . urlencode($methodName) . "&VERSION=" . urlencode($version) . "&PWD=" . urlencode($API_Password) . "&USER=" . urlencode($API_UserName) . "&SIGNATURE=" . urlencode($API_Signature) . $nvpStr . "&BUTTONSOURCE=" . urlencode($sBNCode);
    
    	//setting the nvpreq as POST FIELD to curl
    	curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
    
    	//getting response from server
    	$response = curl_exec($ch);
    
    	//convrting NVPResponse to an Associative Array
    	$nvpResArray=deformatNVP($response);
    	$nvpReqArray=deformatNVP($nvpreq);
    	$_SESSION['nvpReqArray']=$nvpReqArray;
    
    	if (curl_errno($ch)) 
    	{
    		// moving to display page to display curl errors
    		  $_SESSION['curl_error_no']=curl_errno($ch) ;
    		  $_SESSION['curl_error_msg']=curl_error($ch);
    
    		  //Execute the Error handling module to display errors. 
    	} 
    	else 
    	{
    		 //closing the curl
    	  	curl_close($ch);
    	}
    
    	return $nvpResArray;
    }
    
    /*'----------------------------------------------------------------------------------
     Purpose: Redirects to PayPal.com site.
     Inputs:  NVP string.
     Returns: 
    ----------------------------------------------------------------------------------
    */
    function RedirectToPayPal ( $token )
    {
    	global $PAYPAL_URL;
    
    	// Redirect to paypal.com here
    	$payPalURL = $PAYPAL_URL . $token;
    	header("Location: ".$payPalURL);
    }
    
    
    /*'----------------------------------------------------------------------------------
     * This function will take NVPString and convert it to an Associative Array and it will decode the response.
      * It is usefull to search for a particular key and displaying arrays.
      * @nvpstr is NVPString.
      * @nvpArray is Associative Array.
       ----------------------------------------------------------------------------------
      */
    function deformatNVP($nvpstr)
    {
    	$intial=0;
     	$nvpArray = array();
    
    	while(strlen($nvpstr))
    	{
    		//postion of Key
    		$keypos= strpos($nvpstr,'=');
    		//position of value
    		$valuepos = strpos($nvpstr,'&') ? strpos($nvpstr,'&'): strlen($nvpstr);
    
    		/*getting the Key and Value values and storing in a Associative Array*/
    		$keyval=substr($nvpstr,$intial,$keypos);
    		$valval=substr($nvpstr,$keypos+1,$valuepos-$keypos-1);
    		//decoding the respose
    		$nvpArray[urldecode($keyval)] =urldecode( $valval);
    		$nvpstr=substr($nvpstr,$valuepos+1,strlen($nvpstr));
         }
    	return $nvpArray;
    }
    
    ?>
    

     

    <?php
    
    require_once ("paypalfunctions.php");
    // ==================================
    // PayPal Express Checkout Module
    // ==================================
    
    //'------------------------------------
    //' The paymentAmount is the total value of 
    //' the shopping cart, that was set 
    //' earlier in a session variable 
    //' by the shopping cart page
    //'------------------------------------
    $paymentAmount = $_SESSION["Payment_Amount"];
    
    //'------------------------------------
    //' The currencyCodeType and paymentType 
    //' are set to the selections made on the Integration Assistant 
    //'------------------------------------
    $currencyCodeType = "GBP";
    $paymentType = "Sale";
    
    //'------------------------------------
    //' The returnURL is the location where buyers return to when a
    //' payment has been succesfully authorized.
    //'
    //' This is set to the value entered on the Integration Assistant 
    //'------------------------------------
    $returnURL = "";
    
    //'------------------------------------
    //' The cancelURL is the location buyers are sent to when they hit the
    //' cancel button during authorization of payment during the PayPal flow
    //'
    //' This is set to the value entered on the Integration Assistant 
    //'------------------------------------
    $cancelURL = "";
    
    //'------------------------------------
    //' Calls the SetExpressCheckout API call
    //'
    //' The CallShortcutExpressCheckout function is defined in the file PayPalFunctions.php,
    //' it is included at the top of this file.
    //'-------------------------------------------------
    $resArray = CallShortcutExpressCheckout ($paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL);
    $ack = strtoupper($resArray["ACK"]);
    if($ack=="SUCCESS" || $ack=="SUCCESSWITHWARNING")
    {
    RedirectToPayPal ( $resArray["TOKEN"] );
    } 
    else  
    {
    //Display a user friendly Error on the page using any of the following error information returned by PayPal
    $ErrorCode = urldecode($resArray["L_ERRORCODE0"]);
    $ErrorShortMsg = urldecode($resArray["L_SHORTMESSAGE0"]);
    $ErrorLongMsg = urldecode($resArray["L_LONGMESSAGE0"]);
    $ErrorSeverityCode = urldecode($resArray["L_SEVERITYCODE0"]);
    
    echo "SetExpressCheckout API call failed. ";
    echo "Detailed Error Message: " . $ErrorLongMsg;
    echo "Short Error Message: " . $ErrorShortMsg;
    echo "Error Code: " . $ErrorCode;
    echo "Error Severity Code: " . $ErrorSeverityCode;
    }
    ?>
    

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.