Welcome Guest, Not a member yet? Register   Sign In
Paypal Library- successfull transaction returns query string
#1

[eluser]Fast Eddie[/eluser]
Hello everyone,

I'm new to PHP and CodeIgniter and I'm having a little trouble with a PHP class I found online that I've attempted to convert to a CI library...

The purpose of the library is to incorporate Paypal Express Checkout. The class contains 2 parts - HTTPRequest & pplib.

Here is HTTPRequest:
Code:
class Httprequest {

    private $host;
    private $path;
    private $data;
    private $method;
    private $port;
    private $rawhost;

    private $header;
    private $content;
    private $parsedHeader;

    function __construct($host, $path, $method = 'POST', $ssl = false, $port = 0) {
        $this->host = $host;
        $this->rawhost = $ssl ? ("ssl://".$host) : $host;
        $this->path = $path;
        $this->method = strtoupper($method);
        if ($port) {
            $this->port = $port;
        } else {
            if (!$ssl) $this->port = 80; else $this->port = 443;
        }
    }

    public function connect( $data = ''){
        $fp = fsockopen($this->rawhost, $this->port);
        if (!$fp) return false;
        fputs($fp, "$this->method $this->path HTTP/1.1\r\n");
        fputs($fp, "Host: $this->host\r\n");
        //fputs($fp, "Content-type: $contenttype\r\n");
        fputs($fp, "Content-length: ".strlen($data)."\r\n");
        fputs($fp, "Connection: close\r\n");
        fputs($fp, "\r\n");
        fputs($fp, $data);

        $responseHeader = '';
        $responseContent = '';

        do
        {
            $responseHeader.= fread($fp, 1);
        }
        while (!preg_match('/\\r\\n\\r\\n$/', $responseHeader));
            
            
        if (!strstr($responseHeader, "Transfer-Encoding: chunked"))
        {
            while (!feof($fp))
            {
                $responseContent.= fgets($fp, 128);
            }
        }
        else
        {

            while ($chunk_length = hexdec(fgets($fp)))
            {
                $responseContentChunk = '';
                
                $read_length = 0;
                
                while ($read_length < $chunk_length)
                {
                    $responseContentChunk .= fread($fp, $chunk_length - $read_length);
                    $read_length = strlen($responseContentChunk);
                }

                $responseContent.= $responseContentChunk;
                
                fgets($fp);
                
            }
            
        }

        $this->header = chop($responseHeader);
        $this->content = $responseContent;
        $this->parsedHeader = $this->headerParse();
        
        $code = intval(trim(substr($this->parsedHeader[0], 9)));

        return $code;
    }

    function headerParse(){
        $h = $this->header;
        $a=explode("\r\n", $h);
        $out = array();
        foreach ($a as $v){
            $k = strpos($v, ':');
            if ($k) {
                $key = trim(substr($v,0,$k));
                $value = trim(substr($v,$k+1));
                if (!$key) continue;
                $out[$key] = $value;
            } else
            {
                if ($v) $out[] = $v;
            }
        }
        return $out;
    }

    public function getContent() {return $this->content;}
    public function getHeader() {return $this->parsedHeader;}
    

}
#2

[eluser]Fast Eddie[/eluser]
Here is pplib:
Code:
&lt;? if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Pplib {

    //these constants you have to obtain from PayPal
    //Step-by-step manual is here: https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_NVPAPIBasics
    const API_USERNAME = "test_166471665_biz_api1.gmail.com";
    const API_PASSWORD = "126641673";
    const API_SIGNATURE = "AQ36DZtiQhINUPQsIvHEEv1CP5UA0JwXy8e8eG1w33EEnfailcRrVo1";

    private $endpoint;
    private $host;
    private $gate;

    function __construct($real = false) {
        $this->endpoint = '/nvp';
        if ($real) {
            $this->host = "api-3t.paypal.com";
            $this->gate = 'https://www.paypal.com/cgi-bin/webscr?';
        } else {
            //sandbox
            $this->host = "api-3t.sandbox.paypal.com";
            $this->gate = 'https://www.sandbox.paypal.com/cgi-bin/webscr?';
        }
    }

    /**
     * @return string URL of the "success" page
     */
    private function getReturnTo() {
        return 'http://www.example.net/paypal/success_return';
    }

    /**
     * @return string URL of the "cancel" page
     */
    private function getReturnToCancel() {
        return 'http://www.example.net/paypal/cancel';
    }

    /**
     * @return HTTPRequest
     */
    private function response($data){
        $r = new HTTPRequest($this->host, $this->endpoint, 'POST', true);
        $result = $r->connect($data);
        if ($result<400) return $r;
        return false;
    }

    private function buildQuery($data = array()){
        $data['USER'] = self::API_USERNAME;
        $data['PWD'] = self::API_PASSWORD;
        $data['SIGNATURE'] = self::API_SIGNATURE;
        $data['VERSION'] = '52.0';
        $query = http_build_query($data);
        return $query;
    }

    
    /**
     * Main payment function
     *
     * If OK, the customer is redirected to PayPal gateway
     * If error, the error info is returned
     *
     * @param float $amount Amount (2 numbers after decimal point)
     * @param string $desc Item description
     * @param string $invoice Invoice number (can be omitted)
     * @param string $currency 3-letter currency code (USD, GBP, CZK etc.)
     *
     * @return array error info
     */
    public function doExpressCheckout($amount, $desc, $invoice='', $currency='USD'){
        $data = array(
        'PAYMENTACTION' =>'Sale',
        'AMT' =>$amount,
        'RETURNURL' =>$this->getReturnTo(),
        'CANCELURL'  =>$this->getReturnToCancel(),
        'DESC'=>$desc,
        'NOSHIPPING'=>"1",
        'ALLOWNOTE'=>"1",
        'CURRENCYCODE'=>$currency,
        'METHOD' =>'SetExpressCheckout');

        $data['CUSTOM'] = $amount.'|'.$currency.'|'.$invoice;
        if ($invoice) $data['INVNUM'] = $invoice;

        $query = $this->buildQuery($data);

        $result = $this->response($query);

        if (!$result) return false;
        $response = $result->getContent();
        $return = $this->responseParse($response);

        if ($return['ACK'] == 'Success') {
            header('Location: '.$this->gate.'cmd=_express-checkout&useraction=commit&token;='.$return['TOKEN'].'');
            die();
        }
        return($return);
    }

    public function getCheckoutDetails($token){
        $data = array(
        'TOKEN' => $token,
        'METHOD' =>'GetExpressCheckoutDetails');
        $query = $this->buildQuery($data);

        $result = $this->response($query);

        if (!$result) return false;
        $response = $result->getContent();
        $return = $this->responseParse($response);
        return($return);
    }
    public function doPayment(){
        $token = $_GET['token'];
        $payer = $_GET['PayerID'];
        $details = $this->getCheckoutDetails($token);
        if (!$details) return false;
        list($amount,$currency,$invoice) = explode('|',$details['CUSTOM']);
        $data = array(
        'PAYMENTACTION' => 'Sale',
        'PAYERID' => $payer,
        'TOKEN' =>$token,
        'AMT' => $amount,
        'CURRENCYCODE'=>$currency,
        'METHOD' =>'DoExpressCheckoutPayment');
        $query = $this->buildQuery($data);

        $result = $this->response($query);

        if (!$result) return false;
        $response = $result->getContent();
        $return = $this->responseParse($response);

        /*
         * [AMT] => 10.00
         * [CURRENCYCODE] => USD
         * [PAYMENTSTATUS] => Completed
         * [PENDINGREASON] => None
         * [REASONCODE] => None
         */

        return($return);
    }

    private function getScheme() {
        $scheme = 'http';
        if (isset($_SERVER['HTTPS']) and $_SERVER['HTTPS'] == 'on') {
            $scheme .= 's';
        }
        return $scheme;
    }

    private function responseParse($resp){
        $a=explode("&", $resp);
        $out = array();
        foreach ($a as $v){
            $k = strpos($v, '=');
            if ($k) {
                $key = trim(substr($v,0,$k));
                $value = trim(substr($v,$k+1));
                if (!$key) continue;
                $out[$key] = urldecode($value);
            } else {
                $out[] = $v;
            }
        }
        return $out;
    }
}

?&gt;


The problem I am encountering is when the user returns to the success page (function getRetrunTo in pplib)it appends a query string to the URL listed. What modifications do I need to make to turn it into a segment based URL?

Any help is greatly appreciated.


Thanks!
#3

[eluser]octavianmh[/eluser]
Well first, you can turn on enable_query_strings in your config file, and then change "getReturnTo" in the lib file to something like: "http://www.example.net/index.php/c=paypal&m=success_return"

Then you'll be able to access the variables of using "$this->input->get('blah')"

That should get you started!
#4

[eluser]Fast Eddie[/eluser]
thanks for the quick reply octavianmh Smile

enabling it seemed to work.
#5

[eluser]Fast Eddie[/eluser]
octavianmh,

It looks like enabling query strings did more damage than good. The helpers are not working correctly, and since I'm utilizing a lot of them throughout the website, enabling query stings is out of the question now....

Thanks again for your help!
#6

[eluser]octavianmh[/eluser]
Strange, enabling that shouldn't affect CI helpers, your segment based URLs will still work (and you can use them throughout your website).

I have a normal segment-based site that is required to integrate with an SMS service that only communicates incoming TXTs via a "get" request, which works great!

Anyway, just saying you should be able to get it all working in theory. Can you post an example of what is breaking?
#7

[eluser]ldg430[/eluser]
This may help...

I am just finishing up integrating PayPal's Express Checkout. I ran into problems with the query string that PayPal includes in the CANCEL and RETURN url's.

I turned on query strings in config.php

$config['enable_query_strings'] = TRUE;
$config['uri_protocol'] = "AUTO";

It fixed the problem for the RETURN url. But not CANCEL url - which was really weird. Then I found this thread

http://ellislab.com/forums/viewthread/136578/
#8

[eluser]Fast Eddie[/eluser]
octavianmh,

enabling it caused my pagination to break on several pages, and the URL helper isn't working at all...

Also, when someone adds items to the cart, it isnt working either Sad

It looks like I have alot of modifications to get this to work right...

I'm going to look into using tsnax4’s library for PayPal Express that ldg430 was kind enough to share the link for in hopes that it works better than my version.
#9

[eluser]ldg430[/eluser]
fast eddie - i used tsnax4's library as starting point for my implementation. i modified it to suit my needs. i will post the modified library and controller code sometime today...
#10

[eluser]Fast Eddie[/eluser]
ldg430, that would be great- Thanks!




Theme © iAndrew 2016 - Forum software by © MyBB