主頁 > .NET開發 > Asp.net 微信H5喚起支付和支付回呼

Asp.net 微信H5喚起支付和支付回呼

2022-01-05 06:00:27 .NET開發

做任何商城類的專案都離不開支付這一環節,今天就記錄一下在開發微信H5支付時的開發程序

在開發到訂單這部分模塊的時候終于遇到了微信開發第二個難題,微信支付!

首先請閱讀 微信JSAPI支付檔案  和 微信統一下單API 了解場景和引數

微信支付需要有 微信公眾平臺 和 微信商戶平臺 賬號

 

在微信商戶平臺配置 API秘鑰

 

配置 JSAPI域名

 

配置完這些之后 開始寫 WechatHelper 所用到的類

 

目錄

 

Data 用來存放需要用到的引數

 public class WxPayData
    {
        public WxPayData()
        {

        }

        //采用排序的Dictionary的好處是方便對資料包進行簽名,不用再簽名之前再做一次排序
        private SortedDictionary<string, object> m_values = new SortedDictionary<string, object>();

        /**
        * 設定某個欄位的值
        * @param key 欄位名
         * @param value 欄位值
        */
        public void SetValue(string key, object value)
        {
            m_values[key] = value;
        }

        /**
        * 根據欄位名獲取某個欄位的值
        * @param key 欄位名
         * @return key對應的欄位值
        */
        public object GetValue(string key)
        {
            object o = null;
            m_values.TryGetValue(key, out o);
            return o;
        }

        /**
         * 判斷某個欄位是否已設定
         * @param key 欄位名
         * @return 若欄位key已被設定,則回傳true,否則回傳false
         */
        public bool IsSet(string key)
        {
            object o = null;
            m_values.TryGetValue(key, out o);
            if (null != o)
                return true;
            else
                return false;
        }

        /**
        * @將Dictionary轉成xml
        * @return 經轉換得到的xml串
        * @throws WxPayException
        **/
        public string ToXml()
        {
            //資料為空時不能轉化為xml格式
            if (0 == m_values.Count)
            {
                throw new WxPayException("WxPayData資料為空!");
            }

            string xml = "<xml>";
            foreach (KeyValuePair<string, object> pair in m_values)
            {
                //欄位值不能為null,會影響后續流程
                if (pair.Value =https://www.cnblogs.com/kangsir7/p/= null)
                {
                    throw new WxPayException("WxPayData內部含有值為null的欄位!");
                }

                if (pair.Value.GetType() == typeof(int))
                {
                    xml += "<" + pair.Key + ">" + pair.Value + "</" + pair.Key + ">";
                }
                else if (pair.Value.GetType() == typeof(string))
                {
                    xml += "<" + pair.Key + ">" + "<![CDATA[" + pair.Value + "]]></" + pair.Key + ">";
                }
                else//除了string和int型別不能含有其他資料型別
                {
                    throw new WxPayException("WxPayData欄位資料型別錯誤!");
                }
            }
            xml += "</xml>";
            return xml;
        }

        /**
        * @將xml轉為WxPayData物件并回傳物件內部的資料
        * @param string 待轉換的xml串
        * @return 經轉換得到的Dictionary
        * @throws WxPayException
        */
        public SortedDictionary<string, object> FromXml(string xml)
        {
            if (string.IsNullOrEmpty(xml))
            {
                throw new WxPayException("將空的xml串轉換為WxPayData不合法!");
            }

            XmlDocument xmlDoc = new Xml.XmlDocument_XxeFixed();
            xmlDoc.LoadXml(xml);
            XmlNode xmlNode = xmlDoc.FirstChild;//獲取到根節點<xml>
            XmlNodeList nodes = xmlNode.ChildNodes;
            foreach (XmlNode xn in nodes)
            {
                XmlElement xe = (XmlElement)xn;
                m_values[xe.Name] = xe.InnerText;//獲取xml的鍵值對到WxPayData內部的資料中
            }

            try
            {
                //2015-06-29 錯誤是沒有簽名
                if (m_values["return_code"].ToString() != "SUCCESS")
                {
                    return m_values;
                }
                CheckSign();//驗證簽名,不通過會拋例外
            }
            catch (WxPayException ex)
            {
                throw new WxPayException(ex.Message);
            }

            return m_values;
        }

        /**
        * @Dictionary格式轉化成url引數格式
        * @ return url格式串, 該串不包含sign欄位值
        */
        public string ToUrl()
        {
            string buff = "";
            foreach (KeyValuePair<string, object> pair in m_values)
            {
                if (pair.Value =https://www.cnblogs.com/kangsir7/p/= null)
                {
                    throw new WxPayException("WxPayData內部含有值為null的欄位!");
                }

                if (pair.Key != "sign" && pair.Value.ToString() != "")
                {
                    buff += pair.Key + "=" + pair.Value + "&";
                }
            }
            buff = buff.Trim('&');
            return buff;
        }


        /**
        * @Dictionary格式化成Json
         * @return json串資料
        */
        public string ToJson()
        {
          //  string jsonStr = JsonMapper.ToJson(m_values);
            return "";
        }

        /**
        * @values格式化成能在Web頁面上顯示的結果(因為web頁面上不能直接輸出xml格式的字串)
        */
        public string ToPrintStr()
        {
            string str = "";
            foreach (KeyValuePair<string, object> pair in m_values)
            {
                if (pair.Value =https://www.cnblogs.com/kangsir7/p/= null)
                {
                    throw new WxPayException("WxPayData內部含有值為null的欄位!");
                }

                str += string.Format("{0}={1}<br>", pair.Key, pair.Value.ToString());
            }
            return str;
        }

        /**
        * @生成簽名,詳見簽名生成演算法
        * @return 簽名, sign欄位不參加簽名
        */
        public string MakeSign()
        {
            //轉url格式
            string str = ToUrl();
            //在string后加入API KEY
            str += "&key=" + WechatConfig.Key;
            //MD5加密
            var md5 = MD5.Create();
            var bs = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
            var sb = new StringBuilder();
            foreach (byte b in bs)
            {
                sb.Append(b.ToString("x2"));
            }
            //所有字符轉為大寫
            return sb.ToString().ToUpper();
        }

        /**
        * 
        * 檢測簽名是否正確
        * 正確回傳true,錯誤拋例外
        */
        public bool CheckSign()
        {
            //如果沒有設定簽名,則跳過檢測
            if (!IsSet("sign"))
            {
                throw new WxPayException("WxPayData簽名存在但不合法!");
            }
            //如果設定了簽名但是簽名為空,則拋例外
            else if (GetValue("sign") == null || GetValue("sign").ToString() == "")
            {
                throw new WxPayException("WxPayData簽名存在但不合法!");
            }

            //獲取接收到的簽名
            string return_sign = GetValue("sign").ToString();

            //在本地計算新的簽名
            string cal_sign = MakeSign();

            if (cal_sign == return_sign)
            {
                return true;
            }

            throw new WxPayException("WxPayData簽名驗證錯誤!");
        }

        /**
        * @獲取Dictionary
        */
        public SortedDictionary<string, object> GetValues()
        {
            return m_values;
        }
    }

 

 Exception

 public class WxPayException : Exception
    {
        public WxPayException(string msg) : base(msg)
        {
        }
    }

 

HttpService

用于發送請求,訪問微信統一下單API 和 查詢訂單介面

public class HttpService
    {

        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }

        public static string Post(string xml, string url, bool isUseCert, int timeout)
        {
            GC.Collect();//垃圾回收,回收沒有正常關閉的http連接

            string result = "";//回傳結果

            HttpWebRequest request = null;
            HttpWebResponse response = null;
            Stream reqStream = null;

            try
            {
                //設定最大連接數
                ServicePointManager.DefaultConnectionLimit = 200;
                //設定https驗證方式
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback =
                            new RemoteCertificateValidationCallback(CheckValidationResult);
                }

                /***************************************************************
                * 下面設定HttpWebRequest的相關屬性
                * ************************************************************/
                request = (HttpWebRequest)WebRequest.Create(url);

                request.Method = "POST";
                request.Timeout = timeout * 1000;

                //設定代理服務器
                //WebProxy proxy = new WebProxy();                          //定義一個網關物件
                //proxy.Address = new Uri(WxPayConfig.PROXY_URL);              //網關服務器埠:埠
                //request.Proxy = proxy;

                //設定POST的資料型別和長度
                request.ContentType = "text/xml";
                byte[] data =https://www.cnblogs.com/kangsir7/p/ Encoding.UTF8.GetBytes(xml);
                request.ContentLength = data.Length;

                ////是否使用證書
                //if (isUseCert)
                //{
                //    string path = HttpContext.Current.Request.PhysicalApplicationPath;
                //    X509Certificate2 cert = new X509Certificate2(path + WxPayConfig.SSLCERT_PATH, WxPayConfig.SSLCERT_PASSWORD);
                //    request.ClientCertificates.Add(cert);
                //}

                //往服務器寫入資料
                reqStream = request.GetRequestStream();
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();

                //獲取服務端回傳
                response = (HttpWebResponse)request.GetResponse();

                //獲取服務端回傳資料
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                result = sr.ReadToEnd().Trim();
                sr.Close();
            }
            catch (System.Threading.ThreadAbortException e)
            {
                System.Threading.Thread.ResetAbort();
            }
            catch (WebException e)
            {
                throw new WxPayException(e.ToString());
            }
            catch (Exception e)
            {
                throw new WxPayException(e.ToString());
            }
            finally
            {
                //關閉連接和流
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
            }
            return result;
        }
    }

 

WechatConfig 微信支付統一下單所用到的引數 會讀取 /App_Data/xml/payment.xml 檔案里面的內容

appid:微信公眾平臺的開發者ID(AppID)

mchid:微信商戶平臺賬號

key:在微信商戶平臺設定的API密鑰

appsecret:在微信公眾平臺中設定的開發者密碼(AppSecret)

ip:終端IP

notify_url:微信支付異步回呼地址,在微信支付成功時會異步呼叫你的介面

gateway:微信支付統一下單API介面

queryorder:微信支付查詢訂單介面

sealed class WechatConfig
    {
        #region 欄位
        static string appid = string.Empty;
        static string mchid = string.Empty;
        static string key = string.Empty;
        static string appsecret = string.Empty;
        static string notify_url = string.Empty;
        static string gateway = string.Empty;
        static string queryorder = string.Empty;
        #endregion

        static WechatConfig()
        {
            XmlDocument xml = new Xml.XmlDocument_XxeFixed();
            xml.XmlResolver = null;
            xml.Load(HttpContext.Current.Server.MapPath("/App_Data/xml/payment.xml"));
            var root = xml.SelectSingleNode("paymentMethod").ChildNodes;
            foreach (XmlNode xn in root)
            {
                XmlElement xe = (XmlElement)xn;
                if (xe.GetAttribute("id") == "wechatpay")
                {
                    appid = xe.GetAttribute("appid");
                    mchid = xe.GetAttribute("mchid");
                    key = xe.GetAttribute("key");
                    appsecret = xe.GetAttribute("appsecret");
                    notify_url = xe.GetAttribute("notify_url");
                    gateway = xe.GetAttribute("gateway");
                    queryorder = xe.GetAttribute("queryorder");
                    break;
                }
            }
        }

        internal static string Gateway
        {
            get
            {
                return gateway;
            }
        }
        internal static string Appid
        {
            get
            {
                return appid;
            }
        }
        internal static string Mchid
        {
            get
            {
                return mchid;
            }
        }
        internal static string Appsecret
        {
            get
            {
                return appsecret;
            }
        }
        internal static string Key
        {
            get
            {
                return key;
            }
        }
        internal static string Queryorder
        {
            get
            {
                return queryorder;
            }
        }
        internal static string Notify_url
        {
            get
            {
                return notify_url;
            }
        }
    }

 

WechatHelper  

在業務處理層呼叫 根據不同場景傳入不同的引數,可用于一個專案多個支付場景

out_trade_no :商戶支付的訂單號由商戶自定義生成,僅支持使用字母、數字、中劃線-、下劃線_、豎線|、星號*這些英文半角字符的組合,請勿使用漢字或全角等特殊字符,微信支付要求商戶訂單號保持唯一性(建議根據當前系統時間加隨機序列來生成訂單號),重新發起一筆支付要使用原訂單號,避免重復支付;已支付過或已呼叫關單、撤銷的訂單號不能重新發起支付,

total_fee:訂單總金額,單位為分 這里在方法里對金額進行了處理 可直接傳實際金額

attach:附加資料,在查詢API和支付通知中原樣回傳,可作為自定義引數使用,用于區分不同的支付場景,在回呼中可以根據此來呼叫不同的方法

body:商品簡單描述

ip:終端ip

trade_type:交易型別 JSAPI -JSAPI支付  NATIVE -Native支付  APP -APP支付

openId:此引數為微信用戶在商戶對應appid下的唯一標識

 public sealed class WechatHelper
    {
        #region JSAPI Pay

        /// <summary>
        /// JSAPI Pay
        /// </summary>
        /// <param name="out_trade_no">訂單編號</param>
        /// <param name="total_fee">價格</param>
        /// <param name="attach">自定義引數,回呼回傳</param>
        /// <returns></returns>
        public static ResultModel JSApiPay(string out_trade_no, decimal total_fee, string openid, string ip, string attach = "", string body = "購買商品")
        {
            WxPayData result = Pay(out_trade_no, total_fee, attach, body, ip, "JSAPI", openid);
            string return_code = result.GetValue("return_code").ToString();//回傳狀態碼  SUCCESS/FAIL 
            string result_code = result.GetValue("result_code").ToString();//回傳狀態碼  SUCCESS/FAIL 
            if (return_code == "SUCCESS" && result_code == "SUCCESS")
            {
              //  string url = result.GetValue("prepay_id").ToString();//預付款訂單prepay_id
                ResultModel rm = new ResultModel();
                rm.appId = WechatConfig.Appid;
                rm.timeStamp = WxPayApi.GenerateTimeStamp();
                rm.nonceStr = result.GetValue("nonce_str").ToString();
                rm.package = "prepay_id=" + result.GetValue("prepay_id").ToString();
                //設定支付引數
                var paySignReqHandler = new RequestHandler(null);
                paySignReqHandler.SetParameter("appId", rm.appId);
                paySignReqHandler.SetParameter("timeStamp", rm.timeStamp);
                paySignReqHandler.SetParameter("nonceStr", rm.nonceStr);
                paySignReqHandler.SetParameter("package", rm.package);
                paySignReqHandler.SetParameter("signType", "MD5");
                var paySign = paySignReqHandler.CreateMd5Sign("key", WechatConfig.Key);
                rm.paySign = paySign;
                return rm;
            }
            return null;
        }

        #endregion

        public static WxPayData Pay(string out_trade_no, decimal total_fee, string attach, string body, string ip, string trade_type, string openId = "")
        {
            var paymoney = Convert.ToInt32(total_fee * 100);
            WxPayData data = new WxPayData();
            data.SetValue("body", body);//商品描述
            data.SetValue("attach", attach);//附加資料,回呼回傳
            data.SetValue("out_trade_no", out_trade_no);//訂單編號
            data.SetValue("total_fee", paymoney.ToString());//總金額
            data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));//交易起始時間
            data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));//交易結束時間
            data.SetValue("goods_tag", "");//商品標記,訂單優惠標記,使用代金券或立減優惠功能時需要的引數
            data.SetValue("trade_type", trade_type);//交易型別
            if (trade_type == "JSAPI")
            {
                data.SetValue("openid", openId);//openId
            }
            data.SetValue("product_id", out_trade_no);//商品ID
            return WxPayApi.UnifiedOrder(data, ip);//呼叫統一下單介面
        }
        public static WxPayData GetNotifyData(Stream InputStream)
        {
            //接收從微信后臺POST過來的資料
            Stream s = InputStream;
            int count = 0;
            byte[] buffer = new byte[1024];
            StringBuilder builder = new StringBuilder();
            while ((count = s.Read(buffer, 0, 1024)) > 0)
            {
                builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
            }
            s.Flush();
            s.Close();
            s.Dispose();
            //轉換資料格式并驗證簽名
            WxPayData data = https://www.cnblogs.com/kangsir7/p/new WxPayData();
            try
            {
                data.FromXml(builder.ToString());
            }
            catch (WxPayException ex)
            {
                //若簽名錯誤,則立即回傳結果給微信支付后臺
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", ex.Message);
            }
            return data;
        }

        //查詢訂單
        public static bool QueryOrder(string transaction_id)
        {
            WxPayData req = new WxPayData();
            req.SetValue("transaction_id", transaction_id);
            WxPayData res = WxPayApi.OrderQuery(req);
            if (res.GetValue("return_code").ToString() == "SUCCESS" &&
                res.GetValue("result_code").ToString() == "SUCCESS")
            {
                return true;
            }
            else
            {
                return false;
            }
        }

    }
    public class ResultModel
    {
        public string appId { get; set; }
        public string timeStamp { get; set; }
        public string nonceStr { get; set; }
        public string package { get; set; }
        public string paySign { get; set; }
    }

 

 

WxPayApi

在wechathelper中拿到業務引數之后到wxpayapi中加入固定引數

public class WxPayApi
    {

        /**
        * 
        * 統一下單
        * @param WxPaydata inputObj 提交給統一下單API的引數
        * @param int timeOut 超時時間
        * @throws WxPayException
        * @return 成功時回傳,其他拋例外
        */
        public static WxPayData UnifiedOrder(WxPayData inputObj,string ip, int timeOut = 6)
        {
            //檢測必填引數
            if (!inputObj.IsSet("out_trade_no"))
            {
                throw new WxPayException("缺少統一支付介面必填引數out_trade_no!");
            }
            else if (!inputObj.IsSet("body"))
            {
                throw new WxPayException("缺少統一支付介面必填引數body!");
            }
            else if (!inputObj.IsSet("total_fee"))
            {
                throw new WxPayException("缺少統一支付介面必填引數total_fee!");
            }
            else if (!inputObj.IsSet("trade_type"))
            {
                throw new WxPayException("缺少統一支付介面必填引數trade_type!");
            }
            //關聯引數
            if (inputObj.GetValue("trade_type").ToString() == "JSAPI" && !inputObj.IsSet("openid"))
            {
                throw new WxPayException("統一支付介面中,缺少必填引數openid!trade_type為JSAPI時,openid為必填引數!");
            }
            if (inputObj.GetValue("trade_type").ToString() == "NATIVE" && !inputObj.IsSet("product_id"))
            {
                throw new WxPayException("統一支付介面中,缺少必填引數product_id!trade_type為JSAPI時,product_id為必填引數!");
            }
            inputObj.SetValue("notify_url", WechatConfig.Notify_url);//異步通知url
            inputObj.SetValue("appid", WechatConfig.Appid);//公眾賬號ID
            inputObj.SetValue("mch_id", WechatConfig.Mchid);//商戶號
            inputObj.SetValue("spbill_create_ip", ip);//終端ip              
            inputObj.SetValue("nonce_str", GenerateNonceStr());//隨機字串
            //簽名
            inputObj.SetValue("sign", inputObj.MakeSign());
            string xml = inputObj.ToXml();
            string response = HttpService.Post(xml, WechatConfig.Gateway, false, timeOut);
            WxPayData result = new WxPayData();
            result.FromXml(response);

            //ReportCostTime(url, timeCost, result);//測速上報

            return result;
        }

        /**
        * 生成時間戳,標準北京時間,時區為東八區,自1970年1月1日 0點0分0秒以來的秒數
         * @return 時間戳
        */
        public static string GenerateTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }

        /**
        * 生成隨機串,隨機串包含字母或數字
        * @return 隨機串
        */
        public static string GenerateNonceStr()
        {
            return Guid.NewGuid().ToString().Replace("-", "");
        }

        /**
        *    
        * 查詢訂單
        * @param WxPayData inputObj 提交給查詢訂單API的引數
        * @param int timeOut 超時時間
        * @throws WxPayException
        * @return 成功時回傳訂單查詢結果,其他拋例外
        */
        public static WxPayData OrderQuery(WxPayData inputObj, int timeOut = 6)
        {
            string url = "https://api.mch.weixin.qq.com/pay/orderquery";
            inputObj.SetValue("appid", WechatConfig.Appid);//公眾賬號ID
            inputObj.SetValue("mch_id", WechatConfig.Mchid);//商戶號
            inputObj.SetValue("nonce_str",GenerateNonceStr());//隨機字串
            inputObj.SetValue("sign", inputObj.MakeSign());//簽名

            string xml = inputObj.ToXml();

            var start = DateTime.Now;

            string response = HttpService.Post(xml, url, false, timeOut);//呼叫HTTP通信介面提交資料
            var end = DateTime.Now;
            int timeCost = (int)((end - start).TotalMilliseconds);//獲得介面耗時

            //將xml格式的資料轉化為物件以回傳
            WxPayData result = new WxPayData();
            result.FromXml(response);

            // ReportCostTime(url, timeCost, result);//測速上報

            return result;
        }

        /***
    * 訂單查詢完整業務流程邏輯
    * @param transaction_id 微信訂單號(優先使用)
    * @param out_trade_no 商戶訂單號
    * @return 訂單查詢結果(xml格式)
    */
        public static WxPayData Run(string transaction_id, string out_trade_no)
        {

            WxPayData data = new WxPayData();
            if (!string.IsNullOrEmpty(transaction_id))//如果微信訂單號存在,則以微信訂單號為準
            {
                data.SetValue("transaction_id", transaction_id);
            }
            else//微信訂單號不存在,才根據商戶訂單號去查單
            {
                data.SetValue("out_trade_no", out_trade_no);
            }

            WxPayData result = OrderQuery(data);//提交訂單查詢請求給API,接識訓傳資料
            return result;
        }


    }

 

這樣一個完整的wechathelper類就搭建完成了

 

創建xml組態檔 payment.xml

<?xml version="1.0" encoding="utf-8" ?>
<paymentMethod>
  <info
  id="wechatpay"
  appid=""
  mchid=""
  key=""
  appsecret=""
  ip=""
  notify_url="http://xxx/pay/WechatNotify"
  gateway="https://api.mch.weixin.qq.com/pay/unifiedorder"
  queryorder="https://api.mch.weixin.qq.com/pay/orderquery" />
</paymentMethod>

 

在控制器中創建 WechatHelper 呼叫JSApiPay方法

public ActionResult PayView(){
            WechatHelper wechatPay = new WechatHelper();
                    var pay = wechatPay.JSApiPay(OrderNum, Price, WxOpenId, "ip", "5");
                    var jssdkUiPackage = JSSDKHelper.GetJsSdkUiPackage(APPID, SECRET), Request.Url.AbsoluteUri);
                    ViewBag.JssdkUiPackage = jssdkUiPackage;
                    ViewBag.uid = user.Id;
                    ViewBag.orderNum = order.OrderNum;
                    JsSdkUiPackage jup = jssdkUiPackage as JsSdkUiPackage;
                    return View(pay);
}

 

 

創建支付頁面

@{
    var jssdk = ViewBag.JssdkUiPackage as Senparc.Weixin.MP.Helpers.JsSdkUiPackage;
    var uid = ViewBag.uid;
    var ordernum = ViewBag.orderNum;
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>微信支付</title>
</head>
<body>
    <input type="hidden" id="appid" value="@Model.appId" />
    <input type="hidden" id="timestamp" value="@Model.timeStamp" />
    <input type="hidden" id="nonceStr" value="@Model.nonceStr" />
    <input type="hidden" id="signature" value="@Model.paySign" />
    <input type="hidden" id="wxpackage" value="@Model.package" />
    <input type="hidden" id="uid" value="@uid" />

    <input type="hidden" id="_timestamp" value="@jssdk.Timestamp" />
    <input type="hidden" id="_nonceStr" value="@jssdk.NonceStr" />
    <input type="hidden" id="_signature" value="@jssdk.Signature" />
    <input type="hidden" id="ordernum" value="@ordernum" />
    <input type="hidden" id="types" value="1" />

    <script src="~/scripts/plug/jquery-1.9.1.min.js"></script>
    <script src="~/scripts/plug/jweixin-1.2.0.js"></script>
    <script src="~/scripts/plug/wechatpay.js"></script>
</body>
</html>

 

wechatpay.js

var appid = $("#appid").val();
var timestamp = $("#timestamp").val();
var nonceStr = $("#nonceStr").val();
var signature = $("#signature").val();
var wxpackage = $("#wxpackage").val();
var uid = $("#uid").val();
var _timestamp = $("#_timestamp").val();
var _nonceStr = $("#_nonceStr").val();
var _signature = $("#_signature").val();

var types = $("#types").val();

wx.config({
    debug: false,
    appId: appid, // 公眾號的唯一標識
    timestamp: _timestamp, //生成簽名的時間戳
    nonceStr: _nonceStr, // 生成簽名的隨機串
    signature: _signature,// 簽名
    jsApiList: ['chooseWXPay', 'translateVoice']
});

wx.ready(function () {
    wx.chooseWXPay({
        timestamp: timestamp,
        nonceStr: nonceStr,
        package: wxpackage,
        signType: 'MD5',
        paySign: signature,
        success: function (res) {
            if (res.errMsg == "chooseWXPay:ok") {
                window.location.href = "/pay/Pay_Success";
            } else {
                window.location.href = "/pay/Pay_Error";
            }
        },
        fail: function (res) {
            window.location.href = "/pay/Pay_Error";
        },
        cancel: function (res) {
            window.location.href = "/pay/Pay_Error";
        }
    });
});

 

微信支付異步回呼

這里就是支付成功之后微信異步回呼的介面方法

引數可以參考 微信API檔案  支付結果通知 

 #region 微信支付異步回呼

        [HttpPost]
        [Transaction]
        public ActionResult WechatNotify()
        {
            try
            {
                WechatHelper wechatPay = new WechatHelper();
                WxPayData notifyData = wechatPay.GetNotifyData(Request.InputStream);
                string attach = notifyData.GetValue("attach").ToString();string transaction_id = notifyData.GetValue("transaction_id").ToString();
                if (!notifyData.IsSet("transaction_id"))
                {
                    log("回呼return_msg=支付結果中微信訂單號不存在", "wechatpayer");
                }
                if (!wechatPay.QueryOrder(transaction_id))
                {
                    log("回呼return_msg=訂單查詢失敗", "wechatpayer");
                }
                else
                {
                    log("回呼return_msg=OK", "wechatpayer");
                }
                var payxml = XDocument.Parse(notifyData.ToXml());
                if (payxml.Element("xml").Element("return_code").Value =https://www.cnblogs.com/kangsir7/p/= "SUCCESS")
                {
                    if (payxml.Element("xml").Element("result_code").Value =https://www.cnblogs.com/kangsir7/p/= "SUCCESS")
                    {
                        string out_trade_no = payxml.Element("xml").Element("out_trade_no").Value;
                    }
                    return Content("<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[交易失敗]]></return_msg></xml>");
                }
                return Content("<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[交易失敗]]></return_msg></xml>");
            }
            catch (Exception ex)
            {
                log(ex.ToString(), "wechatpayer");
                return Content("<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[交易失敗]]></return_msg></xml>");
            }
        }


        #endregion

 

這樣就完成了在微信H5中喚起微信支付 并且通過異步回呼 完成一些業務

邊記錄邊學習 歡迎各位一起探討

 

本文來自博客園,作者:康Sir7,轉載請注明原文鏈接:https://www.cnblogs.com/kangsir7/p/15762942.html

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/403476.html

標籤:ASP.NET

上一篇:如何制作將在javaSwing中創建其他按鈕的JButton?

下一篇:基于歐姆龍PLC#FinsTcp協議上位機通訊(一)-PLC配置

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • WebAPI簡介

    Web體系結構: 有三個核心:資源(resource),URL(統一資源識別符號)和表示 他們的關系是這樣的:一個資源由一個URL進行標識,HTTP客戶端使用URL定位資源,表示是從資源回傳資料,媒體型別是資源回傳的資料格式。 接下來我們說下HTTP. HTTP協議的系統是一種無狀態的方式,使用請求/ ......

    uj5u.com 2020-09-09 22:07:47 more
  • asp.net core 3.1 入口:Program.cs中的Main函式

    本文分析Program.cs 中Main()函式中代碼的運行順序分析asp.net core程式的啟動,重點不是剖析原始碼,而是理清程式開始時執行的順序。到呼叫了哪些實體,哪些法方。asp.net core 3.1 的程式入口在專案Program.cs檔案里,如下。ususing System; us ......

    uj5u.com 2020-09-09 22:07:49 more
  • asp.net網站作為websocket服務端的應用該如何寫

    最近被websocket的一個問題困擾了很久,有一個需求是在web網站中搭建websocket服務。客戶端通過網頁與服務器建立連接,然后服務器根據ip給客戶端網頁發送資訊。 其實,這個需求并不難,只是剛開始對websocket的內容不太了解。上網搜索了一下,有通過asp.net core 實作的、有 ......

    uj5u.com 2020-09-09 22:08:02 more
  • ASP.NET 開源匯入匯出庫Magicodes.IE Docker中使用

    Magicodes.IE在Docker中使用 更新歷史 2019.02.13 【Nuget】版本更新到2.0.2 【匯入】修復單列匯入的Bug,單元測驗“OneColumnImporter_Test”。問題見(https://github.com/dotnetcore/Magicodes.IE/is ......

    uj5u.com 2020-09-09 22:08:05 more
  • 在webform中使用ajax

    如果你用過Asp.net webform, 說明你也算是.NET 開發的老兵了。WEBform應該是2011 2013左右,當時還用visual studio 2005、 visual studio 2008。后來基本都用的是MVC。 如果是新開發的專案,估計沒人會用webform技術。但是有些舊版 ......

    uj5u.com 2020-09-09 22:08:50 more
  • iis添加asp.net網站,訪問提示:由于擴展配置問題而無法提供您請求的

    今天在iis服務器配置asp.net網站,遇到一個問題,記錄一下: 問題:由于擴展配置問題而無法提供您請求的頁面。如果該頁面是腳本,請添加處理程式。如果應下載檔案,請添加 MIME 映射。 WindowServer2012服務器,添加角色安裝完.netframework和iis之后,運行aspx頁面 ......

    uj5u.com 2020-09-09 22:10:00 more
  • WebAPI-處理架構

    帶著問題去思考,大家好! 問題1:HTTP請求和回傳相應的HTTP回應資訊之間發生了什么? 1:首先是最底層,托管層,位于WebAPI和底層HTTP堆疊之間 2:其次是 訊息處理程式管道層,這里比如日志和快取。OWIN的參考是將訊息處理程式管道的一些功能下移到堆疊下端的OWIN中間件了。 3:控制器處理 ......

    uj5u.com 2020-09-09 22:11:13 more
  • 微信門戶開發框架-使用指導說明書

    微信門戶應用管理系統,采用基于 MVC + Bootstrap + Ajax + Enterprise Library的技術路線,界面層采用Boostrap + Metronic組合的前端框架,資料訪問層支持Oracle、SQLServer、MySQL、PostgreSQL等資料庫。框架以MVC5,... ......

    uj5u.com 2020-09-09 22:15:18 more
  • WebAPI-HTTP編程模型

    帶著問題去思考,大家好!它是什么?它包含什么?它能干什么? 訊息 HTTP編程模型的核心就是訊息抽象,表示為:HttPRequestMessage,HttpResponseMessage.用于客戶端和服務端之間交換請求和回應訊息。 HttpMethod類包含了一組靜態屬性: private stat ......

    uj5u.com 2020-09-09 22:15:23 more
  • 部署WebApi隨筆

    一、跨域 NuGet參考Microsoft.AspNet.WebApi.Cors WebApiConfig.cs中配置: // Web API 配置和服務 config.EnableCors(new EnableCorsAttribute("*", "*", "*")); 二、清除默認回傳XML格式 ......

    uj5u.com 2020-09-09 22:15:48 more
最新发布
  • C#多執行緒學習(二) 如何操縱一個執行緒

    <a href="https://www.cnblogs.com/x-zhi/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2943582/20220801082530.png" alt="" /></...

    uj5u.com 2023-04-19 09:17:20 more
  • C#多執行緒學習(二) 如何操縱一個執行緒

    C#多執行緒學習(二) 如何操縱一個執行緒 執行緒學習第一篇:C#多執行緒學習(一) 多執行緒的相關概念 下面我們就動手來創建一個執行緒,使用Thread類創建執行緒時,只需提供執行緒入口即可。(執行緒入口使程式知道該讓這個執行緒干什么事) 在C#中,執行緒入口是通過ThreadStart代理(delegate)來提供的 ......

    uj5u.com 2023-04-19 09:16:49 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    <a href="https://www.cnblogs.com/huangxincheng/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/214741/20200614104537.png" alt="" /&g...

    uj5u.com 2023-04-18 08:39:04 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    一:背景 1. 講故事 前段時間協助訓練營里的一位朋友分析了一個程式卡死的問題,回過頭來看這個案例比較經典,這篇稍微整理一下供后來者少踩坑吧。 二:WinDbg 分析 1. 為什么會卡死 因為是表單程式,理所當然就是看主執行緒此時正在做什么? 可以用 ~0s ; k 看一下便知。 0:000> k # ......

    uj5u.com 2023-04-18 08:33:10 more
  • SignalR, No Connection with that ID,IIS

    <a href="https://www.cnblogs.com/smartstar/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/u36196.jpg" alt="" /></a>...

    uj5u.com 2023-03-30 17:21:52 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:15:33 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:13:31 more
  • C#遍歷指定檔案夾中所有檔案的3種方法

    <a href="https://www.cnblogs.com/xbhp/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/957602/20230310105611.png" alt="" /></a&...

    uj5u.com 2023-03-27 14:46:55 more
  • C#/VB.NET:如何將PDF轉為PDF/A

    <a href="https://www.cnblogs.com/Carina-baby/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2859233/20220427162558.png" alt="" />...

    uj5u.com 2023-03-27 14:46:35 more
  • 武裝你的WEBAPI-OData聚合查詢

    <a href="https://www.cnblogs.com/podolski/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/616093/20140323000327.png" alt="" /><...

    uj5u.com 2023-03-27 14:46:16 more