C#接入第三方支付一些小问题

13年第一次接入支付宝的时候,支付宝的api还不是很好用,费了些劲才完成,本月再次接入的时候发现已经很好用了,接入过程非常顺畅,只出现了一个小问题,我的金额默认是保留了4位小数,支付宝api只接受最多两位小数,开始的时候没注意,一直报参数错误。

在接入支付宝和微信支付的时候,都有一个需要,就是根据参数名进行排名拼接,为了方便,写了两个小方法来进行这一步:

支付宝:

public static string GetSignStr(SortedDictionary<string, string> sParaTemp)
{
List<string> NameList = sParaTemp.Keys.ToList();
NameList.Sort();
string Str = "";
try
{
foreach (var item in NameList)
{
if (string.IsNullOrEmpty(sParaTemp[item]))
continue;
if (Str != "")
Str += "&";
Str += item + "=" + sParaTemp[item];
}
}
catch (Exception)
{
}
return Str;
}

微信:

public static string GetSignStr(object param)
{
List<PropertyInfo> smList = param.GetType().GetProperties().ToList();
List<string> NameList = new List<string>();
foreach (var item in smList)
{
NameList.Add(item.Name);
}
NameList.Sort();
string Str = "";
try
{
foreach (var item in NameList)
{
PropertyInfo pInfo = smList.FirstOrDefault(p => p.Name == item);
if (pInfo == null)
continue;
object value = pInfo.GetValue(param, null);
if (value == null)
continue;
if (Str != "")
Str += "&";
Str += item + "=" + value;
}
}
catch (Exception)
{
}
return Str;
}

由于项目是pc网站,所以微信支付采用了扫码支付,需要把预支付生成的链接生成二维码图片,这里用了ThoughtWorks来进行,代码如下:

public static string GetQRCodeBmp(string link, string name)
{
string filepath = "";
try
{
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
qrCodeEncoder.QRCodeScale = 4;
qrCodeEncoder.QRCodeVersion = 0;
qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
Bitmap bmp = qrCodeEncoder.Encode(link);
string BasePath = System.Web.Hosting.HostingEnvironment.MapPath("~/");
string QRCodePath = "Files/QRCode/";
if (!Directory.Exists(BasePath + QRCodePath))
Directory.CreateDirectory(BasePath + QRCodePath);
filepath = BasePath + QRCodePath + name + ".jpg";
bmp.Save(filepath, ImageFormat.Jpeg);
return QRCodePath + name + ".jpg";
}
catch (Exception ex)
{
}
return filepath;
}

另外,微信支付的MD5加密需要UTF8格式(去年接入过微信支付,当时签名问题还有xml格式序列化问题调试了N次才通过,此次就用的现成的了):

public static string EncryptUTF8(string source)
{
string md5String = string.Empty;
try
{
byte[] byteCode = System.Text.Encoding.UTF8.GetBytes(source);
byteCode = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(byteCode);

for (int i = 0; i < byteCode.Length; i++)
{
md5String += byteCode[i].ToString("x").PadLeft(2, '0');
}
}
catch (Exception ex)
{

md5String = ex.ToString();
return md5String;
}
return md5String;
}

 支付宝支付,如果完全按照官方Demo改造,在subject包含中文时会出现IE上提交错误,这是因为IE的默认编码格式不是Demo统一的utf-8,解决办法就是在拼接提交的form表单时直接给外部加上html,head,body标签,并指定编码格式,这样就不会使用浏览器默认编码格式了:

/// <summary>
        /// 建立请求,以表单HTML形式构造(默认)
        /// </summary>
        /// <param name="sParaTemp">请求参数数组</param>
        /// <param name="strMethod">提交方式。两个值可选:post、get</param>
        /// <param name="strButtonValue">确认按钮显示文字</param>
        /// <returns>提交表单HTML文本</returns>
        public static string BuildRequest(SortedDictionary<string, string> sParaTemp, string strMethod, string strButtonValue)
        {
            //待请求参数数组
            Dictionary<string, string> dicPara = new Dictionary<string, string>();
            dicPara = BuildRequestPara(sParaTemp);

            StringBuilder sbHtml = new StringBuilder();
            sbHtml.Append("<html>");
            sbHtml.Append("<head>");
            sbHtml.Append("<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />");
            sbHtml.Append("</head>");
            sbHtml.Append("<body>");

            sbHtml.Append("<form id='alipaysubmit' name='alipaysubmit' action='" + GATEWAY_NEW + "_input_charset=" + _input_charset + "' method='" + strMethod.ToLower().Trim() + "'>");

            foreach (KeyValuePair<string, string> temp in dicPara)
            {
                sbHtml.Append("<input type='hidden' name='" + temp.Key + "' value='" + temp.Value + "'/>");
            }
            //submit按钮控件请不要含有name属性
            sbHtml.Append("<input type='submit' value='" + strButtonValue + "' style='display:none;'></form>");
            sbHtml.Append("<script>document.forms['alipaysubmit'].submit();</script>");

            sbHtml.Append("</body>");
            sbHtml.Append("</html>");
            return sbHtml.ToString();
        }

加粗部分就是在Demo基础上加的。

转载于:https://www.cnblogs.com/chimeile/p/Pay.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现第三方支付接口需要调用第三方支付平台的API,一般来说,第三方支付平台都会提供API文档和SDK来方便开发者使用。 具体实现步骤如下: 1. 注册第三方支付平台账号,并获取API密钥; 2. 根据API文档,调用第三方支付平台提供的API进行支付操作,包括生成订单、支付请求等; 3. 根据API文档,处理支付平台返回的支付结果,包括支付成功或失败等; 4. 对于支付成功的订单,更新本地系统中的订单状态,完成支付流程。 以下是一个简单的C#代码示例,使用支付宝的API进行支付操作: ```csharp using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Alipay.AopSdk.Core; using Alipay.AopSdk.Core.Request; using Alipay.AopSdk.Core.Response; public partial class Pay : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // 商户订单号 string out_trade_no = "20180901001001"; // 订单金额 string total_amount = "0.01"; // 商品描述 string subject = "test product"; // 支付宝网关地址 string serverUrl = "https://openapi.alipay.com/gateway.do"; // 应用ID string appId = "your_app_id"; // 支付宝公钥 string alipayPublicKey = "your_alipay_public_key"; // 商户私钥 string merchantPrivateKey = "your_merchant_private_key"; // 构造请求参数 IAopClient client = new DefaultAopClient(serverUrl, appId, merchantPrivateKey); AlipayTradePagePayRequest request = new AlipayTradePagePayRequest(); request.SetReturnUrl("your_return_url"); request.SetNotifyUrl("your_notify_url"); request.SetBizContent("{\"out_trade_no\":\"" + out_trade_no + "\"," + "\"total_amount\":\"" + total_amount + "\"," + "\"subject\":\"" + subject + "\"," + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}"); AlipayTradePagePayResponse response = client.SdkExecute(request); // 获取支付链接,跳转到支付页面 string form = response.Body; Response.Write(form); } } ``` 需要注意的是,不同的第三方支付平台API接口调用方式可能不同,具体实现方式需要根据API文档进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值