private string getSign(string key) { string sign = ""; System.Collections.Generic.SortedDictionary <string, string> dic = new SortedDictionary <string, string>(); dic.Add("app_id", app_id); dic.Add("method", method); dic.Add("charset", charset); dic.Add("sign_type", sign_type); dic.Add("timestamp", timestamp); dic.Add("version", version); dic.Add("biz_content", biz_content()); foreach (KeyValuePair <string, string> item in dic) { if (sign == "") { sign = sign + item.Key + "=" + item.Value; } else { sign = sign + "&" + item.Key + "=" + item.Value; } } sign = RSAFromPkcs8.sign(sign, key, "utf-8"); return(sign); }
/// <summary> /// 生成支付连接 /// </summary> /// <param name="sPara"></param> /// <returns></returns> private string BuildRequestSign(Dictionary <string, string> sPara) { //把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串 string prestr = Core.CreateLinkString(sPara); //把最终的字符串签名,获得签名结果 string mysign = ""; switch (_config.SignType) { case "MD5": mysign = AlipayMD5.Sign(prestr, _config.MD5SignKey, _config.InputCharset); break; case "RSA": mysign = RSAFromPkcs8.sign(prestr, _config.PrivateKey, _config.InputCharset); break; default: mysign = ""; break; } return(mysign); }
public ActionResult CreateOrder(Orders order) { order.Id = Guid.NewGuid().ToString().Replace("-", ""); order.CreateTime = DateTime.Now; if (!entities.NimUser.Any(o => o.Username == order.UserName)) { return(Json(new { code = 200, desc = "指定用户不存在", info = order })); } //order = new StudyOnline.Models.Orders(); //order.Id = "123456789"; //order.Amount = 0.01; //order.Main = "ChineseChat充值"; //order.Body = "ChineseChat充值1000学币"; String orderString = OrderUtil.getOrderInfo(order); String sign = RSAFromPkcs8.sign(orderString, Config.Private_key, Config.Input_charset); //原始订单字符串+URL编码的签名+签名类型 String lastOrderString = orderString + "&sign=\"" + HttpUtility.UrlEncode(sign, Encoding.UTF8) + "\"&sign_type=\"" + Config.Sign_type + "\""; entities.Orders.Add(order); entities.SaveChanges(); return(Json(new { code = 200, desc = "订单创建成功", info = new { order.Id, LastOrderString = lastOrderString } })); }
/// <summary> /// 将SortedDictionary中的键值拼接成一个大字符串,然后使用RSA生成签名 /// </summary> /// <param name="sd"></param> /// <param name="privatekey"></param> /// <returns></returns> public static string handleRSA(SortedDictionary <string, object> sd, string privatekey) { StringBuilder sbuffer = new StringBuilder(); foreach (KeyValuePair <string, object> item in sd) { sbuffer.Append(item.Value); } Console.WriteLine(sbuffer.ToString()); string sign = ""; sign = RSAFromPkcs8.sign(sbuffer.ToString(), privatekey, "UTF-8"); return(sign); }
/// <summary> /// 将SortedDictionary中的键值拼接成一个大字符串,然后使用RSA生成签名 /// </summary> /// <returns></returns> public static string handleRSA(SortedDictionary <string, object> sd, string privatekey, string type) { StringBuilder sbuffer = new StringBuilder(); foreach (KeyValuePair <string, object> item in sd) { sbuffer.Append(item.Value); } string sign = ""; //生成签名 sign = RSAFromPkcs8.sign(sbuffer.ToString(), privatekey, type); return(sign); }
/// <summary>创建当前配置的签名 /// </summary> private string BuildRequestMysign() { string mysign = ""; if (_config.SignType == "RSA") { mysign = RSAFromPkcs8.sign("", _config.PrivateKey, _config.InputCharset); } if (_config.SignType == "MD5") { mysign = AlipayMD5.Sign("", _config.Key, _config.InputCharset); } return(mysign); }
//支付提交 public ActionResult PayPost(Models.B2CInfo order) { //组装xml String xml = DataUtils.getXmlString(order); byte[] bytes = System.Text.Encoding.UTF8.GetBytes(xml); //转成 Base64 形式的 System.String string xmlData = Convert.ToBase64String(bytes); string tranCode = appSetting.postPayCode; //私钥 string privateKey = appSetting.privateKey; //公钥 string publicKey = appSetting.publicKey; string sign = RSAFromPkcs8.sign(xml, privateKey, "UTF-8"); string merchantId = order.merchantId; //发送数据拼接 string param = "xmlData=" + xmlData + "&tranCode=WGZF001" + "&reqOrdId=" + order.reqOrdId + "&signData=" + sign + "&merchantId=" + order.merchantId; string response = HttpClient.HttpPost(order.postUrl, param); B2C.Models.RecallObject recall = JsonHelper.JsonStringToObj <B2C.Models.RecallObject>(response); //返回数据签名验证后生成二维码 // string ec = recall.encryptData; string recallstring = DataUtils.DecodeBase64("utf-8", recall.encryptData); if (RSAFromPkcs8.verify(recallstring, recall.sign, publicKey, "UTF-8")) { string url = DataUtils.getValue(recallstring, "qrCode"); if (order.tranCode.Equals("01")) { //支付宝 // GenerateQRCode.GenerateQRByThoughtWorks(url, DataUtils.getValue(recallstring, "reqOrdId"), memoryAddress); } else { //微信 // GenerateQRCode.GenerateQRByThoughtWorks(url, DataUtils.getValue(recallstring, "reqOrdId"), memoryAddress); } } string result = Newtonsoft.Json.JsonConvert.SerializeObject(order); ViewData["merchant"] = order; return(View()); }
public Task <object> ExecuteAsync(string orderCode, decimal amount, string notifyUrl, string title = "", string description = "") { Task <object> task = new Task <object>(() => { //生成待签名字符串 var signString = Com.Alipay.Core.CreateLinkString(GetPayParams(orderCode, amount, notifyUrl, title, description), true); var orderInfo = GetPayParams(orderCode, amount, notifyUrl, title, description); var sign = RSAFromPkcs8.sign(signString, _config.PrivateKey, _config.InputCharset); var newSignEncode = UrlEncode(sign, Encoding.UTF8); orderInfo.Add("sign", newSignEncode);//签名 orderInfo.Add("sign_type", _config.SignType.ToUpper()); return(Com.Alipay.Core.CreateLinkString(orderInfo, true)); }); task.Start(); return(task); }
public static void testRSA() { /**RSA加密测试,RSA中的密钥对通过SSL工具生成,生成命令如下: * 1 生成RSA私钥: * openssl genrsa -out rsa_private_key.pem 1024 * 2 生成RSA公钥 * openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem * * 3 将RSA私钥转换成PKCS8格式 * openssl pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt -out rsa_pub_pk8.pem * * 直接打开rsa_public_key.pem(公钥)和rsa_pub_pk8.pem(私钥)文件就可以获取密钥对内容,获取密钥对内容组成字符串时,注意将换行符删除 * */ //string publickey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDzOqfNunFxFtCZPlq7fO/jWwjqmTvAooVBB4y87BizSZ9dl/F7FpAxYc6MmX2TqivCvvORXgdlYdFWAhzXOnIUv9OGG///WPLe9TMs9kIwAZ/APUXauvC01oFLnYkzwPlAh0tQ1Au9arTE/OG1V1dKgf8BXHLPhKL4BmGBEUZBtQIDAQAB"; //string privatekey = "MIICeQIBADANBgkqhkiG9w0BAQEFAASCAmMwggJfAgEAAoGBAPM6p826cXEW0Jk+Wrt87+NbCOqZO8CihUEHjLzsGLNJn12X8XsWkDFhzoyZfZOqK8K+85FeB2Vh0VYCHNc6chS/04Yb//9Y8t71Myz2QjABn8A9Rdq68LTWgUudiTPA+UCHS1DUC71qtMT84bVXV0qB/wFccs+EovgGYYERRkG1AgMBAAECgYEA2PmnPdgnYKnolfvQ9tXiLaBFGPpvGk4grz0r6FB5TF7N4rErwxECunq0xioaowK4HPc40qHd2SvkkWQ7FCjYIDsnMk1oOhxNKn0J3FG0n5Cg1/dFai4eoXHs/nKn3SVZ8YZC1T2cMtN2srectLqNqhB8aQEe8xmykyUlUpg/qmECQQD9vkwjUotG5oUUrOj6etcB4WcdyyH0FtThKgyoJUDwgBv6lGGzWyFJEREvp47IgV+FgC7zeP2mL4MhgnD3tNCZAkEA9WRrjOLBNc379XZpoDsH7rZjobVvhnTrEuRDx/whqZ+vk64EPrEW81XYh647bAbJlFn2jPhY+IUHkrxFEFT/fQJBAMoLNOULXQtfkqgb5odMONeue0Ul8itB4tBHgzyALW1TFPQ6InGGJsLfbCfd67uMCFts7fXAaXhibK/KBdm3iEECQQChwVAjzlUN4nnzk9qMhFz2PcPvFGovd2J9UXpcmRaXeWuDLXIe4Rz/ydaxmWgSDWdTIvoicpIzP31+fBwKZ/0BAkEAy0bh4weKmYF29//rK0sxmY8RtqkQeFrwWbqx1daa1w0DfWlNSvy47zyW1G5/AdZU6JSpXxlxdlM/HSDw+v7kcA=="; string publickey = Config.merchantPublickey; string privatekey = Config.merchantPrivatekey; //加密字符串 string data = "1234567890123456"; Console.WriteLine("加密前字符串内容:" + data); //加密 string encrypteddata = RSAFromPkcs8.encryptData(data, publickey, "UTF-8"); Console.WriteLine("加密后的字符串为:" + encrypteddata); Console.WriteLine("解密后的字符串内容:" + RSAFromPkcs8.decryptData(encrypteddata, privatekey, "UTF-8")); //签名 string signdata = "YB010000001441234567286038508081299"; Console.WriteLine("签名前的字符串内容:" + signdata); string sign = RSAFromPkcs8.sign(signdata, privatekey, "UTF-8"); Console.WriteLine("签名后的字符串:" + sign); Console.WriteLine("RSA算法测试结束"); Console.ReadLine(); }
public override void pay(string productID, string productName, float productPrice, string tradeNo, string userID, string notifyUrl, string callbackClass, string callbackMethod, TheBaseAccountDelegate.Function callback) { if ((Singleton <AccountManager> .Instance.accountConfig.paymentBranch != ConfigAccount.PaymentBranch.APPSTORE_CN) && (Singleton <AccountManager> .Instance.accountConfig.paymentBranch == ConfigAccount.PaymentBranch.ORIGINAL_ANDROID_PAY)) { if (Singleton <ChannelPayModule> .Instance.GetPayMethodId() == ChannelPayModule.PayMethod.ALIPAY) { string[] textArray1 = new string[] { "subject=", productID, "&out_trade_no=", tradeNo, "&uid=", userID }; string str = SecurityUtil.Md5(string.Concat(textArray1)) + userID; string str4 = (((string.Empty + "partner=\"" + ALIPAY_PARTNER + "\"") + "&out_trade_no=\"" + tradeNo + "\"") + "&subject=\"" + productID + "\"") + "&body=\"" + str + "\""; string content = (((((string.Concat(new object[] { str4, "&total_fee=\"", productPrice, "\"" }) + "¬ify_url=\"" + WWW.EscapeURL(notifyUrl) + "\"") + "&service=\"mobile.securitypay.pay\"" + "&_input_charset=\"utf-8\"") + "&return_url=\"" + WWW.EscapeURL("http://m.alipay.com") + "\"") + "&payment_type=\"1\"") + "&seller_id=\"" + ALIPAY_SELLER + "\"") + "&it_b_pay=\"1m\""; string s = RSAFromPkcs8.sign(content, ALIPAY_RSAPRIVATE, "utf-8"); content = content + "&sign=\"" + WWW.EscapeURL(s) + "\"&sign_type=\"RSA\""; object[] args = new object[] { content }; base._delegate.Call("pay", args); } else if (Singleton <ChannelPayModule> .Instance.GetPayMethodId() == ChannelPayModule.PayMethod.WEIXIN_PAY) { object[] objArray3 = new object[] { WEIXIN_PAY_APP_ID, this.weixinPrepayOrderInfo.partnerID, this.weixinPrepayOrderInfo.prepayID, WEIXIN_PAY_PACKAGE_VALUE, this.weixinPrepayOrderInfo.nonceStr, this.weixinPrepayOrderInfo.timestamp, this.weixinPrepayOrderInfo.sign }; this._delegate_weixin.Call("pay", objArray3); } } }
//提交查询 public ActionResult SearchPost(Models.B2CInfo order) { string result = Newtonsoft.Json.JsonConvert.SerializeObject(order); string xml = Utils.DataUtils.getSearchXml(order); byte[] bytes = System.Text.Encoding.UTF8.GetBytes(xml); //转成 Base64 形式的 System.String string xmlData = Convert.ToBase64String(bytes); string tranCode = "WGZF003"; //私钥 string privateKey = appSetting.privateKey; //公钥 string publicKey = appSetting.publicKey; //私钥签名 string sign = RSAFromPkcs8.sign(xml, privateKey, "UTF-8"); //发送数据拼接 string param = "xmlData=" + xmlData + "&tranCode=" + tranCode + "&reqOrdId=" + order.reqOrdId + "&signData=" + sign + "&merchantId=" + order.merchantId; string response = HttpClient.HttpPost(order.postUrl, param); ViewData["order"] = order; return(View()); }
/// <summary> /// 支付宝官方扫码H5通道 /// </summary> /// <param name="apptype">应用类型子id</param> /// <param name="code">订单编号</param> /// <param name="goodsname">商品名称</param> /// <param name="price">商品价格(单位元)</param> /// <param name="orderid">订单id</param> /// <param name="ip">ip地址</param> /// <param name="infoTime">查询接口信息缓存时间</param> /// <param name="appid">应用id</param> /// <returns></returns> private InnerResponse IAliPaySmH5(int apptype, string code, string goodsname, decimal price, int orderid, string ip, int appid, int infoTimes) { InnerResponse inn = new InnerResponse(); SelectInterface SeIn = new SelectInterface(); try { string ZfbSmH5jkhc = "ZfbSmH5jkhc" + appid;//组装缓存key值 SeIn = SelectUserInfo(ZfbSmH5jkhc, apptype, appid, infoTimes); if (SeIn == null || SeIn.PayId <= 0 || string.IsNullOrEmpty(SeIn.UserId) || string.IsNullOrEmpty(SeIn.UserKey)) { inn = inn.ToResponse(ErrorCode.Code106); return(inn); } if (!UpdateOrde.OrdeUpdateInfo(orderid, SeIn.PayId)) { inn = inn.ToResponse(ErrorCode.Code101); return(inn); } if (!JudgeMoney.JudgeMinimum(price, SeIn.minmun)) { inn = inn.ToResponse(ErrorCode.Code8990); return(inn); } if (!JudgeMoney.JudgeMaximum(price, SeIn.maximum)) { inn = inn.ToResponse(ErrorCode.Code8989); return(inn); } //公共请求参数 Dictionary <string, string> List = new Dictionary <string, string>(); List.Add("app_id", SeIn.UserId); //支付宝应用ID List.Add("method", "alipay.trade.precreate"); //接口名称(请求类型) List.Add("charset", "utf-8"); //请求使用的编码格式 List.Add("sign_type", "RSA"); //商户生成签名字符串所使用的签名算法类型,目前支持RSA2和RSA,推荐使用RSA2 List.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); //发送请求的时间 List.Add("version", "1.0"); //调用的接口版本 List.Add("notify_url", ConfigurationManager.AppSettings["TokenUrl"].ToString().Replace("{0}", SeIn.PayId.ToString())); //异步通知地址。 //请求参数 Dictionary <string, string> Orlist = new Dictionary <string, string>(); Orlist.Add("out_trade_no", code); //商户订单号 Orlist.Add("total_amount", price.ToString()); //订单总金额,单位为元,精确到小数点后两位, Orlist.Add("subject", goodsname); //订单标题 Orlist.Add("body", goodsname); //对交易或商品的描述 string overtime = (int.Parse(ConfigurationManager.AppSettings["overtime"].ToString()) / 60) + "m"; Orlist.Add("timeout_express", overtime); //该笔订单允许的最晚付款时间,逾期将关闭交易。 string biz_content = JsonHelper.DictJsonstr(Orlist); List.Add("biz_content", biz_content); string SignStr = UrlStr.AzGetStr(List); //签名 string Sign = RSAFromPkcs8.sign(SignStr, SeIn.UserKey, "utf-8"); //签名 注释:get请求时必须采用url编码方式(HttpUtility.UrlEncode) List.Add("sign", HttpUtility.UrlEncode(Sign)); //请求地址 string url = ConfigurationManager.AppSettings["AliPaySmUrl"].ToString(); string Urlstr = url + UrlStr.AzGetStr(List); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Urlstr); //创建一个请求示例 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //获取响应,即发送请求 Stream responseStream = response.GetResponseStream(); StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8); string srcString = streamReader.ReadToEnd(); Root root = new Root(); //对返回参数转换格式 root = JsonHelper.Deserializes <Root>(srcString); if (root != null && root.alipay_trade_precreate_response.code == "10000" && root.alipay_trade_precreate_response.msg == "Success") { string qurl = root.alipay_trade_precreate_response.qr_code + "," + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ",1"; //组装二维码地址 string ImgQRcode = ConfigurationManager.AppSettings["ImgQRcode"].ToString() + "?QRcode=" + Encrypt.IndexEncrypt(qurl); //二维码图片展示地址 string codeurl = ConfigurationManager.AppSettings["QRcode"].ToString() + "?QRcode=" + Encrypt.IndexEncrypt(qurl); //二维码展示地址 inn = inn.ToResponse(ErrorCode.Code100); inn.ExtraData = new { ImgQRcode = ImgQRcode, codeurl = codeurl }; //http提交方式; } else { string error = "支付宝官方扫码支付错误代码:" + srcString + ",商户号:" + SeIn.UserId; PayApiDetailErrorLogger.UpstreamPaymentErrorLog("报错信息:" + error, summary: "支付宝官方扫码支付接口错误信息", channelId: SeIn.PayId); inn = inn.ToResponse(ErrorCode.Code104); } } catch (Exception ex) { PayApiDetailErrorLogger.UpstreamPaymentErrorLog("报错信息:" + ex.ToString(), summary: "支付官方宝扫码接口错误信息", channelId: SeIn.PayId); inn = inn.ToResponse(ErrorCode.Code104); } return(inn); }