支付宝香港对接

支付宝香港API对接,非常的简单,由于文档是跟对接人沟通的,我就不发出来了,先看看效果。

图一支付成功。

图二支付失败,原因15分钟不扫码就过期。重新在生成merchant_reference(唯一ID)

 

 

 

 上代码,如下

 internal class Hash256
    {
        //加密秘钥
        internal const string secret = "GUID,这里我就乱写了,用来加密的";
        internal string UrlEncode(string str)
        {
            StringBuilder builder = new StringBuilder();
            foreach (char c in str)
            {
                if (HttpUtility.UrlEncode(c.ToString()).Length > 1)
                {
                    builder.Append(HttpUtility.UrlEncode(c.ToString()).ToUpper());
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(c.ToString()))
                        builder.Append(HttpUtility.UrlEncode(c.ToString()).ToUpper());
                    else
                        builder.Append(c.ToString());
                }
            }
            return builder.ToString();
        }
        internal static string UrlEncode2(string str)
        {
            string urlStr = HttpUtility.UrlEncode(str);
            var urlCode = Regex.Matches(urlStr, "%[a-f0-9]{2}", RegexOptions.Compiled).Cast<Match>().Select(m => m.Value).Distinct();
            foreach (string item in urlCode)
            {
                urlStr = urlStr.Replace(item, item.ToUpper());
            }
            return urlStr;
        }
        internal static string GetSHA512HashFromString(string strData)
        {
            byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(strData);
            try
            {
                SHA512 sha512 = new SHA512CryptoServiceProvider();
                byte[] retVal = sha512.ComputeHash(bytValue);
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("GetSHA512HashFromString() fail,error:" + ex.Message);
            }
        }
    }

  后台代码如下。因为我们封装过了,所以我就发关键代码块了。

 

        public override void SendRequest()
        {
            var ip = HttpContext.Current.Request.UserHostAddress;
            var dic = new Dictionary<string, object>
            {
                ["merchant_reference"] = itemNumber,
                ["currency"] = CurryCode,//"HKD",
                ["amount"] = amount,
                ["customer_ip"] = ip,
                ["customer_first_name"] = "SOONNEST",
                ["customer_last_name"] = "Soonnest org",
                //["customer_address"] = "customer_address",
                ["customer_phone"] = "07551654445",
                ["customer_email"] = buyerEmail,
                //["customer_state"] = "NY",
                //["customer_country"] = "US",
                //["return_url"] = returnUrl.Replace(":9998", ""),
                ["network"] = "Alipay",
                ["subject"] = "支付捷訊商城商品訂單-" + itemNumber
            };
            var orderby = dic.OrderBy(x => x.Key).ToList();
            var str = "";
            StringBuilder stringBuilder = new StringBuilder();
            foreach (var item in orderby)
            {
                str += item.Key + "=" + Hash256.UrlEncode2(item.Value.ToString()) + "&";
                stringBuilder.Append(this.CreateField(item.Key, item.Value.ToString())); //唯一标识
            }
            
            stringBuilder.Append(this.CreateField("sign", Hash256.GetSHA512HashFromString(str.TrimEnd('&') + Hash256.secret)));
            this.SubmitPaymentForm(this.CreateForm(stringBuilder.ToString(), GatewayUrl));
        }

 

  文章中的CreateForm,SubmitPaymentForm,是生成表单以及提交表单的动作,比较简单,我就不写了。

 

private const string GatewayUrl = "https://gateway.pa-sys.com/0b743214-d242-4951-89fe-facc0d6c2561/payment/query";


public override void VerifyNotify(int timeout, string configXml) { var sb = new StringBuilder(); var keys = parameters.AllKeys.OrderBy(x => x); var searchSing = ""; foreach (var Key in keys) { if (!Key.Equals("sign")) sb.Append(Key + "=" + Hash256.UrlEncode2(parameters[Key].ToString().Trim()) + "&"); if (Key.Equals("merchant_reference")) searchSing = Key.Trim() + "=" + Hash256.UrlEncode2(parameters[Key].ToString().Trim()); } var sing = Hash256.GetSHA512HashFromString(sb.ToString().TrimEnd('&') + Hash256.secret); if (!sing.Equals(parameters["sign"])) { PayLog.writeLog_Collection(this.parameters, configXml, GatewayUrl, "AlipayWXHKD-加密签名失败", LogType.AlipayWXHKD); } ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(GatewayUrl); httpWebRequest.Method = "POST"; httpWebRequest.ContentType = "application/x-www-form-urlencoded"; string text = string.Format("merchant_reference={0}&sign={1}", parameters["merchant_reference"].Trim(), Hash256.GetSHA512HashFromString(searchSing + Hash256.secret)); httpWebRequest.ContentLength = text.Length; StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream(), Encoding.ASCII); streamWriter.Write(text); streamWriter.Close(); StreamReader streamReader = new StreamReader(httpWebRequest.GetResponse().GetResponseStream()); string resultJson = streamReader.ReadToEnd(); streamReader.Close(); PayLog.writeLog_Collection(this.parameters, configXml, GatewayUrl, $"香港支付宝处理返回结果集" + resultJson, LogType.AlipayWXHKD); var result = JsonHelper.ParseFormJson<List<Payment>>(resultJson); if (result!=null && result.Any() && result.FirstOrDefault().status=="1") { this.OnFinished(false); this.OnPayment(); } else { this.OnNotifyVerifyFaild(); } }

 

  文章中,OnFinished();OnPayment();OnNotifyVerifyFaild(); 做自己业务逻辑

如有遗漏,请评论区诶特,或加入群聊,新群人数较少,博主希望利用现有资源做一套快速开发框架,类似ABP。

 

posted @ 2020-01-08 16:51  颖子的踏坑路线  阅读(1499)  评论(0编辑  收藏  举报