Monday, April 7, 2014

Create Refund Using PayPal Api

REST API Reference - PayPal

Create a file such named 'createRefund.php' using following contents:


<?php
session_start();
require './PaypalBase.php';
$paymentId = "";
$amount = 0;
if(isset($_GET["paymentId"]) && PaypalBase::isValidString($_GET["paymentId"])) {
    $paymentId = $_GET["paymentId"]; 
    $dataArray = array();
    if(isset($_GET["amount"]) && PaypalBase::isValidString($_GET["amount"]) 
            && floatval($_GET["amount"]) > 0) {
        $amount = floatval($_GET["amount"]);
        $dataArray = array(
            "amount" => array(
                "total" => floatval($_GET["amount"]),
                "currency" => "USD"
            )
        );
    }
    $refundArray = PaypalBase::createRefund($paymentId, $dataArray);
    PaypalBase::printR($refundArray);
    if($refundArray != NULL) {
        return;
    } else {
        echo "<br/><b>Error in refund</b>";
    }
}
?>
<form>
    Payment: <input type="text" name="paymentId" value="<?php echo $paymentId; ?>"/><br/>
    Amount: <input type="text" name="amount" value="<?php echo $amount; ?>"/><br/>
    <input type="submit" value="Process..."/>
</form>

createRefund method from 'PaypalBase.php'


<?php
public static function createRefund($paymentId, $dataArray = NULL) {
    self::info("createRefund");
    self::info("-----------------------------------------------");
    self::info("-----------------------------------------------");
    $accessToken = self::generateAccessToken(PPConstants::CLIENT_ID, PPConstants::CLIENT_SECRET);
    if(!$accessToken) {
        throw new Exception("Creating accessToken failed");
    }
    self::info("AccessToken: " . $accessToken);
    if(!$paymentId || strlen(trim($paymentId)) == 0) {
        throw new Exception("paymentId required");
    }
    self::info("Creating refund: $paymentId");

    $headers = array(
        'Content-Type: application/json',
        'Authorization: Bearer '.$accessToken,
        "PayPal-Request-Id" => self::generateRequestId(),
        "User-Agent" => self::getUserAgent()
    );
    if($dataArray != NULL && is_array($dataArray) && count($dataArray) > 0) {
        array_push($headers, "Content-Length: " . strlen(json_encode($dataArray)));
        self::info($dataArray);
    }
    if($dataArray != NULL && !is_array($dataArray) && strlen($dataArray) > 0) {
        array_push($headers, "Content-Length: " . strlen($dataArray));
        self::info($dataArray);
    }
    $paymentUrl = PPConstants::REST_SANDBOX_ENDPOINT.
            PPConstants::PAYMENT_GET_URL.$paymentId.PPConstants::PAYMENT_REFUND_URL;
    if(!self::$testMode) {
        $paymentUrl = PPConstants::REST_LIVE_ENDPOINT.
                PPConstants::PAYMENT_GET_URL.$paymentId.PPConstants::PAYMENT_REFUND_URL;
    }
    self::info("Payment url:$paymentUrl");
    $result = self::makeCurlCall($paymentUrl, "POST", json_encode($dataArray), NULL, $headers);
    $returnResult = NULL;
    if($result != NULL && is_array($result) 
            && isset($result["code"]) && isset($result["response"])) {
        $result = json_decode($result["response"]);
        if($result != NULL) {
            $returnResult = $result;
        }
    }
    self::info("Result: ");
    if($returnResult) {
        self::info($returnResult);
    } else {
        self::info($result);
    }
    return $returnResult;
}
?>

Output would be like this from valid refund:


stdClass Object
(
    [id] => 3E1338310M1546933
    [create_time] => 2014-04-07T13:08:52Z
    [update_time] => 2014-04-07T13:08:52Z
    [state] => completed
    [amount] => stdClass Object
        (
            [total] => 20.00
            [currency] => USD
        )

    [sale_id] => 6RE41122CN245801J
    [parent_payment] => PAY-99S90613BC814724UKNBKCVI
    [links] => Array
        (
            [0] => stdClass Object
                (
                    [href] => https://api.sandbox.paypal.com/v1/payments/refund/3E1338310M1546933
                    [rel] => self
                    [method] => GET
                )

            [1] => stdClass Object
                (
                    [href] => https://api.sandbox.paypal.com/v1/payments/payment/PAY-99S90613BC814724UKNBKCVI
                    [rel] => parent_payment
                    [method] => GET
                )

            [2] => stdClass Object
                (
                    [href] => https://api.sandbox.paypal.com/v1/payments/sale/6RE41122CN245801J
                    [rel] => sale
                    [method] => GET
                )

        )

)

Output would be like this from invalid refund:


stdClass Object
(
    [name] => TRANSACTION_REFUSED
    [message] => The request was refused.{0}
    [information_link] => https://developer.paypal.com/webapps/developer/docs/api/#TRANSACTION_REFUSED
    [debug_id] => 58299c9502f28
)

Sunday, April 6, 2014

Create Payment Using PayPal Api

REST API Reference - PayPal

Create a form such named 'createPayment.php' using following contents:


<?php
session_start();
require './PaypalBase.php';

if(count($_POST) > 0) {
    $dataArray = array(
        "intent" => "sale",
        "payer" => array(
            "payment_method" => "credit_card",
            "funding_instruments" => array(
                array (
                    "credit_card" => array(
                        "number" => $_POST["card"],
                        "type" => "visa",
                        "expire_month" => $_POST["cardMonth"],
                        "expire_year" => $_POST["cardYear"],
                        "cvv2" => $_POST["cardCvv"],
                        "first_name" => $_POST["firstName"],
                        "last_name" => $_POST["lastName"]
                    )
                )
            )
        ),
        "transactions" => array(
            array(
                "amount" => array(
                    "total" => floatval($_POST["subTotal"]) + floatval($_POST["tax"]) + floatval($_POST["shipping"]),
                    "currency" => $_POST["currency"],
                    "details" => array(
                        "subtotal" => floatval($_POST["subTotal"]),
                        "tax" => floatval($_POST["tax"]),
                        "shipping" => floatval($_POST["shipping"])
                    )
                )
            )
        )
    );
    $paymentArray = PaypalBase::createPayment($dataArray);
    if($paymentArray != NULL) {
        PaypalBase::printR($paymentArray); return;
    } else {
        echo "<b>Error in payment</b>";
    }
} else {
    $_POST["card"] = "4417119669820331"; /* Test credit card */
    $_POST["firstName"] = "Pritom";
    $_POST["lastName"] = "Kumar Mondal";
    $_POST["cardMonth"] = "06";
    $_POST["cardYear"] = "2018";
    $_POST["cardCvv"] = "123";
    $_POST["subTotal"] = "20";
    $_POST["tax"] = "10";
    $_POST["shipping"] = "10";
    $_POST["currency"] = "USD";
}
?>
<form method="POST">
    <table>
        <tr>
            <td colspan="2"><i>Card Information</i></td>
        </tr>
        <tr>
            <td>Card Number</td>
            <td><input name="card" value="<?php echo $_POST["card"]; ?>"/></td>
        </tr>
        <tr>
            <td>Card Name</td>
            <td>
                <input name="firstName" value="<?php echo $_POST["firstName"]; ?>"/>
                <input name="lastName" value="<?php echo $_POST["lastName"]; ?>"/>
            </td>
        </tr>
        <tr>
            <td>Card Expiry</td>
            <td>
                <input name="cardMonth" value="<?php echo $_POST["cardMonth"]; ?>"/>
                <input name="cardYear" value="<?php echo $_POST["cardYear"]; ?>"/>
            </td>
        </tr>
        <tr>
            <td>Card CVV</td>
            <td><input name="cardCvv" value="<?php echo $_POST["cardCvv"]; ?>"/></td>
        </tr>
        <tr>
            <td colspan="2"><i>Product Information</i></td>
        </tr>
        <tr>
            <td>Currency</td>
            <td><input name="currency" value="<?php echo $_POST["currency"]; ?>"/></td>
        </tr>
        <tr>
            <td>Sub Total</td>
            <td><input name="subTotal" value="<?php echo $_POST["subTotal"]; ?>"/></td>
        </tr>
        <tr>
            <td>Tax</td>
            <td><input name="tax" value="<?php echo $_POST["tax"]; ?>"/></td>
        </tr>
        <tr>
            <td>Shipping</td>
            <td><input name="shipping" value="<?php echo $_POST["shipping"]; ?>"/></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="submit" value="Pay..."/></td>
        </tr>
    </table>
</form>

createPayment method from 'PaypalBase.php'


<?php
public static function createPayment($dataArray) {
    self::info("createpayment");
    self::info("---------------------------------------------------------");
    self::info("---------------------------------------------------------");
    $accessToken = self::generateAccessToken(PPConstants::CLIENT_ID, PPConstants::CLIENT_SECRET);
    if(!$accessToken) {
        throw new Exception("Creating accessToken failed", NULL, NULL);
    }
    self::info("AccessToken: " . $accessToken);
    $headers = array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen(json_encode($dataArray)), 
        'Authorization: Bearer '.$accessToken,
        "PayPal-Request-Id" => self::generateRequestId(),
        "User-Agent" => self::getUserAgent()
    );
    $paymentUrl = PPConstants::REST_SANDBOX_ENDPOINT.  PPConstants::PAYMENT_CREATE_URL;
    if(!self::$testMode) {
        $paymentUrl = PPConstants::REST_LIVE_ENDPOINT.  PPConstants::PAYMENT_CREATE_URL;
    }
    self::info("Url: " . $paymentUrl);
    $result = self::makeCurlCall($paymentUrl, "POST", json_encode($dataArray), NULL, $headers);
    $returnResult = NULL;
    if($result != NULL && is_array($result) && isset($result["code"]) && isset($result["response"]) && $result["code"] == 201) {
        $result = json_decode($result["response"]);
        if($result != NULL) {
            $returnResult = $result;
        }
    }
    self::info("Result: ");
    if($returnResult) {
        self::info($returnResult);
    } else {
        self::info($result);
    }
    return $returnResult;
}
?>

Output would be like this from valid payment:


stdClass Object
(
    [id] => PAY-3H999973GM723222TKNAVENY
    [create_time] => 2014-04-06T13:10:15Z
    [update_time] => 2014-04-06T13:10:30Z
    [state] => approved
    [intent] => sale
    [payer] => stdClass Object
        (
            [payment_method] => credit_card
            [funding_instruments] => Array
                (
                    [0] => stdClass Object
                        (
                            [credit_card] => stdClass Object
                                (
                                    [type] => visa
                                    [number] => xxxxxxxxxxxx0331
                                    [expire_month] => 6
                                    [expire_year] => 2018
                                    [first_name] => Pritom
                                    [last_name] => Kumar Mondal
                                )

                        )

                )

        )

    [transactions] => Array
        (
            [0] => stdClass Object
                (
                    [amount] => stdClass Object
                        (
                            [total] => 40.00
                            [currency] => USD
                            [details] => stdClass Object
                                (
                                    [subtotal] => 20.00
                                    [tax] => 10.00
                                    [shipping] => 10.00
                                )

                        )

                    [related_resources] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [sale] => stdClass Object
                                        (
                                            [id] => 0HU38682D5581260D
                                            [create_time] => 2014-04-06T13:10:15Z
                                            [update_time] => 2014-04-06T13:10:30Z
                                            [state] => completed
                                            [amount] => stdClass Object
                                                (
                                                    [total] => 40.00
                                                    [currency] => USD
                                                )

                                            [parent_payment] => PAY-3H999973GM723222TKNAVENY
                                            [links] => Array
                                                (
                                                    [0] => stdClass Object
                                                        (
                                                            [href] => https://api.sandbox.paypal.com/v1/payments/sale/0HU38682D5581260D
                                                            [rel] => self
                                                            [method] => GET
                                                        )

                                                    [1] => stdClass Object
                                                        (
                                                            [href] => https://api.sandbox.paypal.com/v1/payments/sale/0HU38682D5581260D/refund
                                                            [rel] => refund
                                                            [method] => POST
                                                        )

                                                    [2] => stdClass Object
                                                        (
                                                            [href] => https://api.sandbox.paypal.com/v1/payments/payment/PAY-3H999973GM723222TKNAVENY
                                                            [rel] => parent_payment
                                                            [method] => GET
                                                        )

                                                )

                                        )

                                )

                        )

                )

        )

    [links] => Array
        (
            [0] => stdClass Object
                (
                    [href] => https://api.sandbox.paypal.com/v1/payments/payment/PAY-3H999973GM723222TKNAVENY
                    [rel] => self
                    [method] => GET
                )

        )

)