2

私は MVC の初心者で、次のリンクを使用してペイパルの支払いプロセスを試みています。

http://www.arunrana.net/2012/01/paypal-integration-in-mvc3-and-razor.html

PaypalのIPNとPDTの実装方法を教えてください

データベースに保存したいPaypalから成功とトランザクションIDを取得する方法

前もって感謝します


"

public class CheckoutController : Controller
{
    CartContext _CartCotext = new CartContext();
    CartItemContext _CartItemContext = new CartItemContext();

    Tbl_OrderContext _OrderContext = new Tbl_OrderContext();
    OrderDetailContext _OrderDetailContext = new OrderDetailContext();
    ProductContext _ProductContext = new ProductContext();


    const string PromoCode = "FREE";

    [HttpPost]
    public ActionResult AddressAndPayment(CheckoutViewModel values)
    {

        var cart = ShoppingCart.GetCart(this.HttpContext);
        var _CartItems = Session["CartItems"];
        var list = (List<Cart>)Session["CartItems"];

        values.CartItems = list;

        var order = new CheckoutViewModel();
        order.CartItems = list;
        TryUpdateModel(order);

        {
            try
            {
                if (order.Tbl_Order == null)
                {
                    return View(order);
                }
                else
                {
                    order.Tbl_Order.Username = User.Identity.Name;
                    order.Tbl_Order.OrderDate = DateTime.Now;
                    order.Tbl_Order.CartTotal = order.CartTotal;
                    Session["carttotal"] = order.CartTotal;
                    order.Tbl_Order.Status = "Pending";



                    //Save Order

                    _OrderContext.OrderEntries.Add(order.Tbl_Order);
                    _OrderContext.SaveChanges();


                    //Process the order
                    string username = User.Identity.Name;
                    ShoppingCart obj = new ShoppingCart();
                    int i = obj.CreateOrder(order.Tbl_Order, order.CartItems, username);



                    //return RedirectToAction("Complete",
                    //   new { id = order.Tbl_Order.OrderId });
                    return RedirectToAction("PosttoPaypalShow");
                }

            }
            catch
            {
                //Invalid - redisplay with errors
                return View(order);
            }
        }

    }

    [HttpGet]
    public ActionResult PosttoPaypalShow()
    {

        SportsStore.Models.Paypal payPal = new Paypal();
        payPal.cmd = "_xclick";
        payPal.business = ConfigurationManager.AppSettings["BusinessAccount"];
        bool useSendBox = Convert.ToBoolean(ConfigurationManager.AppSettings["useSendbox"]);
        if (useSendBox)
        {
            ViewBag.actionURL = "https://www.sandbox.paypal.com/cgi-bin/webscr";
        }
        else
        {
            ViewBag.actionURL = "https://www.paypal.com/cgi-bin/webscr";
        }
        payPal.cancel_return = System.Configuration.ConfigurationManager.AppSettings["CancelUrl"];
        payPal.@return = ConfigurationManager.AppSettings["ReturnURL"];
        payPal.notify_url = ConfigurationManager.AppSettings["NotifyURL"];
        payPal.currency_code = ConfigurationManager.AppSettings["currencycode"];
        //payPal.item_Name = ProductName;
        payPal.item_Name = "test1";
        payPal.Descriptions = "tes2";
        payPal.amount = String.Format("{0:0.##}", Session["carttotal"]); //Convert.ToString(Session["carttotal"].ToString("0.00"));
        return View(payPal);
    }
    public ActionResult PaypalAddressAndPayment()
    {

        Tbl_Order order = new Tbl_Order();
        var cart = ShoppingCart.GetCart(this.HttpContext);


        // Set up the ViewModel
        var viewModel = new CheckoutViewModel
        {
            CartItems = cart.GetCartItems(),
            CartTotal = cart.GetTotal(),
            Tbl_Order = order
        };
        Session["CartItems"] = viewModel.CartItems;
        return View(viewModel);
        //return View(order);
    }
    string GetPayPalResponse(Dictionary<string, string> formVals, bool useSandbox)
    {

        string paypalUrl = useSandbox ? "https://www.sandbox.paypal.com/cgi-bin/webscr"
            : "https://www.paypal.com/cgi-bin/webscr";


        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(paypalUrl);

        // Set values for the request back
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";

        byte[] param = Request.BinaryRead(Request.ContentLength);
        string strRequest = Encoding.ASCII.GetString(param);

        StringBuilder sb = new StringBuilder();
        sb.Append(strRequest);

        foreach (string key in formVals.Keys)
        {
            sb.AppendFormat("&{0}={1}", key, formVals[key]);
        }
        strRequest += sb.ToString();
        req.ContentLength = strRequest.Length;

        //for proxy
        //WebProxy proxy = new WebProxy(new Uri("http://urlort#");
        //req.Proxy = proxy;
        //Send the request to PayPal and get the response
        string response = "";
        using (StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII))
        {

            streamOut.Write(strRequest);
            streamOut.Close();
            using (StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream()))
            {
                response = streamIn.ReadToEnd();
            }
        }

        return response;
    }

    public ActionResult IPN()
    {

        var formVals = new Dictionary<string, string>();
        formVals.Add("cmd", "_notify-validate");

        string response = GetPayPalResponse(formVals, true);

        if (response == "VERIFIED")
        {

            string transactionID = Request["txn_id"];
            string sAmountPaid = Request["mc_gross"];
            string orderID = Request["custom"];
            string pay_Status = Request["payment_status"];

            //_logger.Info("IPN Verified for order " + orderID);

            //validate the order
            Decimal amountPaid = 0;
            Decimal.TryParse(sAmountPaid, out amountPaid);

            //Order order = _orderService.GetOrder(new Guid(orderID));
            Tbl_Order order = null;
            //check the amount paid

            if (AmountPaidIsValid(order, amountPaid))
            {

                Tbl_Order add = new Tbl_Order();
                add.Username = User.Identity.Name;
                //add.FirstName = Request["first_name"];
                //add.LastName = Request["last_name"];
                //add.Email = Request["payer_email"];
                //add.Address = Request["address_street"];
                //add.City = Request["address_city"];
                //add.State = Request["address_state"];
                //add.Country = Request["address_country"];
                //add.PostalCode = Request["address_zip"];
                add.TransactionId = transactionID;
                add.Status = pay_Status;
                add.CartTotal = Convert.ToDecimal(sAmountPaid);


                //process it
                try
                {
                    _OrderContext.OrderEntries.Add(add);
                    _OrderContext.SaveChanges();
                    //_pipeline.AcceptPalPayment(order, transactionID, amountPaid);
                    //_logger.Info("IPN Order successfully transacted: " + orderID);
                    //return RedirectToAction("Receipt", "Order", new { id = order.ID });
                }
                catch
                {
                    //HandleProcessingError(order, x);
                    return View();
                }
            }
            else
            {
                //let fail - this is the IPN so there is no viewer
            }
        }



        return View();
    }
    bool AmountPaidIsValid(Tbl_Order order, decimal amountPaid)
    {

        //pull the order
        bool result = true;

        if (order != null)
        {
            if (order.CartTotal > amountPaid)
            {
                //_logger.Warn("Invalid order amount to PDT/IPN: " + order.ID + "; Actual: " + amountPaid.ToString("C") + "; Should be: " + order.Total.ToString("C") + "user IP is " + Request.UserHostAddress);
                result = false;
            }
        }
        else
        {
            //_logger.Warn("Invalid order ID passed to PDT/IPN; user IP is " + Request.UserHostAddress);
        }
        return result;

    }

}

public class Address
{
    public string FirstName { set; get; }
    public string LastName { set; get; }
    public string Email { set; get; }
    public string Street1 { set; get; }
    public string City { set; get; }
    public string StateOrProvince { set; get; }
    public string Country { set; get; }
    public string Zip { set; get; }

}"

および web.config ファイル構成に従う

  <add key="BusinessAccount" value="anilcs_1361585097_biz@gmail.com" />
    <add key="useSendbox" value="true" />
    <add key="currencycode" value="USD" />
    <add key="ReturnURL" value="http://localhost:49424/Checkout/IPN" />
    <add key="CancelUrl" value="http://localhost:49424/SportsStore/CancelFromPaypal" />
    <add key="NotifyURL" value="http://localhost:49424/SportsStore/NotifyFromPaypal" />
    <!--test MarchnatAccountId-->
    <add key =" MerchantAccountID" value="RCERFF5KTC784"/>

これは私のカートです

@model SportsStore.Models.Paypal
@{
    Layout = null;    
}
<html>
<head>
<title>Index</title>
<script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
</head>

</html>
<form id="frm" action="@ViewBag.Actionurl">

@Html.HiddenFor(Model => Model.cmd)
@Html.HiddenFor(Model => Model.business)
@Html.HiddenFor(Model => Model.no_shipping)
@Html.HiddenFor(Model => Model.@return)
@Html.HiddenFor(Model => Model.cancel_return)
@Html.HiddenFor(Model => Model.notify_url)
@Html.HiddenFor(Model => Model.currency_code)
@Html.HiddenFor(Model => Model.item_Name)
@Html.HiddenFor(Model => Model.amount)

</form>
<p style="text-align: center">
    <h4>
        Redirecting to Paypal</h4>
</p>
<script type="text/javascript" language="javascript">
    $(this.document).ready(function () {
        var frm = $("form");
        frm.submit();
    });   
</script>

その後、配送の詳細を入力し、私のページをペイパルにリダイレクトします

{

@model SportsStore.Models.CheckoutViewModel
@{
    ViewBag.Title = "Address And Payment";
}
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm("AddressAndPayment", "Checkout"))
{
    <table>
        <thead>
            <tr>
                <th>
                    @Html.LabelFor(m => m.Tbl_Order.OrderId, "OrderId")
                </th>
                <td>
                    @Html.TextBoxFor(m => m.Tbl_Order.OrderId, new { disabled = "disabled", @readonly = "readonly" })
                </td>
            </tr>
            <tr>
                <th>
                    @Html.LabelFor(m => m.Tbl_Order.OrderDate, "OrderDate")
                </th>
                <td>
                    @Html.EditorFor(m => m.Tbl_Order.OrderDate, "OrderDate")
                    @Html.EditorFor(m => m.CartItems, "CartItems")
                </td>
            </tr>
            <tr>
                <th>
                    @Html.LabelFor(m => m.Tbl_Order.FirstName, "First Name")
                </th>
                <td>
                    @Html.EditorFor(m => m.Tbl_Order.FirstName, "First Name")
                </td>
            </tr>
            <tr>
                <th>
                    @Html.LabelFor(m => m.Tbl_Order.LastName, "Last Name")
                </th>
                <td>
                    @Html.EditorFor(m => m.Tbl_Order.LastName, "Last Name")
                </td>
            </tr>
            <tr>
                <th>
                    @Html.LabelFor(m => m.Tbl_Order.Address, "Address")
                </th>
                <td>
                    @Html.EditorFor(m => m.Tbl_Order.Address, "Address")
                </td>
            </tr>
            <tr>
                <th>
                    @Html.LabelFor(m => m.Tbl_Order.City, "City")
                </th>
                <td>
                    @Html.EditorFor(m => m.Tbl_Order.City, "City")
                </td>
            </tr>
            <tr>
                <th>
                    @Html.LabelFor(m => m.Tbl_Order.State, "State")
                </th>
                <td>
                    @Html.EditorFor(m => m.Tbl_Order.State, "State")
                </td>
            </tr>
            <tr>
                <th>
                    @Html.LabelFor(m => m.Tbl_Order.PostalCode, "PostalCode")
                </th>
                <td>
                    @Html.EditorFor(m => m.Tbl_Order.PostalCode, "PostalCode")
                </td>
            </tr>
            <tr>
                <th>
                    @Html.LabelFor(m => m.Tbl_Order.Country, "Country")
                </th>
                <td>
                    @Html.EditorFor(m => m.Tbl_Order.Country, "Country")
                </td>
            </tr>
            <tr>
                <th>
                    @Html.LabelFor(m => m.Tbl_Order.Phone, "Phone")
                </th>
                <td>
                    @Html.EditorFor(m => m.Tbl_Order.Phone, "Phone")
                </td>
            </tr>
            <tr>
                <th>
                    @Html.LabelFor(m => m.Tbl_Order.Email, "Email")
                </th>
                <td>
                    @Html.EditorFor(m => m.Tbl_Order.Email, "Email")
                </td>
            </tr>
            <tr>
                <th>
                    @Html.LabelFor(m => m.CartTotal, "Total")
                </th>
                <td>
                    @*   @Html.EditorFor(m => m.CartTotal, "Total" ) *@ @*  @Html.TextBoxFor(m => m.CartTotal, new { disabled = "disabled", @readonly = "readonly" })*@
                    @* @Html.DisplayTextFor(m => m.CartTotal)*@
                    @Html.TextBoxFor(m => m.CartTotal, new { @readonly = "readonly" })
                </td>
            </tr>
            <tr>
                <td>
                </td>
                Continoue with paypal
                <td>
                </td>
            </tr>
            <tr>
                <td>
                    @* @Html.ActionLink("Sure to payment", "PosttoPaypalShow", "Checkout")*@
                    <input type="submit" value="Submit" />
                </td>
            </tr>
        </thead>
    </table>





}

1 質問 - これは私が行った適切な方法ですか?

2 質問 - Paypal からカスタム値を返す方法

3 また、支払い後に web.config ファイルを参照してください。PIN を呼び出す必要がありますか?

ガイドしてください ...... そして支払いプロセスを行う方法

4

1 に答える 1