Last commit for views/elements/CreditconfigElement.php: 1391d4923f22f4e1c08d1389ee23802f4e407fb1

Additional changes to get ad script download working, a=chris

Chris Pollett [2015-09-01 17:Sep:st]
Additional changes to get ad script download working, a=chris
<?php
namespace seekquarry\yioop\views\elements;

use seekquarry\yioop as B;
use seekquarry\yioop\configs as C;
use seekquarry\yioop\library as L;

class CreditconfigElement extends Element
{
    /**
     * Displays the CreditConfig script in a textarea
     *
     * @param array $data  available activities and CSRF token
     */
    public function render($data)
    {
        $hash_initialize = "FN" . L\crawlHash($data["NAME_SERVER"] .
            C\YIOOP_VERSION . "getCreditTokenInitializeScript");
        $hash_submit = "FN" . L\crawlHash($data["NAME_SERVER"] .
            C\YIOOP_VERSION . "getSubmitPurchaseScript");
        $purchase_script = <<< 'ZZZ'
<?php
/**
 * SeekQuarry/Yioop -- Credit Card Configuration
 *
 * Copyright (C) 2015  Chris Pollett chris@pollett.org
 * All rights reserved
 */
namespace seekquarry\yioop\configs;

use seekquarry\yioop\library\FetchUrl;

/**
 * Class containing methods used to handle payment processing when keyword
 * advertising is enabled.
 *
 */
class CreditConfig
{
    const PUBLISHABLE_KEY = "";
    const SECRET_KEY = "";
    const TOKEN_URL = "https://js.stripe.com/v2/";
    const CHARGE_URL = "https://api.stripe.com/v1/charges";
    const CHARGE_CURRENCY = "usd";
    const CHARGE_DESCRIPTION = "NAME BUYER WILL SEE CHARGE AS";
    /**
     * Returns whether a version of CreditConfig actually capable of charging
     * cards, receiving bitcoins, etc is in use.
     *
     * @return bool whether a real credit card processing class is use
     */
    public static function isActive()
    {
        return true;
    }
    /**
     * Returns the URL to the credit processing Javascript responsible for
     * sending securely the credit card details to the credit payment agency
     * (for example, stripe.com) then sending along a authorization token
     * as part of the form to the Yioop backend
     * @return string
     */
    public static function getCreditTokenUrl()
    {
        return self::TOKEN_URL;
    }
    /**
     * An initialization Javascript used to set up the Credit payment agency's
     * Javascript
     *
     * @return string
     */
ZZZ;
        $purchase_script .= <<< ZZZ

    public static function {$hash_initialize}()
ZZZ;
        $purchase_script .= <<< 'ZZZ'
    {
        return "\nStripe.setPublishableKey('" .
            self::getPublishableKey() . "');\n";
    }
    /**
     * Returns inline Javascript needed to send credit card details off
     * to credit processing agency by invoking the Javascript credit processing
     * library methods
     *
     * @return string
     */
ZZZ;
        $purchase_script .= <<< ZZZ

    public static function {$hash_submit}()
ZZZ;
        $purchase_script .= <<< 'ZZZ'
    {
        return <<< EOD
            <script type="text/javascript">
            document.getElementById('purchase').onclick =
                function(event) {
                    var ad_form = elt('createAdvertisementForm');
                    elt('purchase').disabled = true;
                    Stripe.card.createToken(ad_form, tokenResponseHandler);
                    event.preventDefault();
                }
            function tokenResponseHandler(status, response) {
                var ad_form = elt('createAdvertisementForm');
                if (response.error) {
                    alert(response.error.message);
                    elt('purchase').disabled = false;
                } else {
                    elt('duration').disabled = false;
                    elt('credit-token').value = response.id;
                    ad_form.submit();
                }
            }
            </script>
EOD;
    }
    /**
     * Used to get field values from input tag with attribute name set to $name
     * and attribute value set to value
     * @param string $name of attribute (usually data-)
     * @param string $value value of attribute
     * @return string field value of the correspond input tag
     */
    public static function getAttribute($name, $type)
    {
        $type = ($type == 'name') ? 0 : 1;
        $names = [
            'card-number' => ['data-stripe', 'number'],
            'cvc' => ['data-stripe', 'cvc'],
            'exp-month' => ['data-stripe', 'exp-month'],
            'exp-year' => ['data-stripe', 'exp-year']
        ];

        return isset($names[$name][$type]) ? $names[$name][$type] : "";
    }
    /**
     * Server side method that is actually responsible for charging the
     * credit card
     *
     * @param float $amount dollar amount to charge the card
     * @param string $token token issued for transaction from the card
     *      processing agency
     * @param string& $message message to use as for reason for charge
     * @return bool whether or not the charge was successful
     */
    public static function charge($amount, $token, &$message)
    {
        $charge = [
            //swipe charges in cents * 100 to convert to dollars
            "amount" => $amount * 100,
            "currency" => self::CHARGE_CURRENCY,
            "source" => $token,
            "description" => self::CHARGE_DESCRIPTION
        ];
        $response = FetchUrl::getPage(self::CHARGE_URL,
            http_build_query($charge), true, self::getSecretKey() . ":");
        $credit_info = json_decode($response, true);
        unset($_REQUEST['CREDIT_TOKEN']);
        return isset($credit_info['status']) &&
            $credit_info['status'] == 'succeeded';
    }
    /*
     * Depending on the field mode returns either the test or production
     * publishable key issued by payment agency to seller.
     *
     * @return string key
     */
    private static function getPublishableKey()
    {
        return self::PUBLISHABLE_KEY;
    }
    /*
     * Depending on the field mode returns either the test or production
     * secret key issued by payment agency to seller.
     *
     * @return string key
     */
    private static function getSecretKey()
    {
        return self::SECRET_KEY;
    }
}

ZZZ;
        $purchase_script = htmlentities($purchase_script);
        ?>
        <textarea class="tall-text-area" readonly="readonly"><?=
            $purchase_script; ?></textarea>
        <?php
    }
}
ViewGit