【问题标题】:PHP mailer is sending, however some code is not rendering after the sendPHP 邮件正在发送,但是在发送后某些代码未呈现
【发布时间】:2015-06-15 04:09:03
【问题描述】:

我不确定标题的最佳表达方式。我的问题涉及这个函数mail($to, $subject, $message, $headers); 我让它运行在一个 PHP 文件的中间,该文件从表单中获取信息,使用条带 api 创建一个令牌,然后用条带对该卡进行收费。

Stripe 仍然接收数据并通过包含邮件功能正确地向卡收费,但是页面并没有像以前那样显示成功消息,除了标题显示在购买后通常是表单之外几乎没有任何内容将清除并显示成功消息。就像邮件功能未包含在成功的表单提交中之后的任何事情一样。

我大部分时间都花在 javascript 上,所以这可能完全是我对 PHP 的不熟悉。

下面是完整的代码。

<?php include 'head.php'; ?>
<body>

  <!--header-->
  <?php include 'header.php'; ?>


  <!--header-->

  <script type="text/javascript">
  // $('input.quantity').keyup(function(){
  //     var value = $( this ).val();
  //     var bookQuantity = $( "input.bfh-number" ).text( value );
  //     console.log(bookQuantity);
  // })




  $(document).ready(function() {


    $( ".quantity" )
  .keyup(function() {
    var value = $( this ).val();
    console.log(value);
    subTotal = 150 * value;
    $( '.paymentTotal' ).text( '$' + subTotal );
  }).keyup();


    $('#payment-form').bootstrapValidator({
      message: 'This value is not valid',
      feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
      },
      submitHandler: function(validator, form, submitButton) {
        var chargeAmount = 3000; //amount you want to charge, in cents. 1000 = $10.00, 2000 = $20.00 ...
        // createToken returns immediately - the supplied callback submits the form if there are no errors
        Stripe.createToken({
          number: $('.card-number').val(),
          cvc: $('.card-cvc').val(),
          exp_month: $('.card-expiry-month').val(),
          exp_year: $('.card-expiry-year').val(),
          name: $('.card-holder-name').val(),
          address_line1: $('.address').val(),
          address_city: $('.city').val(),
          address_zip: $('.zip').val(),
          address_state: $('.state').val(),
          quantity: $('.quantity').val(),
          address_country: $('.country').val()
        }, chargeAmount, stripeResponseHandler);
        return false; // submit from callback
      },
      fields: {
        street: {
          validators: {
            notEmpty: {
              message: 'The street is required and cannot be empty'
            },
            stringLength: {
              min: 6,
              max: 96,
              message: 'The street must be more than 6 and less than 96 characters long'
            }
          }
        },
        city: {
          validators: {
            notEmpty: {
              message: 'The city is required and cannot be empty'
            }
          }
        },
        zip: {
          validators: {
            notEmpty: {
              message: 'The zip is required and cannot be empty'
            },
            stringLength: {
              min: 3,
              max: 9,
              message: 'The zip must be more than 3 and less than 9 characters long'
            }
          }
        },
        email: {
          validators: {
            notEmpty: {
              message: 'The email address is required and cannot be empty'
            },
            emailAddress: {
              message: 'The input is not a valid email address'
            },
            stringLength: {
              min: 6,
              max: 65,
              message: 'The email must be more than 6 and less than 65 characters long'
            }
          }
        },
        cardholdername: {
          validators: {
            notEmpty: {
              message: 'The card holder name is required and cannot be empty'
            },
            stringLength: {
              min: 6,
              max: 70,
              message: 'The card holder name must be more than 6 and less than 70 characters long'
            }
          }
        },
        first_name: {
          validators: {
            notEmpty: {
              message: 'The card holder name is required and cannot be empty'
            }
          }
        },
        cardnumber: {
          selector: '#cardnumber',
          validators: {
            notEmpty: {
              message: 'The credit card number is required and cannot be empty'
            },
            creditCard: {
              message: 'The credit card number is invalid'
            },
          }
        },
        expMonth: {
          selector: '[data-stripe="exp-month"]',
          validators: {
            notEmpty: {
              message: 'The expiration month is required'
            },
            digits: {
              message: 'The expiration month can contain digits only'
            },
            callback: {
              message: 'Expired',
              callback: function(value, validator) {
                value = parseInt(value, 10);
                var year         = validator.getFieldElements('expYear').val(),
                currentMonth = new Date().getMonth() + 1,
                currentYear  = new Date().getFullYear();
                if (value < 0 || value > 12) {
                  return false;
                }
                if (year == '') {
                  return true;
                }
                year = parseInt(year, 10);
                if (year > currentYear || (year == currentYear && value > currentMonth)) {
                  validator.updateStatus('expYear', 'VALID');
                  return true;
                } else {
                  return false;
                }
              }
            }
          }
        },
        expYear: {
          selector: '[data-stripe="exp-year"]',
          validators: {
            notEmpty: {
              message: 'The expiration year is required'
            },
            digits: {
              message: 'The expiration year can contain digits only'
            },
            callback: {
              message: 'Expired',
              callback: function(value, validator) {
                value = parseInt(value, 10);
                var month        = validator.getFieldElements('expMonth').val(),
                currentMonth = new Date().getMonth() + 1,
                currentYear  = new Date().getFullYear();
                if (value < currentYear || value > currentYear + 100) {
                  return false;
                }
                if (month == '') {
                  return false;
                }
                month = parseInt(month, 10);
                if (value > currentYear || (value == currentYear && month > currentMonth)) {
                  validator.updateStatus('expMonth', 'VALID');
                  return true;
                } else {
                  return false;
                }
              }
            }
          }
        },
        cvv: {
          selector: '#cvv',
          validators: {
            notEmpty: {
              message: 'The cvv is required and cannot be empty'
            },
            cvv: {
              message: 'The value is not a valid CVV',
              creditCardField: 'cardnumber'
            }
          }
        },
      }
    });
  });
</script>
<script type="text/javascript">
  // this identifies your website in the createToken call below
  //Stripe.setPublishableKey('pk_live_random');
  Stripe.setPublishableKey('pk_test_random');



  function stripeResponseHandler(status, response) {
    if (response.error) {
      // re-enable the submit button
      $('.submit-button').removeAttr("disabled");
      // show hidden div
      document.getElementById('a_x200').style.display = 'block';
      // show the errors on the form
      $(".payment-errors").html(response.error.message);
    } else {
      var form$ = $("#payment-form");
      // token contains id, last4, and card type
      var token = response['id'];
      // insert the token into the form so it gets submitted to the server
      form$.append("<input type='hidden' name='stripeToken' value='" + token + "' />");
      // and submit
      form$.get(0).submit();
    }
  }

</script>

<!--content-->

<div class="global indent">
  <div class="container partner-wrap">
    <form action="" method="POST" id="payment-form" class="form-horizontal">
      <div class="row"> <div class="col-lg-6"><img id="buyImage" src="img/book.jpg" /></div>
        <div class="col-lg-6"><h2>The Economic Definition of Ore</h2><p>Price:$150</p>
          <label class="control-label" for="textinput">Quantity</label>
          <div class="form-group col-sm-4">
            <div class="col-lg-12">
            <h4>Quantity</h4>
            </div>
            <div class="col-lg-12">
            <input type="text" name="quantity" value="1" data-buttons="false" class="quantity form-control bfh-number">
            </div>
          </div>

          <div class="col-sm-8">
          <h4 class="subTotalRight borderBottom">Total:</h4>
          <h5 class="paymentTotal subTotalRight"></h5>
          </div>
        </div>

  </div>




    <div class="row row-centered">
      <div class="col-md-12">
        <div class="page-header">
          <h2 class="gdfg">Secure Payment Form</h2>
        </div>
        <noscript>
          <div class="bs-callout bs-callout-danger">
            <h4>JavaScript is not enabled!</h4>
            <p>This payment form requires your browser to have JavaScript enabled. Please activate JavaScript and reload this page. Check <a href="http://enable-javascript.com" target="_blank">enable-javascript.com</a> for more informations.</p>
          </div>
        </noscript>
        <?php

        $error = '';
        $success = '';

        require 'Stripe.php';

        if ($_POST) {

          $token = $_POST['stripeToken'];
          $email = $_POST["email"];
          $quantity = $_POST["quantity"];
          $firstName = $_POST["firstName"];
          $lastName = $_POST["lastName"];


          // Get the values from the $_POST array:
         $price = 15000;




        $total = $price * $quantity;
        $customertotal = $price * $quantity / 100;



          //Stripe::setApiKey("sk_random");
          Stripe::setApiKey("sk_random");

          $error = '';
          $success = '';





          try {

            $customer = Stripe_Customer::create(array(
            'email' => $email,
            'card'  => $token,
            "description" => $quantity . " copies of The Economic Definition of Ore -Cut-off Grades in Theory and Practice"
            ));

            $charge = Stripe_Charge::create(array(
            "amount" => $total, // amount in cents, again
            "currency" => "cad",
            'customer' => $customer->id,
            "metadata" => array("First Name:" => $firstName, "Last Name:" => $lastName)

            )
            );

            $success = '<div class="alert alert-success">
              <strong>Success!</strong> Your payment was successful. For $' . $customertotal . ', and you have ordered ' . $quantity . ' copies </div>';



              $to  = $email; // note the comma

              // subject
              $subject = 'Economic Definition of Ore Purchase';

              // message
              $message = '
              <html>
              <head>
                <title>Sumary of Purchase</title>
              </head>
              <body>
                <table>
                  <tr>
                    <td> Hi ' . $firstName . '</td>
                  </tr>
                  <tr>
                    <td>
                      <p>Here is a summary of your recent purchase.</p>
                    </td>
                  </tr>
                  <tr>
                    <td>
                      <p>Your total purchase is $'.$customertotal . ' </p>
                      <p>The number of books you have ordered is <b>'  . $quantity . '</b> </p>
                    </td>
                  </tr>

                </table>
              </body>
              </html>
              ';

              // To send HTML mail, the Content-type header must be set
              $headers  = 'MIME-Version: 1.0' . "\r\n";
              $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

              // Additional headers
              $headers .= 'To: '. $firstName .' <' . $email . ' >  ' . "\r\n";
              $headers .= 'From: Comet <info@cometstrategy.com>' . "\r\n";
              // $headers .= 'Bcc: birthdaycheck@example.com' . "\r\n";

              // Mail it
              mail($to, $subject, $message, $headers);



          }
          catch (Exception $e) {
            $error = '<div class="alert alert-danger">
              <strong></strong> '.$e->getMessage().'
            </div>';
          }
        }
        ?>
        <span class="payment-success">
          <?= $success ?>
          <?= $error ?>

        </span>

        <div class="alert alert-danger" id="a_x200" style="display: none;"> <strong></strong> Please fill out all required fields. </div>




          <!-- Street -->

          <div class="row">
            <div class="col-md-6">

              <!-- Form Name -->
              <legend>Billing Details</legend>


              <fieldset>


          <!-- Street -->
          <div class="form-group">
            <label class="col-sm-4 control-label" for="textinput">First Name</label>
            <div class="col-sm-12">
              <input type="text" name="firstName" placeholder="First Name" class="firstName form-control">
            </div>
          </div>

          <!-- Street -->
          <div class="form-group">
            <label class="col-sm-4 control-label" for="textinput">Last Name</label>
            <div class="col-sm-12">
              <input type="text" name="lastName" placeholder="Last Name" class="firstName form-control">
            </div>
          </div>



          <!-- Street -->
          <div class="form-group">
            <label class="col-sm-4 control-label" for="textinput">Street</label>
            <div class="col-sm-12">
              <input type="text" name="street" placeholder="Billing Address" class="address form-control">
            </div>
          </div>

          <!-- City -->
          <div class="form-group">
            <label class="col-sm-4 control-label" for="textinput">City</label>
            <div class="col-sm-12">
              <input type="text" name="city" placeholder="City" class="city form-control">
            </div>
          </div>

          <!-- State -->
          <div class="form-group">
            <label class="col-sm-4 control-label" for="textinput">State</label>
            <div class="col-sm-12">
              <input type="text" name="state" maxlength="65" placeholder="State" class="state form-control">
            </div>
          </div>

          <!-- Postcal Code -->
          <div class="form-group">
            <label class="col-sm-4 control-label" for="textinput">Postal Code</label>
            <div class="col-sm-12">
              <input type="text" name="zip" maxlength="9" placeholder="Postal Code" class="zip form-control">
            </div>
          </div>

          <!-- Country -->
          <div class="form-group">
            <label class="col-sm-4 control-label" for="textinput">Country</label>
            <div class="col-sm-12">
              <!--input type="text" name="country" placeholder="Country" class="country form-control"-->
              <!-- <div class="country bfh-selectbox bfh-countries" name="country" placeholder="Select Country" data-flags="true" data-filter="true"> </div> -->
              <select class="form-control bfh-countries" data-country="AU"></select>
              <!-- <div class="bfh-selectbox bfh-countries" data-country="AU" data-flags="true"> -->
              <!-- </div> -->
            </div>
          </div>

          <!-- Email -->
          <div class="form-group">
            <label class="col-sm-4 control-label" for="textinput">Email</label>
            <div class="col-sm-12">
              <input type="text" name="email" maxlength="65" placeholder="Email" class="email form-control">
            </div>
          </div>


        </div>

        <div class="col-md-6">


          <fieldset>
            <legend>Card Details</legend>

            <!-- Card Holder Name -->
            <div class="form-group">
              <label class="col-sm-4 control-label"  for="textinput">Card Holder's Name</label>
              <div class="col-sm-12">
                <input type="text" name="cardholdername" maxlength="70" placeholder="Card Holder Name" class="card-holder-name form-control">
              </div>
            </div>

            <!-- Card Number -->
            <div class="form-group">
              <label class="col-sm-4 control-label" for="textinput">Card Number</label>
              <div class="col-sm-12">
                <input type="text" id="cardnumber" maxlength="19" placeholder="Card Number" class="card-number form-control">
              </div>
            </div>

            <!-- Expiry-->
            <div class="form-group">
              <label class="col-xs-12 col-sm-12 control-label" for="textinput">Card Expiry Date</label>
              <div class="col-sm-12">
                <div class="form-inline">
                  <select name="select2" data-stripe="exp-month" class="card-expiry-month stripe-sensitive required form-control">
                    <option value="01" selected="selected">01</option>
                    <option value="02">02</option>
                    <option value="03">03</option>
                    <option value="04">04</option>
                    <option value="05">05</option>
                    <option value="06">06</option>
                    <option value="07">07</option>
                    <option value="08">08</option>
                    <option value="09">09</option>
                    <option value="10">10</option>
                    <option value="11">11</option>
                    <option value="12">12</option>
                  </select>
                  <span> / </span>
                  <select name="select2" data-stripe="exp-year" class="card-expiry-year stripe-sensitive required form-control">
                  </select>
                  <script type="text/javascript">
                    var select = $(".card-expiry-year"),
                    year = new Date().getFullYear();

                    for (var i = 0; i < 12; i++) {
                      select.append($("<option value='"+(i + year)+"' "+(i === 0 ? "selected" : "")+">"+(i + year)+"</option>"))
                    }
                  </script>
                </div>
              </div>
            </div>

            <!-- CVV -->
            <div class="form-group">
              <label class="col-sm-4 control-label" for="textinput">CVV/CVV2</label>
              <div class="col-sm-4">
                <input type="text" id="cvv" placeholder="CVV" maxlength="4" class="card-cvc form-control">
              </div>

            </div>
            <hr>
            <div class="row">
            <div class="col-sm-12">
              <h3>Total ($USD)</h3>
            </div>
            <div class="col-sm-12">
            <h4 class="paymentTotal"></h4>
            </div>

            <div class="col-sm-12">
              <button class="btn btn-success" type="submit">Pay Now</button>
            </div>

          </div>
            <!-- Important notice -->
            <!-- <div class="form-group"> -->
              <!-- <div class="panel panel-success"> -->
              <!-- <div class="panel-heading">
              <h3 class="panel-title">Important notice</h3>
            </div>
            <div class="panel-body">
            <p>Your card will be charged 30€ after submit.</p>
            <p>Your account statement will show the following booking text:
            XXXXXXX </p>
          </div>
        </div> -->


      </fieldset>
    </div>
  </div>
    </form>

  </div>
</div>


  </div>
</div>

    <!--footer-->
    <?php include 'footer.php'; ?>

    <script src="js/bootstrap.min.js"></script>
    <script src="js/tm-scripts.js"></script>
  </body>
  </html>

【问题讨论】:

  • 您的错误日志中有什么内容吗?邮件真的发送成功了吗?听起来邮件功能(或附近的东西)是致命的。
  • 电子邮件发送正常,我的 php 错误日志在哪里,我已经设置了带有数字海洋的服务器以显示 php 错误。

标签: javascript php email stripe-payments


【解决方案1】:

anything 在 PHP 块被发送到客户端之后(如果您查看源代码,&lt;noscript&gt; 块之后是否有任何 HTML?),还是 payment-success 跨度只是空的?

如果是前者(在 PHP 块之后没有任何内容),则在调用 mail() 之后执行将停止。如果mail() 报告某种错误,它不会被try/catch 捕获,因为它是一个不会抛出异常的内部函数——它依赖于旧的PHP 错误报告机制。出于调试目的,尝试设置error_reporting(E_ALL) 并手动测试以查看mail() 是否返回true

<?php // Top of the file error_reporting(E_ALL); include 'head.php'; ?> .... ... // In the PHP block where you call mail() if (!mail($to, $subject, $message, $headers)) { echo "There was a problem with mail()<br />\n"; }

然后,提交表单并查看输出中某处是否有 PHP 错误消息和/或消息“mail() 出现问题”。根据您的发现,我们可以从那里开始。

【讨论】:

  • 我似乎没有得到任何结果,您建议的代码已上传到此站点mini-dev.cf/purchase.php您可以使用 4242424242424242 作为条带测试卡。提交表单也需要很长时间。
  • 老实说,PHP 脚本似乎只是超时了,因为某些事情花费了太长时间。您可以使用set_time_limit () 将超时增加到更高的量(默认值为 30 秒),但最好弄清楚是什么阻碍了执行。它可能是对 Stripe API 的调用。尝试注释掉 API 调用,如果不起作用,注释掉 mail() 调用,我们会看看是什么原因造成的。
  • 确实是 mail() 调用让事情变慢了,我原本只想用 smtp 服务器做这个邮件,但我们的客户承认他们的服务器处理邮件发送,因为那就是如何它过去曾奏效。目前还不确定如何调试。
  • 当。好吧,如果无法对系统上的 SMTP 进行故障排除,请查看此线程,该线程讨论了卸载调用,以便您的脚本仍然可以及时执行:stackoverflow.com/questions/6618293/… 不理想,但可能是您的问题在这种情况下重新寻找。我对 SMTP 程序了解不足,无法解决缓慢的实际原因,如果它是共享服务器,无论如何您可能没有太多能力解决问题。
  • 我看了那个问题,我不确定如何应用参数部分,将数据传递给单独的 php 文件。我会考虑存储在数据库中,但如果我可以通过传递一些理想的参数来做到这一点,因为我没有 mysql 和 php 数据库交互。
猜你喜欢
  • 1970-01-01
  • 2012-02-04
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 2014-03-06
  • 2015-11-07
  • 2010-09-24
  • 1970-01-01
相关资源
最近更新 更多