H5網站接入支付寶的支付介面

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

寫本文章的目的是為了記錄工作中遇到的問題,方便以後遇到可以迅速解決問題 H5手機網站接入支付寶的支付介面,推薦使用支付寶提供的SDK來快速開發 我使用的是SDK開發 引用命名空間 首頁需要定義一些常量 這裡的app_id,merchant_private_key,alipay_public_key ...


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

H5手機網站接入支付寶的支付介面,推薦使用支付寶提供的SDK來快速開發

我使用的是SDK開發

引用命名空間

using Aop.Api;
using Aop.Api.Request;
using Aop.Api.Response;
using Aop.Api.Util;

 

首頁需要定義一些常量

 static string serverUrl = "https://openapi.alipaydev.com/gateway.do";
        static string app_id = "**";   //開發者的應用ID
        static string format = "JSON";
        static string charset = "utf-8";
        static string sign_type = "RSA2";  //簽名格式
        static string version = "1.0";
        string UID = "2088102169707816";//賣家支付寶賬戶號
        //商戶私鑰
        static string merchant_private_key = "***";
        //支付寶公鑰
        static string alipay_public_key = "***";

這裡的app_id,merchant_private_key,alipay_public_key 我就沒有列出來了,獲取的方法需要自己去支付寶平臺完成一些操作進行獲取

在用戶點擊網站付款時,我們需要喚醒支付寶,來進行支付

public string H5RequestPayWay(OrderPO order)
        {
            IAopClient client = new DefaultAopClient(serverUrl, app_id, merchant_private_key, format, version, sign_type, alipay_public_key, charset, false);
            AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
            string address= "http://m." + PathLogic1.RootDomain;
            request.SetReturnUrl(address+ "/WebPay/AlipayPayResult");//同步請求
            request.SetNotifyUrl(address + "/WebPay/AsyncPay");//非同步請求
            var lstDetail = Context.Data.OrderDetail.Where(x => x.OrderNo == order.OrderNo).ToSelectList(x=>new { x.SkuName});
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < lstDetail.Count(); i++)
            {
                sb.Append(lstDetail[i].SkuName + ",");
            }
            request.BizContent = "{" +
    "\"body\":\""+sb.ToString().Substring(0,sb.Length-1)+"\"," +
    "\"subject\":\"袋鼠巴巴商品支付\"," +
    "\"out_trade_no\":\""+order.OrderNo+"\"," +
    "\"timeout_express\":\"90m\"," +
    "\"total_amount\":"+(order.TotalAmount.Value+order.TotalFreight.Value)+"," +
    "\"product_code\":\"QUICK_WAP_PAY\"" +
    "  }";

            AlipayTradeWapPayResponse response = client.pageExecute(request);
             return response.Body;
        }

具體發送給支付寶的參數,自行去查看

執行方法後,買家輸入自己的支付寶賬號密碼進行支付,支付成功的結果,支付寶會以post的方式非同步請求你的SetNotifyUrl的地址

這個SetNotifyUrl的地址必須要外網可以訪問,支付寶的請求才能進來

買家支付成功,商家修改訂單狀態和資料庫的操作,都在非同步請求中執行

同步請求

  public ActionResult AlipayPayResult()
        {
            ViewBag.result = "success";
            return View("PayResult");
        }

 

         /// <summary>
        /// 驗證通知數據的正確性
        /// </summary>
        /// <param name="out_trade_no"></param>
        /// <param name="total_amount"></param>
        /// <param name="seller_id"></param>
        /// <returns></returns>
private SortedDictionary<string, string> GetRequestPost() { int i = 0; SortedDictionary<string, string> sArray = new SortedDictionary<string, string>(); 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 (i = 0; i < requestItem.Length; i++) { sArray.Add(requestItem[i], Request.Form[requestItem[i]]); } return sArray; }
  /// <summary>
        /// 驗簽
        /// </summary>
        /// <param name="inputPara"></param>
        /// <returns></returns>
        public Boolean  Verify(SortedDictionary<string, string> inputPara)
        {
            Dictionary<string, string> sPara = new Dictionary<string, string>();       
            Boolean verifyResult = AlipaySignature.RSACheckV1(inputPara, alipay_public_key, charset,sign_type,false);
            return verifyResult;
        }

非同步請求:

 [HttpPost]
        public void AsyncPay()
        {
            SortedDictionary<string, string> sPara = GetRequestPost();//將post請求過來的參數傳化為SortedDictionary
            if (sPara.Count > 0)
            {
                AlipayTradeWayPayServer pay = new AlipayTradeWayPayServer();
                Boolean VerifyResult = pay.Verify(sPara);//驗簽if (VerifyResult)
                {
                    try
                    {
                         //商戶訂單號
                        string out_trade_no = Request.Form["out_trade_no"];
                        //支付寶交易號
                        string trade_no = Request.Form["trade_no"];
                        //支付金額
                        decimal total_amount = Request.Form["total_amount"].ConvertType(Decimal.Zero);
                        //實收金額
                        //decimal receipt_amount = Request.Form["receipt_amount"].ConvertType(Decimal.Zero);
                        //交易狀態
                        string trade_status = Request.Form["trade_status"];
                        //賣家支付寶賬號
                        string seller_id = Request.Form["seller_id"];

                        //商品描述
                        string body = Request.Form["body"];
                        //交易創建時間
                        DateTime gmt_create = DateTime.Parse(Request.Form["gmt_create"]);
                        //交易付款時間
                        DateTime gmt_payment = DateTime.Parse(Request.Form["gmt_payment"]);
                        string appid = Request.Form["app_id"];
                        WriteError("驗證參數開始");
                        Boolean DataValidity = pay.CheckInform(out_trade_no, total_amount, seller_id, appid);//商家判斷參數時候是否匹配if (DataValidity)
                        {
                            if (Request.Form["trade_status"] == "TRADE_FINISHED")
                            {
                                AlipayWayPayPO model = CreateAlipayWayPay(out_trade_no, trade_no, trade_status, gmt_create, gmt_payment);
                                pay.PaySuccess(out_trade_no, model, Server.MapPath("~/" + DateTime.Today.ToString("yyMMdd") + ".txt"));//修改訂單
                                //註意:
                                //退款日期超過可退款期限後(如三個月可退款),支付寶系統發送該交易狀態通知
                            }
                            else if (Request.Form["trade_status"] == "TRADE_SUCCESS")
                            {
                                AlipayWayPayPO model = CreateAlipayWayPay(out_trade_no, trade_no, trade_status, gmt_create, gmt_payment);
                                pay.PaySuccess(out_trade_no, model, Server.MapPath("~/" + DateTime.Today.ToString("yyMMdd") + ".txt"));//修改訂單
                                //註意:
                                //付款完成後,支付寶系統發送該交易狀態通知
                            }
                            else
                            {

                            }

                            //——請根據您的業務邏輯來編寫程式(以上代碼僅作參考)——

                            Response.Write("success");  //請不要修改或刪除

                            /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                        }
                    }
                    catch (Exception ex)
                    {
                       
                    }
                }
                else//驗證失敗
                {
                    Response.Write("fail");
                }
            }
            else
            {
                Response.Write("無通知參數");
            }
        }

 


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

-Advertisement-
Play Games
更多相關文章
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...