H5網站接入Paypal支付介面

来源:http://www.cnblogs.com/yuanxinSix/archive/2017/05/12/6846077.html
-Advertisement-
Play Games

寫本文章的目的是為了記錄工作中遇到的問題,方便以後遇到可以迅速解決問題 paypal支付介面實現由幾種方法,我使用的是REST API 所以在這裡值介紹這種方法的使用 我們使用vs的Nuget下載Paypal的dll 首先需要配置Web.config文件 1.在configuration節點下配置c ...


寫本文章的目的是為了記錄工作中遇到的問題,方便以後遇到可以迅速解決問題

paypal支付介面實現由幾種方法,我使用的是REST API

所以在這裡值介紹這種方法的使用

我們使用vs的Nuget下載Paypal的dll

首先需要配置Web.config文件

1.在configuration節點下配置configsections中的section節點

2.在configuration節點下配置paypal節點

<configuration> 
<configSections> <!--IMPORTANT: Make sure you add the configSections node to your config file so that the rest of the config file is picked by the application--> <section name="paypal" type="PayPal.SDKConfigHandler, PayPal" /> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> </configSections>
  <paypal>
    <settings>
      <!-- Replace the mode to `security-test-sandbox` to test if your server supports TLSv1.2. For more information follow README instructions.-->
      <add name="mode" value="sandbox" />
      <add name="connectionTimeout" value="360000" />
      <add name="requestRetries" value="1" />
      <add name="clientId" value="ATnMWGSD5FAe8_kd5eA83ZN5V5jiRY57CCqYUG6We3uDrIfZNSolS_CZ0DK2I74yf03IEcN8HgMIl3Md" />
      <add name="clientSecret" value="ENW9z0srkaWrowK5BQif52xHJoDoTaqZU38bz-y0mAz37sHDD9okHubjPcr0gmkZtlR9MbVuMshl_hyX" />
    </settings>
  </paypal>
</configuration>

clientid,和clientSecret的值需要自己在沙箱中配置,才能得到

用戶點擊付款按鈕時,調用這個方法

引用命名空間

using PayPal.Api;

 public ActionResult PaypalPayment(string orderNo)
        {
            try
            {
                var config = ConfigManager.Instance.GetProperties();//讀取配置文件
                var accessToken = new OAuthTokenCredential(config).GetAccessToken();
                var apiContext = new APIContext(accessToken);
                string payerId = Request.Params["PayerID"];//用戶登錄賬號付款後,這個payerid才有值
                if (string.IsNullOrEmpty(payerId))//還沒有登陸付款
                {
                    PaypalTradeWayPayServer pay = new PaypalTradeWayPayServer();
                    var approvalUrl = pay.payment(orderNo, Request, Session, apiContext);//發送給paypal的參數方法
                    if (!string.IsNullOrEmpty(approvalUrl))
                    {
                        return Redirect(approvalUrl);
                    }
                    else
                    {
                        return RedirectToAction("Error404", "MPublic", null);
                    }
                }
                else
                {
var guid = Request.Params["guid"];//登陸付款後才進入這裡 // Using the information from the redirect, setup the payment to execute. var paymentId = Session[guid] as string; var paymentExecution = new PaymentExecution() { payer_id = payerId }; var payment = new Payment() { id = paymentId }; // Execute the payment. var executedPayment = payment.Execute(apiContext, paymentExecution); ViewBag.result = "success"; } } catch (PayPal.PayPalException ex) { //插入錯誤日誌 } return View("PayResult"); }

payment方法:

具體參數請自行查看

/// <summary>
        /// 得到ItemList
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        public string payment(string orderNo, HttpRequest Request,HttpSessionStateBase Session, APIContext apiContext)
        {
            // ###Items
            // Items within a transaction.
            var order = Context.Data.Order.Where(x=>x.OrderNo== orderNo && x.Del==false &&x.PayType== Interface.Order.Eum.EumPayType.Paypal).ToEntity();
            var orderDetail = Context.Data.OrderDetail.Where(x => x.OrderNo == orderNo).ToSelectList(x => new { Num = x.Num.ToString(), SkuPrice = x.SkuPrice, SkuName = x.SkuName,UnitName=x.UnitName });
            if (order == null || orderDetail == null)
            {
                return "";
            }
            var items = new List<Item>();
            string myCurrency = ChangeCurrency(order.CurrencyCode.Trim());
            foreach (var detail in orderDetail)
            {
                var item = new Item { name = detail.SkuName, price = detail.SkuPrice.ToString(), quantity = detail.Num, currency=myCurrency,sku= detail.UnitName };
                items.Add(item);
            }
            var itemList = new ItemList() { items = items };
            var payer = new Payer() { payment_method = "paypal" };

            // ###Redirect URLS
            // These URLs will determine how the user is redirected from PayPal once they have either approved or canceled the payment.
            string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/WebPay/PaypalPayment?";//支付完成後返回的地址
            var guid = Convert.ToString((new Random()).Next(100000));
            var redirUrls = new RedirectUrls()
            {
                cancel_url = baseURI + "guid=" + guid,
                return_url = baseURI + "guid=" + guid
            };
            
            // ###Details
            // Let's you specify details of a payment amount.
            var details = new Details()
            {
                tax = "0.00",
                shipping = order.TotalFreight.Value.ToString(),
                subtotal = order.TotalAmount.Value.ToString()
            };

            // ###Amount
            // Let's you specify a payment amount.
            var amount = new Amount()
            {
                currency = myCurrency,
                total = (order.TotalAmount.Value + order.TotalFreight.Value).ToString(), // Total must be equal to sum of shipping, tax and subtotal.
                details = details
            };

            // ###Transaction
            // A transaction defines the contract of a
            // payment - what is the payment for and who
            // is fulfilling it. 
            var transactionList = new List<Transaction>();

            // The Payment creation API requires a list of
            // Transaction; add the created `Transaction`
            // to a List
            string address = Request.Url.Scheme + "://" + Request.Url.Authority;
            transactionList.Add(new Transaction()
            {
                description = "Transaction description.",
                amount = amount,
                item_list = itemList,
                 custom=order.OrderNo,//這個參數可以傳遞我們的需要的參數,這裡我傳的是訂單號
                  notify_url= address+"/WebPay/Receive"//接收Paypal的IPN消息地址,必須需要外網可以訪問
            });

            // ###Payment
            // A Payment Resource; create one using
            // the above types and intent as `sale` or `authorize`
            var payment = new Payment()
            {
                intent = "sale",
                payer = payer,
                transactions = transactionList,
                redirect_urls = redirUrls               
            };

            try
            {
                // Create a payment using a valid APIContext
                var createdPayment = payment.Create(apiContext);

                // Using the `links` provided by the `createdPayment` object, we can give the user the option to redirect to PayPal to approve the payment.
                var links = createdPayment.links.GetEnumerator();
                string approvalUrl = "";
                while (links.MoveNext())
                {
                    var link = links.Current;
                    if (link.rel.ToLower().Trim().Equals("approval_url"))
                    {
                        approvalUrl = link.href;
                    }
                }
                Session.Add(guid, createdPayment.id);
                Session.Add("orderNo", orderNo);
                return approvalUrl;
            }
            catch (PayPal.PayPalException ex)
            {
                //插入錯誤日誌

            }
            return "";
        }

到這裡支付請求就已經完成了,但修改訂單狀態和操作資料庫的語句我們寫到Paypal的IPN中執行

 private string myEmail = "[email protected]";
        /// <summary>
        ///接收Paypal的IPN消息
        /// </summary>
        /// <returns></returns>
       [HttpPost]
        public HttpStatusCodeResult Receive()
        {//Store the IPN received from PayPal
            LogRequest(Request);
            //Fire and forget verification task
            Task.Run(() => VerifyTask(Request));

            //Reply back a 200 code
            return new HttpStatusCodeResult(HttpStatusCode.OK);
        }
        /// <summary>
        /// 驗證是否是paypal發過來的消息
        /// </summary>
        /// <param name="ipnRequest"></param>

        private void VerifyTask(HttpRequest ipnRequest)
        {
            var verificationResponse = string.Empty;try
            {
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                var verificationRequest = (HttpWebRequest)WebRequest.Create("https://www.sandbox.paypal.com/cgi-bin/webscr");

                //Set values for the verification request
                verificationRequest.Method = "POST";
                verificationRequest.ContentType = "application/x-www-form-urlencoded";
                var param = Request.BinaryRead(ipnRequest.ContentLength);
                var strRequest = Encoding.ASCII.GetString(param);

                //Add cmd=_notify-validate to the payload
                strRequest = "cmd=_notify-validate&" + strRequest;
                verificationRequest.ContentLength = strRequest.Length;

                //Attach payload to the verification request
                var streamOut = new StreamWriter(verificationRequest.GetRequestStream(), Encoding.ASCII);
                streamOut.Write(strRequest);
                streamOut.Close();

                //Send the request to PayPal and get the response
                var streamIn = new StreamReader(verificationRequest.GetResponse().GetResponseStream());
                verificationResponse = streamIn.ReadToEnd();
                streamIn.Close();
                ProcessVerificationResponse(verificationResponse, ipnRequest);
            }
            catch (Exception exception)
            {//插入錯誤日誌
                ErrorLogPO errorLog = new ErrorLogPO();
                errorLog.KID = Guid.NewGuid();
                errorLog.ErrorMessage = exception.Message;
                errorLog.ErrorState = Interface.Offer.Eum.EumErrorLogType.Paypal;
                errorLog.OperaTime = DateTime.Now;
                errorLog.Del = false;
                OfferServer.ErrorLog.AddErrorLog(errorLog);
            }         
        }
        /// <summary>
        /// 記錄txn_id和狀態驗證重覆
        /// </summary>
        /// <param name="request"></param>
        private void LogRequest(HttpRequest request)
        {
            //交易狀態
            string payment_status = request.Form["payment_status"].ToString();//交易號
            string txn_id = request.Form["txn_id"].ToString();

            // Persist the request values into a database or temporary data store
            PaypalTradeWayPayServer pay = new PaypalTradeWayPayServer();
            pay.OneCreate(payment_status, txn_id);
        }
        /// <summary>
        /// 執行業務操作
        /// </summary>
        /// <param name="verificationResponse"></param>
        /// <param name="request"></param>
        private void ProcessVerificationResponse(string verificationResponse, HttpRequest request)
        {
            try
            {
                if (verificationResponse.Equals("VERIFIED"))
                {
                    // check that Payment_status=Completed
                    // check that Txn_id has not been previously processed
                    // check that Receiver_email is your Primary PayPal email
                    // check that Payment_amount/Payment_currency are correct
                    // process payment      
                    //NameValueCollection coll;
                    ////Load Form variables into NameValueCollection variable.
                    //coll = Request.Form;

                    //// Get names of all forms into a string array.
                    //String[] requestItem = coll.AllKeys;

                    //for (var i = 0; i < requestItem.Length; i++)
                    //{
                    //    WriteError(requestItem[i] + ":" + Request.Form[requestItem[i]]);
                    //}
                    //賣方郵箱
                    string receiver_email = request.Form["receiver_email"].ToString();
                    //交易狀態
                    string payment_status = request.Form["payment_status"].ToString();
                    //交易號
                    string txn_id = request.Form["txn_id"].ToString();
                    string mc_gross = request.Form["mc_gross"].ToString();//金額
                    string mc_currency = request.Form["mc_currency"].ToString();//貨幣                          
                    // DateTime Payment_date = Convert.ToDateTime(request.Form["payment_date"].ToString());//交易時間
                    DateTime Payment_date = DateTime.Now;
                    //訂單號
                    string custom = request.Form["custom"].ToString();if (payment_status == "Completed")
                    {
                        PaypalWayPayPO model = PayWayServer.PaypalWayPay.Find(x => x.Txn_id == txn_id.Trim());
                        var order = OrderServer.Order.Find(x => x.OrderNo == custom.Trim());
                        PaypalTradeWayPayServer pay = new PaypalTradeWayPayServer();
                        bool verity = model.Payment_status == payment_status && receiver_email == myEmail && (order.TotalAmount.Value + order.TotalFreight.Value).ToString() == mc_gross && pay.ChangeCurrency(order.CurrencyCode.Trim()) == mc_currency;if (verity)
                        {                         
                            pay.UpdatePaypalData(Payment_date, custom, txn_id, payment_status);
                        }
                    }
                }
                else if (verificationResponse.Equals("INVALID"))
                {
                    string custom1 = request.Form["custom"].ToString();
                    ErrorLogPO model = new ErrorLogPO();
                    model.KID = Guid.NewGuid();
                    model.ErrorState = EumErrorLogType.Paypal;
                    model.ErrorMessage = "Paypal支付訂單號為:" + custom1 + "狀態無效";
                    model.OperaTime = DateTime.Now;
                    model.Del = false;
                    OfferServer.ErrorLog.AddErrorLog(model);
                }
                else
                {
                    ErrorLogPO model = new ErrorLogPO();
                    model.KID = Guid.NewGuid();
                    model.ErrorState = EumErrorLogType.Paypal;
                    model.ErrorMessage = "Palpal請求失敗";
                    model.OperaTime = DateTime.Now;
                    model.Del = false;
                    OfferServer.ErrorLog.AddErrorLog(model);
                }
            }
            catch (Exception ex)
            {
                ErrorLogPO model = new ErrorLogPO();
                model.KID = Guid.NewGuid();
                model.ErrorState = EumErrorLogType.Paypal;
                model.ErrorMessage = ex.Message;
                model.OperaTime = DateTime.Now;
                model.Del = false;
                OfferServer.ErrorLog.AddErrorLog(model);
            }
        }

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 沒玩過linux,折騰了半天的ftp,好不容易親測通過了。不容易啊。 操作環境:vm虛擬機 centos7 首先:搞定網路問題;預設情況下使用ifconfig可以看到虛擬機下是無網路的。(註:虛擬機網路設置為NAT或橋接模式都是可以的) 輸入命令nmtui 打開網路配置 回車-》回車 將倒數第二項 ...
  • 最近部署上線的一個引擎,啟動之後記憶體、日誌顯示一切正常,但是外部無法進行引擎訪問。幾經周折,在同事的協助下,找出了問題:root用戶的open files為1024,引擎啟動時,1024個文件句柄已經用盡。在晚上看到一篇不錯的文章,就轉下來了:http://jameswxx.iteye.com/bl ...
  • VopSdk一個高逼格微信公眾號開發SDK(源碼下載) VopSdk一個高逼格微信公眾號開發SDK:自動化生產(裝逼模式開啟) 針對第一版,我們搞了第二版本,老規矩先定個目標。 一 我們的目標 a、移除PayExcute,統一執行入口,目前只保留一個入口Excute b、序列化特性統一,目前只用設置 ...
  • ORM概念: 指對象結構和資料庫架構間的映射,對象和資料庫架構有一定的映射關係,讓程式員可以不必編寫sql ...
  • 概述 之前聽說很多大神的成長之路,幾乎都有個習慣——寫博文,可以有效的對項目進行總結、從而提高開發的經驗。所以初學WPF的我想試試,順便提高一下小學作文的能力。O(∩_∩)O哈哈~ 讀萬卷書不如行萬里路,實踐是最好的導師!最近在學習WPF,也嘗試著做了一些小Demo,但並沒有真正的使用WPF的開發模 ...
  • 前言:在網頁上需要輸入時間的時候,我們可以用HTML5的inputl中的date類型。但是如下入所示,有些瀏覽器不支持。flatpickr這個小插件可以解決這個問題。 1.flatpickr日期時間選擇器插件的github地址為:https://chmln.github.io/flatpickr/。 ...
  • 首先添加log4net的引用,可以使用VS的Nuget下載 1.配置Web.config文件在configuration節點下配置configSections中的section 2.在configuration節點下添加log4net節點 後臺寫日誌時: 至此,就完成了 ...
  • 問題: 不能在此路徑中使用此配置節。如果在父級別上鎖定了該節,便會出現這種情況。鎖定是預設設置的(overrideModeDefault="Deny"),或者是通過包含 overrideMode="Deny" 或舊有的 allowOverride="false" 的位置標記明確設置的。原因:可能是在 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...