Exemplo n.º 1
0
        /// <summary>
        /// 获取返回时的签名验证结果
        /// </summary>
        /// <param name="inputPara">通知返回参数数组</param>
        /// <param name="sign">对比的签名结果</param>
        /// <returns>签名验证结果</returns>
        private bool GetSignVeryfy(SortedDictionary <string, string> inputPara, string sign)
        {
            Dictionary <string, string> sPara = new Dictionary <string, string>();

            //过滤空值、sign与sign_type参数
            sPara = core.FilterPara(inputPara);

            //获取待签名字符串
            string preSignStr = core.CreateLinkString(sPara);

            //获得签名验证结果
            bool isSgin = false;

            if (sign != null && sign != "")
            {
                switch (_sign_type)
                {
                case "RSA":
                    isSgin = RSAFromPkcs8.verify(preSignStr, sign, alipay_public_key, _input_charset);
                    break;

                default:
                    break;
                }
            }

            return(isSgin);
        }
Exemplo n.º 2
0
    /// <summary>
    /// 将一键支付清算接口返回的结果进行解析,支付结果回调解析一样可以调用该方法
    /// </summary>
    /// <param name="ybResult">易宝支付返回的结果</param>
    /// <returns></returns>
    public static string checkYbClearResult(String ybResult)
    {
        if (ybResult.IndexOf("data") >= 0)
        {
            //将支付结果json字符串反序列化为对象
            RespondJson respJson      = Newtonsoft.Json.JsonConvert.DeserializeObject <RespondJson>(ybResult);
            string      yb_encryptkey = respJson.encryptkey;
            string      yb_data       = respJson.data;
            //将易宝返回的结果进行验签名
            bool passSign = EncryptUtil.checkDecryptAndSign(yb_data, yb_encryptkey, yibaoPublickey, merchantPrivatekey);
            if (passSign)
            {
                string yb_aeskey = RSAFromPkcs8.decryptData(yb_encryptkey, merchantPrivatekey, "UTF-8");

                string payresult_view = AES.Decrypt(yb_data, yb_aeskey);
                return(payresult_view);
            }
            else
            {
                return("验签未通过");
            }
        }
        else
        {
            return(ybResult);
        }
    }
Exemplo n.º 3
0
        /// <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);
        }
Exemplo n.º 4
0
        /// <summary>
        /// 将请求接口中的业务明文参数加密并请求一键支付接口,单不对返回的数据进行解密,用于获取清算对账单接口--商户通用接口
        /// </summary>
        /// <param name="sd"></param>
        /// <param name="apiUri"></param>
        /// <returns></returns>
        private string createMerchantDataAndRequestYb2(SortedDictionary <string, object> sd, string apiUri, bool ispost)
        {
            //随机生成商户AESkey
            string merchantAesKey = AES.GenerateAESKey();

            //生成RSA签名
            string sign = EncryptUtil.handleRSA(sd, merchantPrivatekey);

            sd.Add("sign", sign);


            //将对象转换为json字符串
            string bpinfo_json = Newtonsoft.Json.JsonConvert.SerializeObject(sd);
            string datastring  = AES.Encrypt(bpinfo_json, merchantAesKey);

            //将商户merchantAesKey用RSA算法加密
            string encryptkey = RSAFromPkcs8.encryptData(merchantAesKey, yibaoPublickey, "UTF-8");

            String ybResult = "";

            if (ispost)
            {
                ybResult = YJPayUtil.payAPIRequest(apimercahntprefix + apiUri, datastring, encryptkey, true);
            }
            else
            {
                ybResult = YJPayUtil.payAPIRequest(apimercahntprefix + apiUri, datastring, encryptkey, false);
            }

            return(YJPayUtil.checkYbClearResult(ybResult));
        }
Exemplo n.º 5
0
        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);
        }
Exemplo n.º 6
0
        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 } }));
        }
Exemplo n.º 7
0
        protected override void SetSign()
        {
            var sortTempdic = new SortedDictionary <string, string>(Paras);
            var tempdic     = AliPayFunction.FilterPara(sortTempdic);
            var prestr      = AliPayFunction.CreateLinkString(tempdic);

            Log.Loggers.Debug(new Log.DebugLogInfo()
            {
                Message = "Sign字符串:" + prestr
            });
            switch (SignType)
            {
            case "MD5":
                Sign = AlipayMD5.Sign(prestr, Channel.MD5Key, InputCharset);
                break;

            case "RSA":
                Sign = RSAFromPkcs8.Sign(prestr, Channel.RSA_PrivateKey, InputCharset);
                break;

            case "0001":
                Sign = RSAFromPkcs8.Sign(prestr, Channel.RSA_PrivateKey, InputCharset);
                break;

            default:
                throw new Exception("未知的加密方式:" + SignType);
            }
            this.SignType = "MD5";
        }
Exemplo n.º 8
0
    /// <summary>
    /// 字符串RSA公钥加密
    /// </summary>
    /// <param name="data"></param>
    /// <param name="privatekey"></param>
    /// <param name="type"></param>
    /// <returns></returns>
    public static string handleRSA(string data, string publicKey, string type)
    {
        string sign = "";

        //生成签名
        sign = RSAFromPkcs8.encryptData(data.ToString(), publicKey, type);
        return(sign);
    }
Exemplo n.º 9
0
    /// <summary>
    /// 对一键支付返回的业务数据进行验签
    /// </summary>
    /// <param name="data"></param>
    /// <param name="encrypt_key"></param>
    /// <param name="yibaoPublickKey"></param>
    /// <param name="merchantPrivateKey"></param>
    /// <returns></returns>
    public static bool checkDecryptAndSign(string data, string encrypt_key,
                                           string yibaoPublickKey, string merchantPrivateKey)
    {
        /** 1.使用YBprivatekey解开aesEncrypt。 */
        string AESKey = "";

        try
        {
            AESKey = RSAFromPkcs8.decryptData(encrypt_key, merchantPrivateKey, "UTF-8");
        }
        catch (Exception e)
        {
            /** AES密钥解密失败 */
            return(false);
        }

        /** 2.用aeskey解开data。取得data明文 */
        string realData = AES.Decrypt(data, AESKey);


        SortedDictionary <string, object> sd = Newtonsoft.Json.JsonConvert.DeserializeObject <SortedDictionary <string, object> >(realData);


        /** 3.取得data明文sign。 */
        string sign = (string)sd["sign"];

        /** 4.对map中的值进行验证 */
        StringBuilder signData = new StringBuilder();

        foreach (var item in sd)
        {
            /** 把sign参数隔过去 */
            if (item.Key == "sign")
            {
                continue;
            }
            signData.Append(item.Value);
        }

        signData = signData.Replace("\r", "");
        signData = signData.Replace("\n", "");
        signData = signData.Replace("    ", "");
        signData = signData.Replace("  ", "");
        signData = signData.Replace("\": \"", "\":\"");
        signData = signData.Replace("\": ", "\":");

        /**5. result为true时表明验签通过 */
        bool result = RSAFromPkcs8.checkSign(Convert.ToString(signData), sign,
                                             yibaoPublickKey, "UTF-8");

        return(result);
    }
Exemplo n.º 10
0
    /// <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);
    }
Exemplo n.º 11
0
    /// <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);
    }
Exemplo n.º 12
0
        /// <summary>
        /// 易宝支付
        /// </summary>
        /// <returns></returns>
        public string YBPaySendRequesWriter(YBRequestPara para, bool isMobile)
        {
            SortedDictionary <string, object> sd = new SortedDictionary <string, object>();

            sd.Add("merchantaccount", Config.merchantAccount);
            sd.Add("amount", para.amount);
            sd.Add("currency", 156);
            sd.Add("identityid", "user_" + para.userId.DESDecrypt());
            sd.Add("identitytype", 2);
            sd.Add("orderid", para.orderid);
            sd.Add("orderexpdate", 60);
            sd.Add("productcatalog", "48");
            sd.Add("productdesc", "速库美味商品");
            sd.Add("productname", "速库美味商品");
            //DateTime t1 = DateTime.Now;
            //DateTime t2 = new DateTime(1970, 1, 1);
            //double t = t1.Subtract(t2).TotalSeconds;
            //int transtime = (int)t;

            sd.Add("transtime", para.orderTime.DateTimeConvertTimeStamp().ParseInt());
            sd.Add("userip", "255.255.255.255");
            sd.Add("terminaltype", 3);
            sd.Add("terminalid", "nothing");
            sd.Add("callbackurl", APIURLConfig.callbackUrl);
            sd.Add("fcallbackurl", isMobile ? APIURLConfig.fcallbackUrl_Mobile : APIURLConfig.fcallbackUrl);
            sd.Add("userua", "");
            sd.Add("paytypes", "1|2");
            //生成RSA签名
            string sign = EncryptUtil.handleRSA(sd, Config.merchantPrivatekey);

            sd.Add("sign", sign);
            //将网页支付对象转换为json字符串
            string merchantAesKey = APIURLConfig.merchantAesKey;

            string wpinfo_json = Newtonsoft.Json.JsonConvert.SerializeObject(sd);
            string datastring  = AES.Encrypt(wpinfo_json, merchantAesKey);
            string encryptkey  = RSAFromPkcs8.encryptData(merchantAesKey, Config.yibaoPublickey, "UTF-8");

            string postParams = "data=" + HttpUtility.UrlEncode(datastring)
                                + "&encryptkey=" + HttpUtility.UrlEncode(encryptkey)
                                + "&merchantaccount=" + Config.merchantAccount;
            string url = (!isMobile ? APIURLConfig.payWebPrefix : APIURLConfig.payMobilePrefix)
                         + (!isMobile ? APIURLConfig.pcwebURI : APIURLConfig.webpayURI)
                         + "?" + postParams;

            return(url);
            //return YBPAY.CreatePayByPostHTML(HttpUtility.UrlEncode(datastring),
            //    HttpUtility.UrlEncode(encryptkey),
            //    Config.merchantAccount,isMobile);
        }
Exemplo n.º 13
0
        /// <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);
        }
Exemplo n.º 14
0
        public static string GetResponseStr(RequestScanEntity pRequest, string scanDetailJson, string key)
        {
            Encoding code = Encoding.GetEncoding("utf-8");

            pRequest.biz_content = scanDetailJson;
            string requestPar = AliPayFunction.GetSignContent(pRequest.Paras);

            string sign = RSAFromPkcs8.Sign(requestPar, key, "utf-8");                     //生成签名
            //构造请求地址
            string strUrl = Geteway + requestPar + "&sign=" + HttpUtility.UrlEncode(sign); //请求参数

            //请求远程HTTP
            string strResult = "";

            try
            {
                //设置HttpWebRequest基本信息
                HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(strUrl);
                myReq.Method      = "post";
                myReq.ContentType = "application/x-www-form-urlencoded";

                //发送POST数据请求服务器
                HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
                Stream          myStream  = HttpWResp.GetResponseStream();

                //获取服务器返回信息
                StreamReader  reader       = new StreamReader(myStream, code);
                StringBuilder responseData = new StringBuilder();
                String        line;
                while ((line = reader.ReadLine()) != null)
                {
                    responseData.Append(line);
                }

                //释放
                myStream.Close();

                strResult = responseData.ToString();
            }
            catch (Exception exp)
            {
                throw exp;
            }

            return(HttpUtility.UrlDecode(strResult));
        }
Exemplo n.º 15
0
        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);
        }
Exemplo n.º 16
0
        //支付提交
        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());
        }
Exemplo n.º 17
0
    /// <summary>
    /// 一键支付回调信息解密
    /// </summary>
    /// <param name="data">返回的data</param>
    /// <param name="encryptkey">返回的encryptkey</param>
    /// <param name="yibaoPublickey">易宝公钥</param>
    /// <param name="merchantPrivatekey">商户私钥</param>
    /// <param name="type">编码格式</param>
    /// <returns></returns>
    public static string checkYbCallbackResult(string data, string encryptkey, string yibaoPublickey, string merchantPrivatekey, string type)
    {
        string yb_encryptkey = encryptkey;
        string yb_data       = data;
        //将易宝返回的结果进行验签名
        bool passSign = EncryptUtil.checkDecryptAndSign(yb_data, yb_encryptkey, yibaoPublickey, merchantPrivatekey);

        if (passSign)
        {
            string yb_aeskey = RSAFromPkcs8.decryptData(yb_encryptkey, merchantPrivatekey, type);

            string payresult_view = AES.Decrypt(yb_data, yb_aeskey);
            //返回易宝支付回调的业务数据明文
            return(payresult_view);
        }
        else
        {
            return("验签未通过");
        }
    }
Exemplo n.º 18
0
    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();
    }
Exemplo n.º 19
0
        public NotifyData GetNotifyData(AliPayChannel pChannel)
        {
            var str = string.Empty;

            if (this.SecID == "0001")
            {
                str = RSAFromPkcs8.DecryptData(NotifyDataStr, pChannel.RSA_PrivateKey, AliPayConfig.InputCharset);
            }
            else
            {
                str = HttpUtility.UrlDecode(NotifyDataStr);
            }
            if (!string.IsNullOrEmpty(str))
            {
                try
                {
                    Log.Loggers.Debug(new Log.DebugLogInfo()
                    {
                        Message = "阿里PAY支付通知的业务数据:" + str
                    });
                    Dictionary <string, string> tempDic = new Dictionary <string, string>();
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(str);
                    foreach (XmlElement item in doc.DocumentElement.ChildNodes)
                    {
                        tempDic[item.Name] = item.InnerText;
                    }
                    NotifyData data = new NotifyData();
                    data.Load(tempDic);
                    return(data);
                }
                catch (Exception ex)
                {
                    Log.Loggers.Exception(new Log.ExceptionLogInfo(ex)
                    {
                        ErrorMessage = str + ex.Message
                    });
                }
            }
            return(null);
        }
Exemplo n.º 20
0
 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, "\"" }) + "&notify_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);
         }
     }
 }
Exemplo n.º 21
0
        //提交查询
        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());
        }
Exemplo n.º 22
0
        /// <summary>
        /// 获取Sign
        /// </summary>
        protected override void SetSign()
        {
            var sortTempdic = new SortedDictionary <string, string>(Paras);
            var tempdic     = AliPayFunction.FilterPara(sortTempdic);
            var prestr      = AliPayFunction.CreateLinkString(tempdic);

            switch (SecID)
            {
            case "MD5":
                Sign = AlipayMD5.Sign(prestr, Channel.MD5Key, InputCharset);
                break;

            case "RSA":
                Sign = RSAFromPkcs8.Sign(prestr, Channel.RSA_PrivateKey, InputCharset);
                break;

            case "0001":
                Sign = RSAFromPkcs8.Sign(prestr, Channel.RSA_PrivateKey, InputCharset);
                break;

            default:
                throw new Exception("未知的加密方式:" + SecID);
            }
        }
Exemplo n.º 23
0
        public ActionResult VerifyAliPay(String orderId, String result)
        {
            Orders order = entities.Orders.Find(orderId);

            if (order == null)
            {
                return(Json(new { code = 201, desc = "指定订单不存在" }));
            }

            NimUser user = entities.NimUser.Single(o => o.Username == order.UserName);

            //如果异步通知成功,直接返回
            if (order.TradeStatus == "TRADE_SUCCESS" || order.TradeStatus == "TRADE_FINISHED")
            {
                //平衡学币
                user.NimUserEx.Coins = order.Coin + (user.NimUserEx.Coins ?? 0);
                order.IsBalance      = 1;
                entities.SaveChanges();

                return(Json(new { code = 200, desc = "支付成功", info = new { user.Username, Nickname = user.NimUserEx.Name, user.NimUserEx.Coins } }));
            }

            //如果服务端没有收到异步通知的时候,则要验证客户端发过来的同步通知(https://doc.open.alipay.com/doc2/detail.htm?spm=0.0.0.0.bsvyrx&treeId=59&articleId=103665&docType=1)
            //1、原始数据是否跟商户请求支付的原始数据一致(必须验证这个);
            //2、验证这个签名是否能通过。上述1、2通过后,在sign字段中success = true才是可信的。

            //构建原始数据,并验证是否一致,比如如果订单号不存在,那么就会验证不成功
            String orderString = OrderUtil.getOrderInfo(order);

            if (!result.Contains(orderString))
            {
                return(Json(new { code = 201, desc = "数据验证不通过" }));
            }

            //验证数据的签名,以[&sign_type="RSA"&sign=]为界,前面的为(原始数据&支付结果),后面的为带双引号的签名结果,在验证签名时,记录把开头和结尾的引号trim掉
            String[] a      = result.Split(new String[] { "&sign_type=\"RSA\"&sign=" }, StringSplitOptions.None);
            bool     isPass = RSAFromPkcs8.verify(a[0], a[1].Trim(new char[] { '"' }), Config.Public_key, Config.Input_charset);

            if (!isPass)
            {
                return(Json(new { code = 201, desc = "数据签名不相符" }));
            }

            //验证是否包含""这样的支付结果
            if (!a[0].Contains("&success=\"true\""))
            {
                return(Json(new { code = 201, desc = "支付失败" }));
            }

            order.TradeNo     = "";
            order.TradeStatus = "COMPLETED";//只说明是同步验证成功,应该尽量依靠服务器异步验证

            if (order.IsBalance != 1)
            {
                user.NimUserEx.Coins = order.Coin + (user.NimUserEx.Coins ?? 0);
                order.IsBalance      = 1;
            }

            entities.SaveChanges();
            return(Json(new { code = 200, desc = "支付成功", info = new { user.Username, Nickname = user.NimUserEx.Name, user.NimUserEx.Coins } }));
        }
Exemplo n.º 24
0
        /// <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);
        }
Exemplo n.º 25
0
        /// <summary>
        /// 验签,返回token字符串
        /// </summary>
        /// <param name="strResult">创建订单返回信息</param>
        /// <param name="sellprivatekey">商户私钥</param>
        /// <param name="input_charset">编码格式</param>
        /// <returns>token字符串</returns>
        private static string Res_dataDecrypt(string strResult, AliPayChannel pChannel, string input_charset, bool needCheck = false)
        {
            //分解返回数据 用&拆分赋值给result
            string[] result = strResult.Split('&');

            //提取res_data参数
            string res_data = string.Empty;

            for (int i = 0; i < result.Length; i++)
            {
                string data = result[i];
                if (data.IndexOf("res_data=") >= 0)
                {
                    res_data = data.Replace("res_data=", string.Empty);

                    //解密(用"商户私钥"对"res_data"进行解密)
                    res_data = AliPayFunction.Decrypt(res_data, pChannel.RSA_PrivateKey, input_charset);

                    //res_data 赋值 给 result[0]
                    result[i] = "res_data=" + res_data;
                }
            }

            //创建待签名数组
            SortedDictionary <string, string> sd = new SortedDictionary <string, string>();
            int    count  = 0;
            string sparam = "";
            string key    = "";
            string value  = "";

            for (int i = 0; i < result.Length; i++)
            {
                sparam = result[i];
                count  = sparam.IndexOf('=');
                key    = sparam.Substring(0, count);
                value  = sparam.Substring(count + 1, sparam.Length - (count + 1));
                sd.Add(key, value);
            }

            string sign = sd["sign"];

            //配置待签名数据
            Dictionary <string, string> dicData = AliPayFunction.FilterPara(sd);
            string req_Data = AliPayFunction.CreateLinkString(dicData);

            //验签,使用支付宝公钥
            bool vailSign = RSAFromPkcs8.Verify(req_Data, sign, pChannel.RSA_PublicKey, input_charset);

            if (!needCheck)
            {
                vailSign = true;
            }
            if (vailSign)//验签通过
            {
                //得到 request_token 的值
                string token = string.Empty;
                try
                {
                    token = AliPayFunction.GetStrForXmlDoc(res_data, "direct_trade_create_res/request_token");
                }
                catch (Exception ex)
                {
                    throw new Exception("方法:AliPayFunction.GetStrForXmlDoc()解析数据失败", ex);
                }
                return(token);
            }
            else
            {
                throw new Exception("返回的数据未通过验证,验签失败");
            }
        }
Exemplo n.º 26
0
    public static void testPay()
    {
        //一键支付URL前缀
        string apiprefix = APIURLConfig.payMobilePrefix;

        //网页支付地址
        string creditpayURI = APIURLConfig.webpayURI;

        //商户账户编号
        string merchantAccount = Config.merchantAccount;

        //商户公钥(该商户公钥需要在易宝一键支付商户后台报备)
        string merchantPublickey = Config.merchantPublickey;

        //商户私钥(商户公钥对应的私钥)
        string merchantPrivatekey = Config.merchantPrivatekey;

        //易宝支付分配的公钥(进入商户后台公钥管理,报备商户的公钥后分派的字符串)
        string yibaoPublickey = Config.yibaoPublickey;

        //随机生成商户AESkey
        string merchantAesKey = AES.GenerateAESKey();
        Random ra             = new Random();
        int    amount         = 2;                          //支付金额为分
        int    currency       = 156;
        string identityid     = "1234567" + 50 * ra.Next(); //用户身份标识
        int    identitytype   = 0;

        string orderid        = "1234567" + 50 * ra.Next();
        int    orderexpdate   = 60;
        string productcatalog = "1";    //商品类别码,商户支持的商品类别码由易宝支付运营人员根据商务协议配置
        string productdesc    = "我叫MT";
        string productname    = "符石";

        DateTime t1        = DateTime.Now;
        DateTime t2        = new DateTime(1970, 1, 1);
        double   t         = t1.Subtract(t2).TotalSeconds;
        int      transtime = (int)t;

        string userip       = "172.18.66.218";
        int    terminaltype = 3;
        String terminalid   = "05-16-DC-59-C2-34";



        //商户提供的商户后台系统异步支付回调地址
        string callbackurl = "http://172.18.66.107:8082/payapi-java-demo/callback";
        //商户提供的商户前台系统异步支付回调地址
        string fcallbackurl = "http://172.18.66.107:8082/payapi-java-demo/fcallback";
        //用户浏览器ua
        string userua = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1";


        SortedDictionary <string, object> sd = new SortedDictionary <string, object>();

        sd.Add("merchantaccount", merchantAccount);
        sd.Add("amount", amount);
        sd.Add("currency", currency);
        sd.Add("identityid", identityid);
        sd.Add("identitytype", identitytype);
        sd.Add("orderid", orderid);
        sd.Add("orderexpdate", orderexpdate);
        sd.Add("productcatalog", productcatalog);
        sd.Add("productdesc", productdesc);
        sd.Add("productname", productname);
        sd.Add("transtime", transtime);
        sd.Add("userip", userip);
        sd.Add("terminaltype", terminaltype);
        sd.Add("terminalid", terminalid);
        sd.Add("callbackurl", callbackurl);
        sd.Add("fcallbackurl", fcallbackurl);
        sd.Add("userua", userua);

        //生成RSA签名
        string sign = EncryptUtil.handleRSA(sd, merchantPrivatekey);

        Console.WriteLine("生成的签名为:" + sign);

        sd.Add("sign", sign);

        //将网页支付对象转换为json字符串
        string wpinfo_json = Newtonsoft.Json.JsonConvert.SerializeObject(sd);

        Console.WriteLine("网页支付明文数据json格式为:" + wpinfo_json);
        string datastring = AES.Encrypt(wpinfo_json, merchantAesKey);

        Console.WriteLine("网页支付业务数据经过AES加密后的值为:" + datastring);

        //将商户merchantAesKey用RSA算法加密
        Console.WriteLine("merchantAesKey为:" + merchantAesKey);
        string encryptkey = RSAFromPkcs8.encryptData(merchantAesKey, yibaoPublickey, "UTF-8");

        Console.WriteLine("encryptkey为:" + encryptkey);

        //打开浏览器访问一键支付网页支付链接地址,请求方式为get
        string postParams = "data=" + HttpUtility.UrlEncode(datastring) + "&encryptkey=" + HttpUtility.UrlEncode(encryptkey) + "&merchantaccount=" + merchantAccount;
        string url        = apiprefix + creditpayURI + "?" + postParams;

        Console.WriteLine("网页支付链接地址为:" + url);
        Console.WriteLine("网页支付链接地址长度为:" + url.Length);
        //System.Diagnostics.Process.Start("iexplore.exe", url);//打开IE浏览器
        System.Diagnostics.Process.Start("firefox.exe", url);    //打开firefox浏览器
        System.Diagnostics.Process.Start(url);

        Console.ReadLine();
    }
Exemplo n.º 27
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Request.Cookies.Remove("ErrorMsg");
            fastYeepayUser  = Request.Form["fastYeepayUser"] ?? string.Empty;
            fastYeepayMoney = Request.Form["fastYeepayMoney"] ?? string.Empty;
            payOtherMoney   = Request.Form["selfMoney"] ?? string.Empty;
            if (fastYeepayMoney.Equals("0"))
            {
                fastYeepayMoney = "100";
            }
            if (!string.IsNullOrEmpty(payOtherMoney))
            {
                fastYeepayMoney = payOtherMoney;
            }
            if (fastYeepayMoney.IndexOf(',') != -1)
            {
                fastYeepayMoney = fastYeepayMoney.Substring(0, fastYeepayMoney.Length - 1);
            }
            if (!string.IsNullOrEmpty(fastYeepayUser) && !string.IsNullOrEmpty(fastYeepayMoney))
            {
                AccountsInfo accountsInfo = accountsfacade.GetAccountsByAccontsName(fastYeepayUser);
                if (accountsInfo == null)
                {
                    HttpCookie UserCookie2 = new HttpCookie("ErrorMsg");
                    UserCookie2["error"] = HttpUtility.UrlEncode("用户名不存在");
                    UserCookie2.Expires  = DateTime.Now.AddMinutes(7);
                    Response.Cookies.Add(UserCookie2);
                    Response.Redirect("/showpayInfo.html");
                }
                try
                {
                    int.Parse(fastYeepayMoney);
                }
                catch (Exception)
                {
                    return;
                }
                //订单号
                string orderid = "KJZF-" + DateTime.Now.ToString("yyyyMMddhhmmss");

                HttpCookie UserCookie = new HttpCookie("PayOrder");
                UserCookie["order"]      = orderid;
                UserCookie["orderMoney"] = fastYeepayMoney;
                UserCookie["orderUser"]  = HttpUtility.UrlEncode(fastYeepayUser);
                UserCookie.Expires       = DateTime.Now.AddMinutes(7);
                Response.Cookies.Add(UserCookie);

                OnLineOrder online = new OnLineOrder();
                online.Accounts    = fastYeepayUser;
                online.UserID      = accountsInfo.UserID;
                online.OrderAmount = decimal.Parse((Convert.ToInt32(fastYeepayMoney)).ToString());
                online.OrderID     = orderid;
                online.OrderStatus = 0;
                online.ShareID     = 20;
                online.CardTotal   = 1;
                online.CardTypeID  = 1;
                online.TelPhone    = "";
                online.IPAddress   = GameRequest.GetUserIP();
                Message msg = treasurefacade.RequestOrder(online);
                if (msg.Success)
                {
                    //一键支付URL前缀
                    string apiprefix = APIURLConfig.payWebPrefix;

                    //网页支付地址
                    string pcPayURI = APIURLConfig.pcwebURI;

                    //商户账户编号
                    string merchantAccount = Config.merchantAccount;

                    //商户公钥(该商户公钥需要在易宝一键支付商户后台报备)
                    string merchantPublickey = Config.merchantPublickey;

                    //商户私钥(商户公钥对应的私钥)
                    string merchantPrivatekey = Config.merchantPrivatekey;

                    //易宝支付分配的公钥(进入商户后台公钥管理,报备商户的公钥后分派的字符串)
                    string yibaoPublickey = Config.yibaoPublickey;

                    //随机生成商户AESkey
                    string merchantAesKey = payapi_mobile_demo.AES.GenerateAESKey();

                    int      amount         = Convert.ToInt32(fastYeepayMoney) * 100;  //支付金额为分
                    int      currency       = 156;
                    string   identityid     = DateTime.Now.ToString("yyyyMMddhhmmss"); //用户身份标识
                    int      identitytype   = 0;
                    string   other          = "00-23-5A-15-99-42";                     //mac地址
                    string   productcatalog = "1";                                     //商品类别码,商户支持的商品类别码由易宝支付运营人员根据商务协议配置
                    string   productdesc    = "789游戏中心";
                    string   productname    = "金币";
                    DateTime t1             = DateTime.Now;
                    DateTime t2             = new DateTime(1970, 1, 1);
                    double   t         = t1.Subtract(t2).TotalSeconds;
                    int      transtime = (int)t;
                    string   userip    = GameRequest.GetUserIP();
                    //商户提供的商户后台系统异步支付回调地址
                    string callbackurl = ConfigurationManager.AppSettings["fastYeepayNotify"].ToString();
                    //商户提供的商户前台系统异步支付回调地址
                    string fcallbackurl = ConfigurationManager.AppSettings["fastYeepayCallback"].ToString();
                    //用户浏览器ua
                    string userua = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1";
                    SortedDictionary <string, object> sd = new SortedDictionary <string, object>();
                    sd.Add("merchantaccount", merchantAccount);
                    sd.Add("amount", amount);
                    sd.Add("currency", currency);
                    sd.Add("identityid", identityid);
                    sd.Add("identitytype", identitytype);
                    sd.Add("orderid", orderid);
                    sd.Add("other", other);
                    sd.Add("productcatalog", productcatalog);
                    sd.Add("productdesc", productdesc);
                    sd.Add("productname", productname);
                    sd.Add("transtime", transtime);
                    sd.Add("userip", userip);
                    sd.Add("callbackurl", callbackurl);
                    sd.Add("fcallbackurl", fcallbackurl);
                    sd.Add("userua", userua);
                    //生成RSA签名
                    string sign = EncryptUtil.handleRSA(sd, merchantPrivatekey);
                    //Console.WriteLine("生成的签名为:" + sign);
                    sd.Add("sign", sign);
                    //将网页支付对象转换为json字符串
                    string wpinfo_json = Newtonsoft.Json.JsonConvert.SerializeObject(sd);
                    string datastring  = payapi_mobile_demo.AES.Encrypt(wpinfo_json, merchantAesKey);
                    //将商户merchantAesKey用RSA算法加密
                    string encryptkey = RSAFromPkcs8.encryptData(merchantAesKey, yibaoPublickey, "UTF-8");
                    //打开浏览器访问一键支付网页支付链接地址,请求方式为get
                    string postParams = "data=" + HttpUtility.UrlEncode(datastring) + "&encryptkey=" + HttpUtility.UrlEncode(encryptkey) + "&merchantaccount=" + merchantAccount;
                    string url        = apiprefix + pcPayURI + "?" + postParams;
                    Response.Redirect(url);
                }
                else
                {
                    HttpCookie UserCookie2 = new HttpCookie("ErrorMsg");
                    UserCookie2["error"] = HttpUtility.UrlEncode(msg.Content);
                    UserCookie2.Expires  = DateTime.Now.AddMinutes(7);
                    Response.Cookies.Add(UserCookie2);
                    Response.Redirect("/showpayInfo.html");
                }
            }
        }
Exemplo n.º 28
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // string apiprefix = APIURLConfig.apiprefix;

            //网页支付地址
            // string creditpayURI = APIURLConfig.webpayURI;

            //一键支付URL前缀
            string apiprefix = APIURLConfig.payWebPrefix;

            //网页支付地址
            string pcPayURI = APIURLConfig.pcwebURI;

            //商户账户编号
            string merchantAccount = Config.merchantAccount;

            //商户公钥(该商户公钥需要在易宝一键支付商户后台报备)
            string merchantPublickey = Config.merchantPublickey;

            //商户私钥(商户公钥对应的私钥)
            string merchantPrivatekey = Config.merchantPrivatekey;

            //易宝支付分配的公钥(进入商户后台公钥管理,报备商户的公钥后分派的字符串)
            string yibaoPublickey = Config.yibaoPublickey;

            //随机生成商户AESkey
            string merchantAesKey = payapi_mobile_demo.AES.GenerateAESKey();

            int    amount         = Convert.ToInt32(Request["p3_Amt1"].ToString()) * 100; //支付金额为分
            int    currency       = 156;
            string identityid     = DateTime.Now.ToString("yyyyMMddhhmmss");              //用户身份标识
            int    identitytype   = 0;
            Random ra             = new Random();
            string orderid        = "kjzf789123456" + 50 * ra.Next();
            string other          = "00-23-5A-15-99-42"; //mac地址
            string productcatalog = "1";                 //商品类别码,商户支持的商品类别码由易宝支付运营人员根据商务协议配置
            string productdesc    = "789游戏中心";
            string productname    = "金币";

            DateTime t1        = DateTime.Now;
            DateTime t2        = new DateTime(1970, 1, 1);
            double   t         = t1.Subtract(t2).TotalSeconds;
            int      transtime = (int)t;

            string userip = GameRequest.GetUserIP();
            //商户提供的商户后台系统异步支付回调地址
            string callbackurl = ConfigurationManager.AppSettings["yibao_Notify"].ToString();
            //商户提供的商户前台系统异步支付回调地址
            string fcallbackurl = ConfigurationManager.AppSettings["yibao_CallBack"].ToString();
            //用户浏览器ua
            string userua = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1";


            SortedDictionary <string, object> sd = new SortedDictionary <string, object>();

            sd.Add("merchantaccount", merchantAccount);
            sd.Add("amount", amount);
            sd.Add("currency", currency);
            sd.Add("identityid", identityid);
            sd.Add("identitytype", identitytype);
            sd.Add("orderid", orderid);
            sd.Add("other", other);
            sd.Add("productcatalog", productcatalog);
            sd.Add("productdesc", productdesc);
            sd.Add("productname", productname);
            sd.Add("transtime", transtime);
            sd.Add("userip", userip);
            sd.Add("callbackurl", callbackurl);
            sd.Add("fcallbackurl", fcallbackurl);
            sd.Add("userua", userua);

            //生成RSA签名
            string sign = EncryptUtil.handleRSA(sd, merchantPrivatekey);

            //Console.WriteLine("生成的签名为:" + sign);

            sd.Add("sign", sign);

            //将网页支付对象转换为json字符串
            string wpinfo_json = Newtonsoft.Json.JsonConvert.SerializeObject(sd);
            // Console.WriteLine("网页支付明文数据json格式为:" + wpinfo_json);
            string datastring = payapi_mobile_demo.AES.Encrypt(wpinfo_json, merchantAesKey);
            //Console.WriteLine("网页支付业务数据经过AES加密后的值为:" + datastring);

            //将商户merchantAesKey用RSA算法加密
            // Console.WriteLine("merchantAesKey为:" + merchantAesKey);
            string encryptkey = RSAFromPkcs8.encryptData(merchantAesKey, yibaoPublickey, "UTF-8");
            // Console.WriteLine("encryptkey为:" + encryptkey);

            //打开浏览器访问一键支付网页支付链接地址,请求方式为get
            string postParams = "data=" + HttpUtility.UrlEncode(datastring) + "&encryptkey=" + HttpUtility.UrlEncode(encryptkey) + "&merchantaccount=" + merchantAccount;
            string url        = apiprefix + pcPayURI + "?" + postParams;

            OnLineOrder online = new OnLineOrder();
            int         uid    = accountsfacade.GetAccountsId(Request["yijianAccountNo"].ToString());

            online.Accounts    = Request["yijianAccountNo"].ToString();
            online.UserID      = uid;
            online.OrderAmount = decimal.Parse((Convert.ToInt32(amount) / 100).ToString());
            online.OrderID     = orderid;
            online.OrderStatus = 0;
            online.ShareID     = 19;
            online.CardTotal   = 1;
            online.CardTypeID  = 1;
            online.TelPhone    = "";
            online.IPAddress   = GameRequest.GetUserIP();
            Message msg = treasurefacade.RequestOrder(online);

            if (!msg.Success)
            {
                Response.Redirect("/Tips.aspx?msg=" + msg.Content);
            }
            else
            {
                Response.Redirect(url);
            }
            // Console.WriteLine("网页支付链接地址为:" + url);
            // Console.WriteLine("网页支付链接地址长度为:" + url.Length);
            // System.Diagnostics.Process.Start("firefox.exe", url);//打开firefox浏览器
            // System.Diagnostics.Process.Start(url);

            //Console.ReadLine();
        }