标签:
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格式:
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;
}
标签:
原文地址:http://www.cnblogs.com/chimeile/p/Pay.html