Home > Backend Development > C#.Net Tutorial > Example analysis of .NET Alipay App payment access

Example analysis of .NET Alipay App payment access

黄舟
Release: 2018-05-11 15:01:00
Original
3480 people have browsed it

1. Foreword

#                            I am so busy with new products that my blog is updated very slowly. In order to facilitate user payment, new products require Alipay to scan the QR code to access. The job fell to me. The product is a desktop software under Windows system, and the software generates QR code for payment. The interface is written in native MVVM. The basic process is described below. Veteran drivers who have done it can just click to close it.

##2. Application interface

            ## Applying for an interface is the first step , here are a few things first:

  1. ##The company has an Alipay account


  2. ##The company has business qualifications (nonsense)
  3. #Create an application, sign up for computer website payment, mobile payment, and App payment.
  4. #Create a private Key, public key, Alipay public key
  5. ##Configure gateway and callback address

  6. ##                         The following points should be noted:

When creating an application, the name should not contain the words "payment", "pay", etc. High-definition images are recommended


  1. When creating an application, contract payment requires some application materials, such as: Business qualification photos, 4 company photos, application introduction (name, download address, whether the application is available on the company website, and the interface style of Alipay payment appears in the application)

  2. After signing the contract, it needs to be reviewed, which takes about one day (Alibaba is really fast, Tencent WeChat takes 4 days ), if approved, an email will be sent with a link in it. Click the link to complete the signing

  3. ##Create private key, public key, and Alipay public key. There are official tools on the Alipay interface website. You can download and use them

  4. The gateway and callback address must be associated with the company website, such as a second-level domain name; if the gateway, callback address and The company website has no connection, so I’m afraid it won’t work.

#3. Code process

         ##There are three constituent elements. Client software, merchant server backend, Alipay backend

The client software clicks "Get payment QR code" to get a payable QR code:

Encapsulate some necessary information from the client and send it to the merchant server backend to form a merchant order #

        /// <summary>
        /// 获取二维码信息        /// </summary>
        /// <param name="packageClientInfo">封装信息</param>
        /// <param name="serverAddress">商户产品服务器地址</param>
        /// <returns></returns>
        public static void GetQRCodeInfo(string packageClientInfo, string serverAddress, Action<string> getQRCodeAction)
        {            if (!string.IsNullOrEmpty(packageClientInfo))
            {                try
                {
                    HttpClient httpsClient = new HttpClient
                    {
                        BaseAddress = new Uri(serverAddress),
                        Timeout = TimeSpan.FromMinutes(20)
                    };                    if (DsClientOperation.ConnectionTest(httpsClient))
                    {
                        StringContent strData = new StringContent(
                                                           packageClientInfo,
                                                           Encoding.UTF8,
                                                           RcCommonNames.JasonMediaType);                        
                                                           string PostUrl = httpsClient.BaseAddress + "api/AlipayForProduct/GetQRCodeString";
                        Uri address = new Uri(PostUrl);
                        Task<HttpResponseMessage> response = httpsClient.PostAsync(address, strData);
                        response.ContinueWith(
                            (postTask) =>
                            {                                
                            if (postTask.IsFaulted)
                                {                                    
                                throw postTask.Exception;
                                }
                                HttpResponseMessage postResponse = postTask.Result;
                                postResponse.EnsureSuccessStatusCode();                                
                                var result = postResponse.Content.ReadAsStringAsync().Result;
                                getQRCodeAction(JsonConvert.DeserializeObject<string>(result)); //注意这个委托                      
                                          return result;
                            });
                    }
                }                catch
                {                    // ignored                }
            }
        }
Copy after login
The delegate method here is used to generate a QR code. When you return some strings (result) from this "api/AlipayForProduct/GetQRCodeString", for example, the returned :

##                                                                                                Number)

Then use ThoughtWorks.QRCode.dll to generate the QR code

        /// <summary>
        /// 根据字符串得到相应的二维码        /// </summary>
        /// <param name="qrInfo"></param>
        /// <param name="productName"></param>
        /// <param name="version"></param>
        /// <returns></returns>
        public static Image CreateQRCodeImage(string qrInfo, string productName, string version)
        {            try
            {                if (!string.IsNullOrEmpty(qrInfo))
                {
                    QRCodeEncoder encoder = new QRCodeEncoder
                    {
                        QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE,
                        QRCodeScale = 4,
                        QRCodeVersion = 0,
                        QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M
                    };                    
                    //编码方式(注意:BYTE能支持中文,ALPHA_NUMERIC扫描出来的都是数字)                    
                    //大小(值越大生成的二维码图片像素越高)                    
                    //版本(注意:设置为0主要是防止编码的字符串太长时发生错误)                    
                    //错误效验、错误更正(有4个等级)
                    Image image = encoder.Encode(qrInfo, Encoding.GetEncoding("utf-8"));                    
                    string filename = $"{productName}_{version}.png";                    
                    var userLocalPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);                    
                    var docPath = Path.Combine(userLocalPath, @"YourProduct\QRCode");                    
                    if (!Directory.Exists(docPath))
                    {
                        Directory.CreateDirectory(docPath);
                    }                    string filepath = Path.Combine(docPath, filename); 
                    using (FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.Write))
                    {
                        image.Save(fs, System.Drawing.Imaging.ImageFormat.Png);
                        fs.Close();
                        image.Dispose();
                    }                    return image;
                }
            }            catch (Exception)
            {                return null;
            }            return null;
        }
Copy after login
QR code, to put it bluntly, changes the API of a service from a string to a picture. When the user uses the Alipay app to scan the QR code, the API will be requested:

        

"http://xxx.xxx.com/AlipayForProduct/SendInfoToAlipay?ordernumber=" + $"{orderNumber}"; (orderNumber is the merchant order number)

          orderNumber = Request[ (! matchedItem = db.OrderInfoForProduct.FirstOrDefault(x => x.OrderNumber == (matchedItem !=  && matchedItem.IsPaid == 
                     alipayServerURL =  app_id = privateKeyPem = format =  version =  signType = 
                     out_trade_no = orderNumber; 
                     product_code = ; 
                     total_amount = ;  
                     subject = ; 
                     body = ; =  returnurl = $ notifyurl == =  +                                      + body +  +                                      + subject +  +                                      + out_trade_no +  +                                      + total_amount +  +                                      + product_code +  +                                     
                    requestWap.SetReturnUrl(returnurl); = pNone =  + responseWap.Body +
Copy after login

异步请求一般需要做这么几件事:

  1. 用户扫码支付完之后,支付宝后台会把所有需要验证的信息发给你,除了一个参数不需要验签完,其余都需要验签;

  2. 如果验签成功且支付状态也是成功交易后,你需要更新商户服务器后台关于此条商户订单的状态,比如将其支付状态变成已支付,填充支付时间等等;

 
          <, > sPara = (sPara.Count > 
                 sign_type = Request.Form[
                 seller_id = Request.Form[]; 
                 trade_status = Request.Form[]; 
                 notify_time = Request.Form[]; 
                 app_id = Request.Form[]; 
                 out_trade_no = Request.Form[]; 
                 total_amount = Request.Form[]; 
                 receipt_amount = Request.Form[]; 
                 invoice_amount = Request.Form[]; 
                 buyer_pay_amount = Request.Form[]; 
                 body = Request.Form[]; 
                 gmt_payment = Request.Form[]; 

                 tradeGuid = 
                 isVerfied = AlipaySignature.RSACheckV1(sPara, alipayPublicKey, , sign_type,  (app_id == appID && seller_id == isTradeSuccess = .Equals(trade_status, ) || .Equals(trade_status,  (
Copy after login

同步请求一般需要做这么几件事:

1. 当异步调用完后,如果支付成功而且商户服务器后台对此条订单号处理也正确的话;同步请求可以再做一次验证

2. 如果验证成功,跳转支付成功页面;如果失败,跳转支付失败页面。

        public ActionResult AlipayResult()
        {
            SortedDictionary<string, string> sPara = GetRequestGet();            if (sPara.Count > 0)
            {                //非验签参数
                var sign_type = Request.QueryString["sign_type"];                //接收参数并排序
                var seller_id = Request.QueryString["seller_id"]; //卖家支付宝用户号
                var app_id = Request.QueryString["app_id"]; //开发者AppId
                var out_trade_no = Request.QueryString["out_trade_no"]; //交易订单号

                var orderNumberGuid = new Guid(out_trade_no);                try
                {                    var isVerfied = AlipaySignature.RSACheckV1(sPara, alipayPublicKey, "utf-8", sign_type, false);    
                                if (isVerfied)
                    {                        if (app_id == appID && seller_id == sellerID)
                        {
                           //你的支付成功页面
                        }
                    }

                }                catch
                {
                   //你的支付失败页面
                }
            }            else
            {               //你的支付失败页面
            }            return View();
        }        /// <summary>
        /// 参数排序字典        /// </summary>
        /// <returns></returns>
        private SortedDictionary<string, string> GetRequestGet()
        {
            SortedDictionary<string, string> sArray = new SortedDictionary<string, string>();
            NameValueCollection coll = Request.QueryString;

            String[] requestItem = coll.AllKeys;            foreach (string t in requestItem)
            {
                sArray.Add(t, Request.QueryString[t]);
            }            return sArray;
        }
Copy after login

 

The above is the detailed content of Example analysis of .NET Alipay App payment access. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template