条纹Webhooks不起作用

时间:2013-12-26 07:20:01

标签: php codeigniter stripe-payments

我在应用程序中实现了条带测试网关... 集成页面使用jQuery模式发送数据。

它使用Codeigniter构建在MVC结构中。

现在,我的控制器:

<?php
class stripe_connect extends CI_Controller{
 public function __construct() {
        parent::__construct();
        @session_start();

    }

    function index()
    {
        $this->load->view('stripe_same_site_connect');
    }
}
?>

这是我的观点文件,

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="<?php echo base_url();?>assets/front_assets/stripe/js/jquery.js"></script>
        <script type="text/javascript" src="https://js.stripe.com/v1/"></script>

        <script type="text/javascript">
            Stripe.setPublishableKey('PUBLIC KEY'); // Test key!
        </script>

        <script type="text/javascript" src="<?php echo base_url();?>assets/front_assets/stripe/js/buy-controller.js"></script>
                <script>
                function showErrorDialogWithMessage(message)
{
    // For the tutorial, we'll just do an alert. You should customize this function to 
    // present "pretty" error messages on your page.
    alert(message);

    // Re-enable the submit button so the user can try again
    $('#buy-submit-button').removeAttr("disabled");
}


// Called when Stripe's server returns a token (or an error)
function stripeResponseHandler(status, response)
{
    if (response.error) 
    {
        // Stripe.js failed to generate a token. The error message will explain why.
        // Usually, it's because the customer mistyped their card info.
        // You should customize this to present the message in a pretty manner:
        alert(response.error.message);
    } 
    else 
    {   
        // Stripe.js generated a token successfully. We're ready to charge the card!
        var token = response.id;
        var firstName = $("#first-name").val();
        var lastName = $("#last-name").val();
        var email = $("#email").val();

        // We need to know what amount to charge. Assume $20.00 for the tutorial. 
        // You would obviously calculate this on your own:
        var price = 20;

        // Make the call to the server-script to process the order.
        // Pass the token and non-sensitive form information.
        var request = $.ajax ({
            type: "POST",
            url: "<?php echo base_url();?>ajax/stripe_payment",
            dataType: "json",
            data: {
                "stripeToken" : token,
                "firstName" : firstName,
                "lastName" : lastName,
                "email" : email,
                "price" : price
                }
        });

        request.done(function(msg)
        {
                        if (msg.result === 0)
            {
                // Customize this section to present a success message and display whatever
                // should be displayed to the user.
                alert(msg.message);
            }
            else
            {
                // The card was NOT charged successfully, but we interfaced with Stripe
                // just fine. There's likely an issue with the user's credit card.
                // Customize this section to present an error explanation
                alert("The user's credit card failed.");
            }
        });

        request.fail(function(jqXHR, textStatus)
        {
            // We failed to make the AJAX call to pay.php. Something's wrong on our end.
            // This should not normally happen, but we need to handle it if it does.
            alert("Error: failed to call pay.php to process the transaction.");
        });
    }
}



$(document).ready(function() 
{
    $('#buy-form').submit(function(event)
    {
        // immediately disable the submit button to prevent double submits
        $('#buy-submit-button').attr("disabled", "disabled");

        var fName = $('#first-name').val();
        var lName = $('#last-name').val();
        var email = $('#email').val();
        var cardNumber = $('#card-number').val();
        var cardCVC = $('#card-security-code').val();

        // First and last name fields: make sure they're not blank
        if (fName === "") {
            showErrorDialogWithMessage("Please enter your first name.");
            return;
        }
        if (lName === "") {
            showErrorDialogWithMessage("Please enter your last name.");
            return;
        }

        // Validate the email address:
        var emailFilter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if (email === "") {
            showErrorDialogWithMessage("Please enter your email address.");
            return;
        } else if (!emailFilter.test(email)) {
            showErrorDialogWithMessage("Your email address is not valid.");
            return;
        }

        // Stripe will validate the card number and CVC for us, so just make sure they're not blank
        if (cardNumber === "") {
            showErrorDialogWithMessage("Please enter your card number.");
            return;
        }
        if (cardCVC === "") {
            showErrorDialogWithMessage("Please enter your card security code.");
            return;
        }

        // Boom! We passed the basic validation, so request a token from Stripe:
        Stripe.createToken({
            number: cardNumber,
            cvc: cardCVC,
            exp_month: $('#expiration-month').val(),
            exp_year: $('#expiration-year').val()
        }, stripeResponseHandler);

        // Prevent the default submit action on the form
        return false;
    });
});
                </script>














    </head>

    <body>
        <h2>Payment Form</h2>

        <form id="buy-form" method="post" action="javascript:">

            <p class="form-label">First Name:</p>
            <input class="text" id="first-name" spellcheck="false"></input>

            <p class="form-label">Last Name:</p>
            <input class="text" id="last-name" spellcheck="false"></input>

            <p class="form-label">Email Address:</p>
            <input class="text" id="email" spellcheck="false"></input>

            <p class="form-label">Credit Card Number:</p>
            <input class="text" id="card-number" autocomplete="off"></input>

            <p class="form-label">Expiration Date:</p>
            <select id="expiration-month">
            <option value="1">January</option>
            <option value="2">February</option>
            <option value="3">March</option>
            <option value="4">April</option>
            <option value="5">May</option>
            <option value="6">June</option>
            <option value="7">July</option>
            <option value="8">August</option>
            <option value="9">September</option>
            <option value="10">October</option>
            <option value="11">November</option>
            <option value="12">December</option>
            </select>

            <select id="expiration-year">
                <?php 
                    $yearRange = 20;
                    $thisYear = date('Y');
                    $startYear = ($thisYear + $yearRange);

                    foreach (range($thisYear, $startYear) as $year) 
                    {
                        if ( $year == $thisYear) {
                            print '<option value="'.$year.'" selected="selected">' . $year . '</option>';
                        } else {
                            print '<option value="'.$year.'">' . $year . '</option>';
                        }
                    }
                ?>
            </select>

            <p class="form-label">CVC:</p>
            <input class="text" id="card-security-code" autocomplete="off"></input>

            <input id="buy-submit-button" type="submit" value="Place This Order »"></input>
        </form>
    </body>
</html>

这是ajax支付控制器文件:

<?php
class ajax extends CI_Controller{

    public function __construct() {
        parent::__construct();
        require APPPATH.'libraries/stripeLibrary/Stripe.php';
    }
    // Helper Function: used to post an error message back to our caller
function returnErrorWithMessage($message) 
{
    $a = array('result' => 1, 'errorMessage' => $message);
    echo json_encode($a);
}
    function stripe_payment()
    {
      // Credit Card Billing 
            //require_once('stripeLibrary/Stripe.php');  // change this path to wherever you put the Stripe PHP library!

            $trialAPIKey = "TEST KEY";  // These are the SECRET keys!
            $liveAPIKey = "LIVE KEY";

            Stripe::setApiKey($trialAPIKey);  // Switch to change between live and test environments

            // Get all the values from the form
            $token = $_POST['stripeToken'];
            $email = $_POST['email'];
            $firstName = $_POST['firstName'];
            $lastName = $_POST['lastName'];
            $price = $_POST['price'];

            $priceInCents = $price * 100;   // Stripe requires the amount to be expressed in cents

            try 
            {
                    // We must have all of this information to proceed. If it's missing, balk.
                    if (!isset($token)) throw new Exception("Website Error: The Stripe token was not generated correctly or passed to the payment handler script. Your credit card was NOT charged. Please report this problem to the webmaster.");
                    if (!isset($email)) throw new Exception("Website Error: The email address was NULL in the payment handler script. Your credit card was NOT charged. Please report this problem to the webmaster.");
                    if (!isset($firstName)) throw new Exception("Website Error: FirstName was NULL in the payment handler script. Your credit card was NOT charged. Please report this problem to the webmaster.");
                    if (!isset($lastName)) throw new Exception("Website Error: LastName was NULL in the payment handler script. Your credit card was NOT charged. Please report this problem to the webmaster.");
                    if (!isset($priceInCents)) throw new Exception("Website Error: Price was NULL in the payment handler script. Your credit card was NOT charged. Please report this problem to the webmaster.");

                    try 
                    {
                            // create the charge on Stripe's servers. THIS WILL CHARGE THE CARD!
                            $charge = Stripe_Charge::create(array(
                                    "amount" => $priceInCents,
                                    "currency" => "usd",
                                    "card" => $token,
                                    "description" => $email)
                            );

                            if ($charge->paid == true) 
                             {
                $array = array('result' => 0, 'email' => $email, 'price' => $price, 'message' => 'Thank you; your transaction was successful!');
                                echo json_encode($array);
                // Store the order in the database.
                // Send the email.
                // Celebrate!
                    } 
                            else { // Charge was not paid!  
                $array = array('result' => 0, 'email' => $email, 'price' => $price, 'message' => 'Not paid');
                                echo json_encode($array);
                     }
                            // If no exception was thrown, the charge was successful! 
                            // Here, you might record the user's info in a database, email a receipt, etc.

                            // Return a result code of '0' and whatever other information you'd like.
                            // This is accessible to the jQuery Ajax call return-handler in "buy-controller.js"

                    }
                    catch (Stripe_Error $e)
                    {
                            // The charge failed for some reason. Stripe's message will explain why.
                            $message = $e->getMessage();
                            returnErrorWithMessage($message);
                    }
            }
            catch (Exception $e) 
            {
                    // One or more variables was NULL
                    $message = $e->getMessage();
                    returnErrorWithMessage($message);
            }
    }
}

?>

现在的问题是,我收到了积极的警告信息,表明付款已经完成。

但是当我看到测试仪表板时,我无法获得任何交易记录。

此外,我也看不到仪表板中发生任何webhook事件,但我启用了webhook。

这是我的webhook网址:

http://the-iguts.com/wepay_testing/get_stripe_pay

我在controllwe文件中的脚本是:

<?php
class get_stripe_pay extends CI_Controller{

    public function __construct() {
        parent::__construct();
        require APPPATH.'libraries/stripeLibrary/Stripe.php';
    }

    function index()
    {
            $trialAPIKey = "TEST KEY";  // These are the SECRET keys!
            //$liveAPIKey = "LIVE KEY";

            Stripe::setApiKey($trialAPIKey);  // Switch to change between live and test environments
            $body = file_get_contents('php://input');
            $event_json = json_decode($body);
            $header = "From: MyApp Support <support@myapp.com>";
            $admin = "support@myapp.com";

            try {
                // for extra security, retrieve from the Stripe API, this will fail in Test Webhooks
                $event_id = $event_json->{'id'};
                $event = Stripe_Event::retrieve($event_id);

                if ($event->type == 'charge.succeeded') 
                {
                        $this->load->library('email');
                        $config['charset'] = 'utf-8';
                        $config['wordwrap'] = TRUE;
                        $config['mailtype'] = 'html';
                        $config['protocol'] = 'sendmail';
                        $this->email->initialize($config);
                        $this->email->from("saswat.saz.routroy@gmail.com");
                        $this->email->to($event->data->object->customer);
                        $this->email->subject("Payment");
                        $this->email->message("Payment");
                        if($this->email->send())
                        {
                            $this->email->from($event->data->object->customer);
                            $this->email->to("saswat.saz.routroy@gmail.com");
                            $this->email->subject("Payment");
                            $this->email->message("Payment");
                            if($this->email->send())
                            {
                                return "success";
                            }
                            else
                                die("error". mysql_error());
                        }
                    else
                            die("error". mysql_error());
                }

                // This will send receipts on succesful invoices
                if ($event->type == 'invoice.payment_succeeded') 
                {
                email_invoice_receipt($event->data->object, $header);
                }

                } 
                catch (Stripe_InvalidRequestError $e) 
                {
                   mail($admin, $e->getMessage(), $body, $header);
                }

                function email_payment_receipt($payment, $email, $header) 
                {
                    $subject = 'Payment has been received';
                    mail($email, $subject, payment_received_body($payment, $email), $header);     
                }


    }
}

?>

enter image description here

另见webhook部分,未发生任何事件。

enter image description here

0 个答案:

没有答案