Beispiel #1
0
        private static void CheckSign()
        {
            IDictionary <string, string> paramsMap = new Dictionary <string, string>();

            paramsMap.Add("appId", "2013092500031084");
            var privateKeyPem = Path.Combine(GetCurrentPath(), "aop-sandbox-RSA-private-c#.pem");

            if (!File.Exists(privateKeyPem))
            {
                throw new FileNotFoundException();
            }
            var sign = AlipaySignature.RSASign(paramsMap, privateKeyPem, null, "RSA");

            paramsMap.Add("sign", sign);
            var publicKey = Path.Combine(GetCurrentPath(), "public-key.pem");

            if (!File.Exists(publicKey))
            {
                throw new FileNotFoundException();
            }
            var checkSign = AlipaySignature.RSACheckV2(paramsMap, publicKey);

            Console.Write("---------公众号通知消息签名验证--------" + "\n\r");
            Console.Write("checkSign:" + checkSign + "\n\r");
        }
Beispiel #2
0
        public static string Signature(VipUserOrderInfo info)
        {
            string timestamp   = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string biz_content = string.Empty;

            StringBuilder builder = new StringBuilder();

            builder.Append("app_id=");
            builder.Append(HttpUtility.UrlEncode(app_id));
            builder.Append("&biz_content=");
            biz_content  = "{\"timeout_express\":\"30m\",\"seller_id\":\"";
            biz_content += seller_id;
            biz_content += "\",";
            biz_content += "\"product_code\":\"QUICK_MSECURITY_PAY\",";
            biz_content += "\"total_amount\":\"" + info.mo_money.ToString("f2") + "\",";
            biz_content += "\"subject\":\"" + "企业查询宝会员" + "\",";
            biz_content += "\"body\":\"" + "企业查询宝会员" + "\",";
            biz_content += "\"out_trade_no\":\"" + info.mo_orderid + "\"}";
            biz_content  = HttpUtility.UrlEncode(biz_content);
            builder.Append(biz_content);
            builder.Append("&charset=" + HttpUtility.UrlEncode("utf-8"));
            builder.Append("&method=" + HttpUtility.UrlEncode("alipay.trade.app.pay"));
            builder.Append("&notify_url=");
            builder.Append(HttpUtility.UrlEncode(alipay_notify_url));
            builder.Append("&sign_type=" + HttpUtility.UrlEncode("RSA"));
            builder.Append("&timestamp=");
            builder.Append(HttpUtility.UrlEncode(timestamp).Replace("+", " "));
            builder.Append("&version=" + HttpUtility.UrlEncode("1.0"));
            string Signature = AlipaySignature.RSASign(SignatureContent(info, timestamp), APP_PRIVATE_KEY, "utf-8", "RSA");

            builder.Append("&sign=");
            builder.Append(HttpUtility.UrlEncode(Signature));

            return(builder.ToString());
        }
Beispiel #3
0
        /// <summary>
        /// 生成RSA签名后的订单字符串
        /// </summary>
        /// <param name="price"></param>
        /// <param name="description"></param>
        /// <returns></returns>
        public static string createRSASignedOrderString(double price, string description)
        {
            Dictionary <string, string> orderStringDict = new Dictionary <string, string>();

            orderStringDict.Add("app_id", APP_ID);
            orderStringDict.Add("method", "alipay.trade.app.pay");
            orderStringDict.Add("format", "JSON");
            orderStringDict.Add("charset", "utf-8");
            orderStringDict.Add("sign_type", "RSA");
            orderStringDict.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            orderStringDict.Add("version", "1.0");
            orderStringDict.Add("notify_url", "");
            orderStringDict.Add("biz_content", generateBizContentString(price.ToString(), description));

            // 排序拼接成字符串
            string orderInfo        = AlipaySignature.GetSignContent(orderStringDict);
            string orderInfoEncoded = Core.CreateLinkStringUrlencode(orderStringDict, (new System.Text.UTF8Encoding()));

            // 签名
            string privateKeyPem = GetCurrentPath() + "rsa_private_key.pem";
            string signString    = AlipaySignature.RSASign(orderInfo, privateKeyPem, null, "RSA");

            signString = HttpUtility.UrlEncode(signString, new UTF8Encoding());

            // 加上sign
            string orderString = orderInfoEncoded + "&sign=" + signString;

            // 拼接最终返回给客户端的字符串
            return(orderString);
        }
Beispiel #4
0
        private static void CheckSignAndDecrypt()
        {
            // 参数构建
            var charset    = "UTF-8";
            var bizContent =
                "<XML><AppId><![CDATA[2013082200024893]]></AppId><FromUserId><![CDATA[2088102122485786]]></FromUserId><CreateTime>1377228401913</CreateTime><MsgType><![CDATA[click]]></MsgType><EventType><![CDATA[event]]></EventType><ActionParam><![CDATA[authentication]]></ActionParam><AgreementId><![CDATA[201308220000000994]]></AgreementId><AccountNo><![CDATA[null]]></AccountNo><UserInfo><![CDATA[{\"logon_id\":\"15858179811\",\"user_name\":\"许旦辉\"}]]></UserInfo></XML>";
            var publicKeyPem  = Path.Combine(GetCurrentPath(), "public-key.pem");
            var privateKeyPem = Path.Combine(GetCurrentPath(), "aop-sandbox-RSA-private-c#.pem");

            if (!File.Exists(publicKeyPem))
            {
                throw new FileNotFoundException();
            }
            if (!File.Exists(privateKeyPem))
            {
                throw new FileNotFoundException();
            }
            IDictionary <string, string> paramsMap = new Dictionary <string, string>();

            paramsMap.Add("biz_content", AlipaySignature.RSAEncrypt(bizContent, publicKeyPem, charset));
            paramsMap.Add("charset", charset);
            paramsMap.Add("service", "alipay.mobile.public.message.notify");
            paramsMap.Add("sign_type", "RSA");
            paramsMap.Add("sign", AlipaySignature.RSASign(paramsMap, privateKeyPem, null, "RSA"));

            // 验签&解密
            var resultContent = AlipaySignature.CheckSignAndDecrypt(paramsMap, publicKeyPem, privateKeyPem, true, true);

            Console.Write("resultContent=" + resultContent + "\n\r");
        }
Beispiel #5
0
        public async Task <T> ExecuteAsync <T>(IAlipayRequest <T> request, string accessToken, string appAuthToken) where T : AlipayResponse
        {
            var multiMediaDownloadRequest = ((AlipayMobilePublicMultiMediaDownloadRequest)request);
            // 添加协议级请求参数
            var txtParams = new AlipayDictionary(request.GetParameters())
            {
                { METHOD, request.GetApiName() },
                { VERSION, Options.Version },
                { APP_ID, Options.AppId },
                { FORMAT, Options.Format },
                { TIMESTAMP, DateTime.Now },
                { ACCESS_TOKEN, accessToken },
                { SIGN_TYPE, Options.SignType },
                { TERMINAL_TYPE, request.GetTerminalType() },
                { TERMINAL_INFO, request.GetTerminalInfo() },
                { PROD_CODE, request.GetProdCode() }
            };

            if (!string.IsNullOrEmpty(appAuthToken))
            {
                txtParams.Add(APP_AUTH_TOKEN, appAuthToken);
            }

            // 添加签名参数
            txtParams.Add(SIGN, AlipaySignature.RSASign(txtParams, RSAPrivateParameters, Options.SignType));

            var outStream = multiMediaDownloadRequest.Stream;
            var rsp       = await DoGetAsync(txtParams, outStream);

            return((T)rsp);
        }
Beispiel #6
0
    public static string com_alipay_account_auth()
    {
        IDictionary <string, string> paramsMap = new Dictionary <string, string>();

        paramsMap.Add("scope", "kuaijie");
        paramsMap.Add("product_id", "APP_FAST_LOGIN");
        paramsMap.Add("pid", Pid);
        paramsMap.Add("apiname", "com.alipay.account.auth");
        paramsMap.Add("auth_type", "AUTHACCOUNT");
        paramsMap.Add("biz_type", "openservice");
        paramsMap.Add("app_id", appId);
        paramsMap.Add("target_id", "RSA");
        paramsMap.Add("app_name", "mc");
        paramsMap.Add("sign_type", "RSA");


        string privateKeyPem = merchant_private_key;
        string sign          = AlipaySignature.RSASign(paramsMap, privateKeyPem, null, false, "RSA");

        paramsMap.Add("sign", System.Web.HttpUtility.UrlEncode(sign));

        var str = AlipaySignature.GetSignContent(paramsMap);

        return(str);
    }
Beispiel #7
0
        /// <summary>
        /// 验证网关,签名内容并返回给支付宝xml
        /// </summary>
        /// <param name="_success"></param>
        /// <param name="merchantPubKey"></param>
        /// <returns></returns>
        public string verifygwResponse(bool _success, string merchantPubKey)
        {
            //Response.ContentType = "text/xml";
            //Response.ContentEncoding = System.Text.Encoding.GetEncoding("GBK");
            //Response.Clear();

            XmlDocument    xmlDoc  = new XmlDocument(); //创建实例
            XmlDeclaration xmldecl = xmlDoc.CreateXmlDeclaration("1.0", "GBK", null);

            xmlDoc.AppendChild(xmldecl);


            XmlElement xmlElem = xmlDoc.CreateElement("alipay"); //新建元素

            xmlDoc.AppendChild(xmlElem);                         //添加元素


            XmlNode    alipay   = xmlDoc.SelectSingleNode("alipay");
            XmlElement response = xmlDoc.CreateElement("response");
            XmlElement success  = xmlDoc.CreateElement("success");

            if (_success)
            {
                success.InnerText = "true";    //设置文本节点
                response.AppendChild(success); //添加到<Node>节点中
            }
            else
            {
                success.InnerText = "false";   //设置文本节点
                response.AppendChild(success); //添加到<Node>节点中
                XmlElement err = xmlDoc.CreateElement("error_code");
                err.InnerText = "VERIFY_FAILED";
                response.AppendChild(err);
            }

            XmlElement biz_content = xmlDoc.CreateElement("biz_content");

            biz_content.InnerText = merchantPubKey;
            response.AppendChild(biz_content);

            alipay.AppendChild(response);

            string _sign = AlipaySignature.RSASign(response.InnerXml, Config.merchant_private_key, Config.charset);

            XmlElement sign = xmlDoc.CreateElement("sign");

            sign.InnerText = _sign;
            alipay.AppendChild(sign);
            XmlElement sign_type = xmlDoc.CreateElement("sign_type");

            sign_type.InnerText = "RSA";
            alipay.AppendChild(sign_type);

            //Response.Output.Write(xmlDoc.InnerXml);
            //log(xmlDoc.InnerXml);
            //Response.End();

            return(xmlDoc.InnerXml);
        }
Beispiel #8
0
        public static string ReturnXmlResponse(bool _success, string merchantPubKey, HttpContext context, string ToUserId, string AppId)
        {
            context.Response.ContentType     = "text/xml";
            context.Response.ContentEncoding = System.Text.Encoding.GetEncoding(AlipayFuwuConfig.charset);
            context.Response.Clear();
            XmlDocument    xmlDocument = new XmlDocument();
            XmlDeclaration newChild    = xmlDocument.CreateXmlDeclaration("1.0", AlipayFuwuConfig.charset, null);

            xmlDocument.AppendChild(newChild);
            XmlElement newChild2 = xmlDocument.CreateElement("alipay");

            xmlDocument.AppendChild(newChild2);
            XmlNode    xmlNode     = xmlDocument.SelectSingleNode("alipay");
            XmlElement xmlElement  = xmlDocument.CreateElement("response");
            XmlElement xmlElement2 = xmlDocument.CreateElement("success");
            XmlElement xmlElement3 = xmlDocument.CreateElement("XML");

            if (_success)
            {
                XmlElement xmlElement4 = xmlDocument.CreateElement("MsgType");
                xmlElement4.InnerText = "ack";
                XmlElement xmlElement5 = xmlDocument.CreateElement("CreateTime");
                xmlElement5.InnerText = AliOHHelper.TransferToMilStartWith1970(System.DateTime.Now).ToString("F0");
                XmlElement xmlElement6 = xmlDocument.CreateElement("ToUserId");
                xmlElement6.InnerText = ToUserId;
                XmlElement xmlElement7 = xmlDocument.CreateElement("AppId");
                xmlElement7.InnerText = AppId;
                xmlElement3.AppendChild(xmlElement4);
                xmlElement3.AppendChild(xmlElement5);
                xmlElement3.AppendChild(xmlElement6);
                xmlElement3.AppendChild(xmlElement7);
                xmlElement.AppendChild(xmlElement3);
            }
            else
            {
                xmlElement2.InnerText = "false";
                xmlElement.AppendChild(xmlElement2);
                XmlElement xmlElement8 = xmlDocument.CreateElement("error_code");
                xmlElement8.InnerText = "VERIFY_FAILED";
                xmlElement.AppendChild(xmlElement8);
            }
            xmlNode.AppendChild(xmlElement);
            string     innerText   = AlipaySignature.RSASign(xmlElement.InnerXml, AlipayFuwuConfig.merchant_private_key, AlipayFuwuConfig.charset);
            XmlElement xmlElement9 = xmlDocument.CreateElement("sign");

            xmlElement9.InnerText = innerText;
            xmlNode.AppendChild(xmlElement9);
            XmlElement xmlElement10 = xmlDocument.CreateElement("sign_type");

            xmlElement10.InnerText = "RSA";
            xmlNode.AppendChild(xmlElement10);
            AliOHHelper.log(xmlDocument.InnerXml);
            context.Response.Output.Write(xmlDocument.InnerXml);
            context.Response.End();
            return(null);
        }
        public static string ReturnXmlResponse(bool _success, string merchantPubKey, HttpContext context, string ToUserId, string AppId)
        {
            context.Response.ContentType     = "text/xml";
            context.Response.ContentEncoding = Encoding.GetEncoding(AlipayFuwuConfig.charset);
            context.Response.Clear();
            XmlDocument    document = new XmlDocument();
            XmlDeclaration newChild = document.CreateXmlDeclaration("1.0", AlipayFuwuConfig.charset, null);

            document.AppendChild(newChild);
            XmlElement element = document.CreateElement("alipay");

            document.AppendChild(element);
            XmlNode    node     = document.SelectSingleNode("alipay");
            XmlElement element2 = document.CreateElement("response");
            XmlElement element3 = document.CreateElement("success");
            XmlElement element4 = document.CreateElement("XML");

            if (_success)
            {
                XmlElement element5 = document.CreateElement("MsgType");
                element5.InnerText = "ack";
                XmlElement element6 = document.CreateElement("CreateTime");
                element6.InnerText = TransferToMilStartWith1970(DateTime.Now).ToString("F0");
                XmlElement element7 = document.CreateElement("ToUserId");
                element7.InnerText = ToUserId;
                XmlElement element8 = document.CreateElement("AppId");
                element8.InnerText = AppId;
                element4.AppendChild(element5);
                element4.AppendChild(element6);
                element4.AppendChild(element7);
                element4.AppendChild(element8);
                element2.AppendChild(element4);
            }
            else
            {
                element3.InnerText = "false";
                element2.AppendChild(element3);
                XmlElement element9 = document.CreateElement("error_code");
                element9.InnerText = "VERIFY_FAILED";
                element2.AppendChild(element9);
            }
            node.AppendChild(element2);
            string     str       = AlipaySignature.RSASign(element2.InnerXml, AlipayFuwuConfig.merchant_private_key, AlipayFuwuConfig.charset);
            XmlElement element10 = document.CreateElement("sign");

            element10.InnerText = str;
            node.AppendChild(element10);
            XmlElement element11 = document.CreateElement("sign_type");

            element11.InnerText = "RSA";
            node.AppendChild(element11);
            log(document.InnerXml);
            context.Response.Output.Write(document.InnerXml);
            context.Response.End();
            return(null);
        }
Beispiel #10
0
        public void CheckSign()
        {
            IDictionary <string, string> paramsMap = new Dictionary <string, string>();

            paramsMap.Add("appId", "2013092500031084");
            string privateKeyPem = GetCurrentPath() + "aop-sandbox-RSA-private-c#.pem";
            string sign          = AlipaySignature.RSASign(paramsMap, privateKeyPem, null, "RSA2");

            paramsMap.Add("sign", sign);
            string publicKey = GetCurrentPath() + "public-key.pem";
            bool   checkSign = AlipaySignature.RSACheckV2(paramsMap, publicKey);
        }
Beispiel #11
0
        // GET: /<controller>/
        public IActionResult Index()
        {
            var builder = BuildPayContent();
            var request = new AlipayTradeWapPayRequest();

            request.BizContent = JsonConvert.SerializeObject(builder);


            string apiVersion = null;

            if (!string.IsNullOrEmpty(request.GetApiVersion()))
            {
                apiVersion = request.GetApiVersion();
            }
            else
            {
                apiVersion = "1.0";
            }

            // 添加协议级请求参数
            var txtParams = new AopDictionary(request.GetParameters());

            txtParams.Add("method", request.GetApiName());
            txtParams.Add("version", apiVersion);
            txtParams.Add("app_id", Config.app_id);
            txtParams.Add("format", "json");
            txtParams.Add("timestamp", DateTime.Now);
            txtParams.Add("auth_token", null);
            txtParams.Add("sign_type", Config.sign_type);
            txtParams.Add("terminal_type", request.GetTerminalType());
            txtParams.Add("terminal_info", request.GetTerminalInfo());
            txtParams.Add("prod_code", request.GetProdCode());
            txtParams.Add("charset", Config.charset);


            if (!string.IsNullOrEmpty(request.GetNotifyUrl()))
            {
                txtParams.Add("notify_url", request.GetNotifyUrl());
            }

            // 添加签名参数
            txtParams.Add("sign",
                          AlipaySignature.RSASign(txtParams, Config.merchant_private_key, Config.charset, false, Config.sign_type));

            //建立请求
            var sHtmlText = Submit.BuildRequest(txtParams, "get", "确认");


            return(View("Index", sHtmlText));
        }
Beispiel #12
0
        /// <summary>
        /// 生成支付宝订单
        /// author:陶林辉
        /// </summary>
        /// <param name="recharge">商品对象</param>
        /// <param name="order">订单号</param>
        /// <returns></returns>
        public string CreateAlipayReceipt(RechargeCommodityDto recharge, string order)
        {
            string privateKeyPem             = _appSettings.PrivateKeyPem;              //商户私钥
            string out_trade_no              = order;                                   //订单号
            double total_fee                 = double.Parse(recharge.Money.ToString()); //交易金额
            string app_id                    = _appSettings.App_id;                     //app支付,支付宝中该应用的ID
            string charset                   = "utf-8";                                 //utf-8
            string timestamp                 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string notify_url                = _appSettings.Notify_url;                 //回调地址
            string body                      = recharge.Name;
            string subject                   = "乐趣海南充值";
            Dictionary <string, string> dic  = new Dictionary <string, string>();
            Dictionary <string, object> dic2 = new Dictionary <string, object>();

            dic.Add("app_id", app_id);
            dic.Add("method", "alipay.trade.app.pay");
            dic.Add("version", "1.0");
            dic.Add("charset", charset);
            dic.Add("notify_url", notify_url);
            dic.Add("sign_type", _appSettings.Sign_type);
            dic.Add("timestamp", timestamp);
            dic2.Add("out_trade_no", out_trade_no); //商户订单号
            dic2.Add("total_amount", total_fee);    //支付金额
            dic2.Add("product_code", _appSettings.Product_code);
            dic2.Add("body", body);
            dic2.Add("subject", subject);
            dic.Add("biz_content", JsonHelper.SerializeObject(dic2));
            string sign = AlipaySignature.RSASign(dic, privateKeyPem, "utf-8", false, _appSettings.Sign_type);

            sign = HttpUtility.UrlEncode(sign, Encoding.GetEncoding(charset));
            string Parms     = string.Empty;
            var    testparms = string.Empty;

            foreach (KeyValuePair <String, string> k in dic)
            {
                testparms += k.Key + "=" + k.Value + "&";
                if (Parms == string.Empty)
                {
                    Parms = k.Key + "=" + HttpUtility.UrlEncode(k.Value, Encoding.GetEncoding(charset));
                }
                else
                {
                    Parms += "&" + k.Key + "=" + HttpUtility.UrlEncode(k.Value, Encoding.GetEncoding(charset));
                }
            }

            Parms = Parms + "&sign=" + sign;
            return(Parms);
        }
Beispiel #13
0
        //static void Main()
        //{
        //    // 公众号菜单查询
        //    //MenuGet();

        //    // 公众号通知消息签名验证
        //    //CheckSign();

        //    // 公众号验签&解密
        //    CheckSignAndDecrypt();

        //    // 公众号加密&加签
        //    EncryptAndSign();
        //}

        private static void CheckSign()
        {
            IDictionary <string, string> paramsMap = new Dictionary <string, string>();

            paramsMap.Add("appId", "2013092500031084");
            string privateKeyPem = GetCurrentPath() + "aop-sandbox-RSA-private-c#.pem";
            string sign          = AlipaySignature.RSASign(paramsMap, privateKeyPem, null, "RSA");

            paramsMap.Add("sign", sign);
            string publicKey = GetCurrentPath() + "public-key.pem";
            bool   checkSign = AlipaySignature.RSACheckV2(paramsMap, publicKey);

            System.Console.Write("---------公众号通知消息签名验证--------" + "\n\r");
            System.Console.Write("checkSign:" + checkSign + "\n\r");
        }
        private static void CheckSign()
        {
            IDictionary <string, string> dictionary = new Dictionary <string, string>();

            dictionary.Add("appId", "2013092500031084");
            string privateKeyPem = GetCurrentPath() + "aop-sandbox-RSA-private-c#.pem";
            string value         = AlipaySignature.RSASign(dictionary, privateKeyPem, null, "RSA");

            dictionary.Add("sign", value);
            string publicKeyPem = GetCurrentPath() + "public-key.pem";
            bool   flag         = AlipaySignature.RSACheckV2(dictionary, publicKeyPem);

            Console.Write("---------公众号通知消息签名验证--------\n\r");
            Console.Write("checkSign:" + flag.ToString() + "\n\r");
        }
        public static string verifygwResponse(bool _success, string merchantPubKey, HttpContext context)
        {
            context.Response.ContentType     = "text/xml";
            context.Response.ContentEncoding = Encoding.GetEncoding(AlipayFuwuConfig.charset);
            context.Response.Clear();
            XmlDocument    document = new XmlDocument();
            XmlDeclaration newChild = document.CreateXmlDeclaration("1.0", AlipayFuwuConfig.charset, null);

            document.AppendChild(newChild);
            XmlElement element = document.CreateElement("alipay");

            document.AppendChild(element);
            XmlNode    node     = document.SelectSingleNode("alipay");
            XmlElement element2 = document.CreateElement("response");
            XmlElement element3 = document.CreateElement("success");

            if (_success)
            {
                element3.InnerText = "true";
                element2.AppendChild(element3);
            }
            else
            {
                element3.InnerText = "false";
                element2.AppendChild(element3);
                XmlElement element4 = document.CreateElement("error_code");
                element4.InnerText = "VERIFY_FAILED";
                element2.AppendChild(element4);
            }
            XmlElement element5 = document.CreateElement("biz_content");

            element5.InnerText = merchantPubKey;
            element2.AppendChild(element5);
            node.AppendChild(element2);
            string     str      = AlipaySignature.RSASign(element2.InnerXml, AlipayFuwuConfig.merchant_private_key, AlipayFuwuConfig.charset);
            XmlElement element6 = document.CreateElement("sign");

            element6.InnerText = str;
            node.AppendChild(element6);
            XmlElement element7 = document.CreateElement("sign_type");

            element7.InnerText = "RSA";
            node.AppendChild(element7);
            context.Response.Output.Write(document.InnerXml);
            context.Response.End();
            return(null);
        }
        public static void CheckSignAndDecrypt()
        {
            string text    = "UTF-8";
            string content = "<XML><AppId><![CDATA[2013082200024893]]></AppId><FromUserId><![CDATA[2088102122485786]]></FromUserId><CreateTime>1377228401913</CreateTime><MsgType><![CDATA[click]]></MsgType><EventType><![CDATA[event]]></EventType><ActionParam><![CDATA[authentication]]></ActionParam><AgreementId><![CDATA[201308220000000994]]></AgreementId><AccountNo><![CDATA[null]]></AccountNo><UserInfo><![CDATA[{\"logon_id\":\"15858179811\",\"user_name\":\"许旦辉\"}]]></UserInfo></XML>";
            string text2   = GetCurrentPath() + "public-key.pem";
            string text3   = GetCurrentPath() + "aop-sandbox-RSA-private-c#.pem";
            IDictionary <string, string> dictionary = new Dictionary <string, string>();

            dictionary.Add("biz_content", AlipaySignature.RSAEncrypt(content, text2, text));
            dictionary.Add("charset", text);
            dictionary.Add("service", "alipay.mobile.public.message.notify");
            dictionary.Add("sign_type", "RSA");
            dictionary.Add("sign", AlipaySignature.RSASign(dictionary, text3, null, "RSA"));
            string str = AlipaySignature.CheckSignAndDecrypt(dictionary, text2, text3, isCheckSign: true, isDecrypt: true);

            Console.Write("resultContent=" + str + "\n\r");
        }
Beispiel #17
0
        /// <summary>
        /// 生成请求时的签名
        /// </summary>
        /// <param name="sPara">请求给支付宝的参数数组</param>
        /// <returns>签名结果</returns>
        private static string BuildRequestMysign(Dictionary <string, string> sPara)
        {
            //把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
            string prestr = Core.CreateLinkString(sPara);

            //把最终的字符串签名,获得签名结果
            string mysign = "";

            switch (_sign_type)
            {
            case "RSA2":
                mysign = AlipaySignature.RSASign(sPara, _private_key, _input_charset, false, _sign_type);
                break;

            default:
                mysign = "";
                break;
            }

            return(mysign);
        }
        public static void CheckSignAndDecrypt()
        {
            // 参数构建
            string charset       = "UTF-8";
            string bizContent    = "<XML><AppId><![CDATA[2013082200024893]]></AppId><FromUserId><![CDATA[2088102122485786]]></FromUserId><CreateTime>1377228401913</CreateTime><MsgType><![CDATA[click]]></MsgType><EventType><![CDATA[event]]></EventType><ActionParam><![CDATA[authentication]]></ActionParam><AgreementId><![CDATA[201308220000000994]]></AgreementId><AccountNo><![CDATA[null]]></AccountNo><UserInfo><![CDATA[{\"logon_id\":\"15858179811\",\"user_name\":\"许旦辉\"}]]></UserInfo></XML>";
            string publicKeyPem  = GetCurrentPath() + "public-key.pem";
            string privateKeyPem = GetCurrentPath() + "aop-sandbox-RSA-private-c#.pem";
            IDictionary <string, string> paramsMap = new Dictionary <string, string>
            {
                { "biz_content", AlipaySignature.RSAEncrypt(bizContent, publicKeyPem, charset) },
                { "charset", charset },
                { "service", "alipay.mobile.public.message.notify" },
                { "sign_type", "RSA" }
            };

            paramsMap.Add("sign", AlipaySignature.RSASign(paramsMap, privateKeyPem, null, "RSA"));

            // 验签&解密
            string resultContent = AlipaySignature.CheckSignAndDecrypt(paramsMap, publicKeyPem, privateKeyPem, true, true);

            System.Console.Write("resultContent=" + resultContent + "\n\r");
        }
Beispiel #19
0
        /// <summary>
        /// App支付宝支付
        /// </summary>
        /// <param name="body">商品描述</param>
        /// <param name="subject">标题</param>
        /// <param name="total_amount">金额</param>
        /// <param name="newOrderId">订单ID</param>
        public string ZfbPayMethod(string body, string subject, string total_amount, string newOrderId)
        {
            if (newOrderId != null && newOrderId != "")
            {
                IDictionary <string, string> paramsMap = new Dictionary <string, string>();
                paramsMap.Add("appId", AlipayUtilities.AliPay.Config.appid);
                string privateKeyPem = AppDomain.CurrentDomain.BaseDirectory + "/Signature/" + "aop-sandbox-RSA-private-c#.pem";
                string sign          = AlipaySignature.RSASign(paramsMap, privateKeyPem, null, "RSA");
                paramsMap.Add("sign", sign);
                string publicKey = AppDomain.CurrentDomain.BaseDirectory + "/Signature/" + "public-key.pem";
                bool   checkSign = AlipaySignature.RSACheckV2(paramsMap, publicKey);    //验证签名是否正确
                if (checkSign == true)
                {
                    biz_content _biz_content = new biz_content();
                    _biz_content.notify_url      = Config.notify_url;
                    _biz_content.body            = body == null ? "" : body;
                    _biz_content.out_trade_no    = newOrderId;
                    _biz_content.product_code    = "QUICK_MSECURITY_PAY";
                    _biz_content.subject         = subject == null ? "" : subject;
                    _biz_content.timeout_express = "30m";
                    var newtotal_amount = "0.01";
                    if (total_amount != null || total_amount != "")
                    {
                        newtotal_amount = double.Parse(total_amount).ToString("f2");
                    }
                    _biz_content.total_amount = newtotal_amount;
                    string jsonvalue  = jsonHelper.Serialize(_biz_content);
                    string BizContent = "app_id=" + AlipayUtilities.AliPay.Config.appid + @"&biz_content=" + jsonvalue + "";
                    BizContent += @"&charset=utf-8&format=json&method=alipay.trade.app.pay&sign_type=RSA&timestamp=" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "&version=1.0";
                    string sign_ = AlipaySignature.RSASign(BizContent, privateKeyPem, null, "RSA");

                    BizContent += @"&sign=" + UrlEncode(sign_, Encoding.UTF8) + "";

                    return(BizContent);
                }
                return("");
            }
            return("");
        }
        public T Execute <T>(IRequest request) where T : AliResponse, IAliResponseStatus
        {
            Dictionary <string, string> dictionary = new Dictionary <string, string>();

            dictionary.Add("method", request.GetMethodName());
            dictionary.Add("app_id", this.appId);
            dictionary.Add("timestamp", DateTime.Now.ToString(this.dateTimeFormat));
            dictionary.Add("sign_type", this.signType);
            dictionary.Add("charset", this.charset);
            dictionary.Add("biz_content", request.GetBizContent());
            dictionary.Add("sign", AlipaySignature.RSASign((IDictionary <string, string>)dictionary, this.privateKey, this.charset));
            T obj = JsonConvert.DeserializeObject <T>(this.webUtils.DoPost(this.serverUrl, (IDictionary <string, string>)dictionary, this.charset));

            if (obj.error_response != null && obj.error_response.IsError)
            {
                throw new AliResponseException(obj.error_response.code, obj.error_response.sub_msg);
            }
            if (obj.Code != "200")
            {
                throw new AliResponseException(obj.Code, obj.Message);
            }
            return(obj);
        }
Beispiel #21
0
        public Task <T> SdkExecuteAsync <T>(IAlipayRequest <T> request) where T : AlipayResponse
        {
            // 构造请求参数
            var requestParams = BuildRequestParams(request, null, null);

            // 字典排序
            var sortedParams    = new SortedDictionary <string, string>(requestParams);
            var sortedAlipayDic = new AlipayDictionary(sortedParams);

            // 参数签名
            var signResult = AlipaySignature.RSASign(sortedAlipayDic, Options.RsaPrivateKey, Options.SignType);

            // 添加签名结果参数
            sortedAlipayDic.Add(SIGN, signResult);

            // 参数拼接
            var signedResult = HttpClientEx.BuildQuery(sortedAlipayDic);

            // 构造结果
            var rsp = (T)Activator.CreateInstance(typeof(T));

            rsp.Body = signedResult;
            return(Task.FromResult(rsp));
        }
Beispiel #22
0
        public IHttpActionResult AliPaySign(int OrderID)
        {
            WebApi_BLL.T_Product_Orders   bll   = new WebApi_BLL.T_Product_Orders();
            WebApi_Model.T_Product_Orders order = bll.GetModel(OrderID);

            if (order == null)
            {
                return(Ok(ReturnJsonResult.GetJsonResult(-1, "Error", "找不到订单")));
            }
            else if (order.Status != 0)
            {
                return(Ok(ReturnJsonResult.GetJsonResult(-1, "Error", "找不到需要支付的订单")));
            }
            else
            {
                Dictionary <string, string> parameters = new Dictionary <string, string>();
                parameters.Add("app_id", ConfigurationManager.AppSettings["app_id"].ToString());
                parameters.Add("biz_content", "{\"timeout_express\":\"30m\",\"seller_id\":\"" + ConfigurationManager.AppSettings["seller_id"].ToString() + "\",\"product_code\":\"QUICK_MSECURITY_PAY\",\"total_amount\":\"" + order.TotalAmount + "\",\"subject\":\"商品支付" + order.OrderID + "\",\"body\":\"支付\",\"out_trade_no\":\"" + order.OrderNum + "\"}");
                parameters.Add("charset", "utf-8");
                parameters.Add("format", "json");
                parameters.Add("method", "alipay.trade.app.pay");
                parameters.Add("notify_url", ConfigurationManager.AppSettings["notify_url"].ToString());
                parameters.Add("sign_type", "RSA");
                parameters.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
                parameters.Add("version", "1.0");

                string strSignContent = AlipaySignature.GetSignContent(parameters);
                string strSign        = AlipaySignature.RSASign(parameters, System.Web.Hosting.HostingEnvironment.MapPath("~/Content/Key/rsa_private_key.pem"), "", "RSA");

                //parameters.Add("sign", strSign);

                string strRet = Decode(parameters) + "&sign=" + HttpUtility.UrlEncode(strSign);
                //string str = strSignContent + "&sign=" + strSign;
                return(Ok(ReturnJsonResult.GetJsonResult(1, "OK", strRet)));
            }
        }
Beispiel #23
0
        public async Task <T> PageExecuteAsync <T>(IAlipayRequest <T> request, string accessToken, string reqMethod) where T : AlipayResponse
        {
            string apiVersion = null;

            if (!string.IsNullOrEmpty(request.GetApiVersion()))
            {
                apiVersion = request.GetApiVersion();
            }
            else
            {
                apiVersion = Options.Version;
            }

            var txtParams = new AlipayDictionary(request.GetParameters())
            {
                // 序列化BizModel
                { BIZ_CONTENT, JsonConvert.SerializeObject(request.GetBizModel(), new JsonSerializerSettings()
                    {
                        NullValueHandling = NullValueHandling.Ignore
                    }) },
                // 添加协议级请求参数
                { METHOD, request.GetApiName() },
                { VERSION, apiVersion },
                { APP_ID, Options.AppId },
                { FORMAT, Options.Format },
                { TIMESTAMP, DateTime.Now },
                { ACCESS_TOKEN, accessToken },
                { SIGN_TYPE, Options.SignType },
                { TERMINAL_TYPE, request.GetTerminalType() },
                { TERMINAL_INFO, request.GetTerminalInfo() },
                { PROD_CODE, request.GetProdCode() },
                { NOTIFY_URL, request.GetNotifyUrl() },
                { CHARSET, Options.Charset },
                { RETURN_URL, request.GetReturnUrl() }
            };

            // 添加签名参数
            txtParams.Add(SIGN, AlipaySignature.RSASign(txtParams, Options.RsaPrivateKey, Options.SignType));

            // 是否需要上传文件
            string body;

            if (request is IAlipayUploadRequest <T> uRequest)
            {
                var fileParams = AlipayUtility.CleanupDictionary(uRequest.GetFileParameters());
                body = await Client.DoPostAsync(Options.ServerUrl, txtParams, fileParams);
            }
            else
            {
                if (reqMethod.Equals("GET"))
                {
                    //拼接get请求的url
                    var tmpUrl = Options.ServerUrl;
                    if (txtParams != null && txtParams.Count > 0)
                    {
                        if (tmpUrl.Contains("?"))
                        {
                            tmpUrl = tmpUrl + "&" + HttpClientEx.BuildQuery(txtParams);
                        }
                        else
                        {
                            tmpUrl = tmpUrl + "?" + HttpClientEx.BuildQuery(txtParams);
                        }
                    }
                    body = tmpUrl;
                }
                else
                {
                    //输出post表单
                    body = BuildHtmlRequest(txtParams, reqMethod, reqMethod);
                }
            }

            T rsp = null;
            IAlipayParser <T> parser = null;

            if ("json".Equals(Options.Format))
            {
                parser = new AlipayJsonParser <T>();
                rsp    = parser.Parse(body);
            }
            return(rsp);
        }
Beispiel #24
0
        public async Task <T> ExecuteAsync <T>(IAlipayRequest <T> request, string accessToken, string appAuthToken) where T : AlipayResponse
        {
            string apiVersion = null;

            if (!string.IsNullOrEmpty(request.GetApiVersion()))
            {
                apiVersion = request.GetApiVersion();
            }
            else
            {
                apiVersion = Options.Version;
            }

            // 添加协议级请求参数
            var txtParams = new AlipayDictionary(request.GetParameters())
            {
                { BIZ_CONTENT, JsonConvert.SerializeObject(request.GetBizModel(), new JsonSerializerSettings()
                    {
                        NullValueHandling = NullValueHandling.Ignore
                    }) },
                { METHOD, request.GetApiName() },
                { VERSION, apiVersion },
                { APP_ID, Options.AppId },
                { FORMAT, Options.Format },
                { TIMESTAMP, DateTime.Now },
                { ACCESS_TOKEN, accessToken },
                { SIGN_TYPE, Options.SignType },
                { TERMINAL_TYPE, request.GetTerminalType() },
                { TERMINAL_INFO, request.GetTerminalInfo() },
                { PROD_CODE, request.GetProdCode() },
                { CHARSET, Options.Charset }
            };

            if (!string.IsNullOrEmpty(request.GetNotifyUrl()))
            {
                txtParams.Add(NOTIFY_URL, request.GetNotifyUrl());
            }

            if (!string.IsNullOrEmpty(appAuthToken))
            {
                txtParams.Add(APP_AUTH_TOKEN, appAuthToken);
            }

            if (request.GetNeedEncrypt())
            {
                if (string.IsNullOrEmpty(txtParams[BIZ_CONTENT]))
                {
                    throw new AlipayException("api request Fail ! The reason: encrypt request is not supported!");
                }

                if (string.IsNullOrEmpty(Options.EncyptKey) || string.IsNullOrEmpty(Options.EncyptType))
                {
                    throw new AlipayException("encryptType or encryptKey must not null!");
                }

                if (!"AES".Equals(Options.EncyptType))
                {
                    throw new AlipayException("api only support Aes!");
                }

                var encryptContent = AlipayUtility.AesEncrypt(Options.EncyptKey, txtParams[BIZ_CONTENT]);
                txtParams.Remove(BIZ_CONTENT);
                txtParams.Add(BIZ_CONTENT, encryptContent);
                txtParams.Add(ENCRYPT_TYPE, Options.EncyptType);
            }

            // 添加签名参数
            txtParams.Add(SIGN, AlipaySignature.RSASign(txtParams, Options.RsaPrivateKey, Options.SignType));

            // 是否需要上传文件
            string body;

            if (request is IAlipayUploadRequest <T> uRequest)
            {
                var fileParams = AlipayUtility.CleanupDictionary(uRequest.GetFileParameters());
                body = await Client.DoPostAsync(Options.ServerUrl, txtParams, fileParams);
            }
            else
            {
                body = await Client.DoPostAsync(Options.ServerUrl, txtParams);
            }

            T rsp = null;
            IAlipayParser <T> parser = null;

            if ("json".Equals(Options.Format))
            {
                parser = new AlipayJsonParser <T>();
            }

            var item = ParseRespItem(request, body, parser, Options.EncyptKey, Options.EncyptType);

            rsp = parser.Parse(item.realContent);

            CheckResponseSign(request, item.respContent, rsp.IsError, parser, Options.RsaPublicKey, Options.SignType);

            return(rsp);
        }
Beispiel #25
0
        public string RSASign(string OrderNo, decimal Money, string bodyp, string subjectp)
        {
            string publicKeyPem  = @"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnMZa3HbYp3iK1GNdO4wgWLnpo3FOJYim8QrzhTatE6al7+Gz5WuaUpJEIV4CcFd9lW1n0XuUUIKDznXp4SaX0Yz/J9pA5WQ0Qoq3OwcwmyYGm58VTuF2Kqnu4AnD27z4CsrArvyp760ijgRPEU1CUQLXEvRLV4tvBCukZ3Sx3hRuJvRF3prc7m+GtehkstZUc38os9DqNJE2yBPj6Ae1mXE+Se26vdmQfykyXeQjFpZ4cdELsJAvoHp1HzSQ8l+zCCcndTI/RCOtSensb2wMXSQ1zhSmYjEXtEpPpTZcO5Js9nvjr0/i9hp6Eao0P5ppMtjO2TX3uvFPb5SRVBUACwIDAQAB";
            string privateKeyPem = @"MIIEpAIBAAKCAQEAwEcE+f25SQy8I1EjCgVrTC0xRicTMBl5Wos4MblkDWokw0Z6
8ADPLLkOL/WPae7a9NgRdOMOmBuLDDqaL+KSZ1ALw+rGA0G92TD56QYI4JIhDaUr
ShD/V4kEFbcH/Muws8wlw0Rka7AyZiea4V66TUzG0bDnUZTtMJJTppXfS/qpE4Kg
0MxFb+whBCwyicMVsyHA2ZmBrPPAzETid1iN6ILdtkKgs97U3C7Gz2uB9X5UBShN
G5gIyEV0tlb+C9J+3K1v7CD2Pybs2JG7+olEXIoHfHntoq8S0W6hVxGssLR1eDd0
tfzibiMH6F69TdO0yEHeK5YkdsaH5CzCEqMQiQIDAQABAoIBABWoakEWeUZnLtHz
k7TPQ3TDKmeygxDJ7cdrIxtGvKReLmHokHR0QuHQvm5chJj0FKm7pMu7v6sWfyUT
fMakCMWmWIzq5v766r2KLLw4t8tD6oE095lSLNDZWCJyCW5KK081UZObIoyWvjaP
g3ybRPTsDwETohqoYcc01ENRYmOWWA5hmO5ZDDuyzTkD89iG4+wqHvLD/pqWUTF7
P8sXnePwD/q1OUX0NkGFzA7d7FnFor2mlvG9sPouCrIXQABL086ZTcLyrsoWyDbV
QMxv0P77ebtHQcyT5D5sIF8BZqQ5J06PNCqr4GwgBHea5mgHS2JD0swlHPQERcYE
/sT9M1kCgYEA++98NsZi+8IIHZrbT4ilOIbTcKmU3RWEcvNj42ngu6TueGRNZBoc
/4UXL1Ci1n6O+BopJuAVrG5ko0DehmEmo+kZUxntRSExajZ8osBaqM1VTajU2pRK
pHatP273m5AA5EM3SmsUuYOi49b6/xFi1PLzlXtj7uUMkEkbNtAk+NMCgYEAw2Ek
MU7MhNDPqNYZBhU0dYQKyhaH9ZTWK2IfcYz35Cx8MVgoj+2PMd9yrFlUzMRWwP9F
vCw6eyaEnHb/ks0l6+3sC8AVh8DBwj9nk+6hRqM76hLdbM+iVtTP/UxmuDlUoe6n
bmgJIuG/ByilfnbIAhx+luzRarpCH8D7C28Fd7MCgYEA9mxGPDGKSiR82bBJyZ6n
tQWztWQ6NpHAbsuArcU3S3NEyj+Zr0sXiBs/FUmzLUi3QRgdnmfa60FDcKeXwSsv
p23uFmmquk6AThqjiHHLe4b0ZDS6ll4sMHfgd8ZrrR6KsLrKTyE0MUz/vAngkjMI
T7Cf71u04MvroQnQ86leMH8CgYBxGeDLsmPuVrp/cEDYJppRlPhx+A0Ievpn7sto
/kPaEG5sWi5Q8yI7qrBFWQkf6GCYJK4Hukq4U5ncwX49SwiyxO4p9y3/gfQoMHAT
UMaHj6L1Y6pOfPvq7BLi/MFRz85QV0kRPqRbTvc4e60hwj0SC9C0Ka8o612v6BTr
j39IxQKBgQCLjMw4u1jomTsc+pqpieeay4aGvLlTRoOpsAKMI+YBn1072KjSPY1m
PhqMa50QfsgQtk9f/nHDF03IU7PITyY7K/3gUx3NSkNz789Jjrt7TS+xxBHuBM3C
aRqLacU+wjdieRylky7lwkVwg0mToUQFlxgmJACdibz1ZS0sja9IvQ==";                                    //商户私钥

            string out_trade_no = OrderNo;                                                    //订单号
            double total_fee    = (double)Money;                                              //交易金额
            string app_id       = "2017082808426992";                                         //app支付,支付宝中该应用的ID
            string charset      = "utf-8";                                                    //utf-8
            string timestamp    = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string notify_url   = Utility.Helper.GetHttpUrl("/api/sdk_callback_alipay.aspx"); //服务器异步通知页面路径 ;//回调地址
            string body         = bodyp;
            string subject      = subjectp;

            Dictionary <string, string> dic = new Dictionary <string, string>();

            Dictionary <string, object> dic2 = new Dictionary <string, object>();

            dic.Add("app_id", app_id);
            dic.Add("method", "alipay.trade.app.pay");
            dic.Add("version", "1.0");
            dic.Add("charset", charset);
            dic.Add("notify_url", notify_url);
            dic.Add("sign_type", "RSA2");
            dic.Add("timestamp", timestamp);

            dic2.Add("out_trade_no", out_trade_no); //商户订单号
            dic2.Add("total_amount", total_fee);    //支付金额
            dic2.Add("product_code", "QUICK_MSECURITY_PAY");
            dic2.Add("body", bodyp);
            dic2.Add("subject", subject);

            dic.Add("biz_content", JsonConvert.SerializeObject(dic2));

            //string sign = AlipaySignature.RSASign(dic, privateKeyPem, null, "RSA2");

            //AlipaySignature.RSASign方法是支付宝提供的签名方法,使用这个方法需要注意参数的传入,第一个参数为需要签名的参数,第二个参数为商户私钥,第4个参数如果传入fase,表示支付宝私钥以字符串的形式传入,true表示第二个参数要传存储私钥的文件地址,并且这个文件内容开头和结尾都要加“-----BEGIN RSA PRIVATE KEY----- 私钥 -----END RSA PRIVATE KEY-----”

            string sign = AlipaySignature.RSASign(dic, privateKeyPem, "utf-8", false, "RSA2");

            sign = HttpUtility.UrlEncode(sign, Encoding.GetEncoding(charset));

            string Parms     = string.Empty;
            var    testparms = string.Empty;

            //Parms = Aop.Api.Util.AlipaySignature.GetSignContent(dic);

            foreach (KeyValuePair <String, string> k in dic)
            {
                testparms += k.Key + "=" + k.Value + "&";
                if (Parms == string.Empty)
                {
                    Parms = k.Key + "=" + HttpUtility.UrlEncode(k.Value, Encoding.GetEncoding(charset));
                }
                else
                {
                    Parms += "&" + k.Key + "=" + HttpUtility.UrlEncode(k.Value, Encoding.GetEncoding(charset));
                }
            }

            Parms = Parms + "&sign=" + sign;
            //Parms = sign;
            return(Parms);
        }
Beispiel #26
0
 /// <summary>
 ///     建议直接使用<code>AlipaySignature.RSASign(data, privateKeyPem)</code>
 /// </summary>
 /// <param name="data"></param>
 /// <param name="privateKeyPem"></param>
 /// <returns></returns>
 public static string RSASign(string data, string privateKeyPem, string charset)
 {
     return(AlipaySignature.RSASign(data, privateKeyPem, charset, "RSA"));
 }
Beispiel #27
0
        public string RSASigntext(string OrderNo, decimal Money, string bodyp, string subjectp)
        {
            string publicKeyPem  = @"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAofOvvo2LrP3JIX6QerZ2
jzAgK0JFocOR+MZFCXxCboJ177LEc/LcHh5SsKovlApMqMf6QtpQenP4tFi60WYP
0YJTK122f9o/EccXcgVZZMs5LCTpH8KcnGrT67LxMSwV8akvaw8ifCFovZw35oFc
VJ7R+3xoiYRhzIDpQ+6hwoKBlgDpbGaTww9bW3qrHL91SljYrSgjI9H/jhO6XWlr
Pof6gEhruf8uPhfEG9oGs77IpVNP9xWjAmFnMAqjU0isXItmhkBYmYT89PcccIr5
VCy1rXJmNVylpiVELSCatCq+OP0M5J14pGkez5dEbQbnoJ+3E/T8UD3KUZ35aZCe
eQIDAQAB";                                                                                    //支付宝公钥
            string privateKeyPem = @"MIIEowIBAAKCAQEAofOvvo2LrP3JIX6QerZ2jzAgK0JFocOR+MZFCXxCboJ177LE
c/LcHh5SsKovlApMqMf6QtpQenP4tFi60WYP0YJTK122f9o/EccXcgVZZMs5LCTp
H8KcnGrT67LxMSwV8akvaw8ifCFovZw35oFcVJ7R+3xoiYRhzIDpQ+6hwoKBlgDp
bGaTww9bW3qrHL91SljYrSgjI9H/jhO6XWlrPof6gEhruf8uPhfEG9oGs77IpVNP
9xWjAmFnMAqjU0isXItmhkBYmYT89PcccIr5VCy1rXJmNVylpiVELSCatCq+OP0M
5J14pGkez5dEbQbnoJ+3E/T8UD3KUZ35aZCeeQIDAQABAoIBAQCPxEXlAL5XqUsd
Qr97T/LblbtY65Ho0jYJA+lRTE+kzodna+jdjWA+FGkPj2SBJMt8oVnWcvsyWTUU
1Bezv8iXEfxG6QATa2jFnVmAzKLYyVdNis6wdRCWAndyKv3Vyu8IAkqn3V2dmALl
H4K4S2ntbLe3am9adHxlEKMCvRo4Ejyf+/dWbVJZpy8ryd6ei1FBXeePVTwwqCbz
NEd+WDnxJCp3hxGG9SaSWg9uEmpV8W929InRRhAY4foSeXo7eUCwMJfCDGDDbvuS
NAWlR0kqZ8wxAjugKAwTY48vT9pX8On+54u4ERYNfH2ALDjVHr7T9d65w2TAXxyX
RutMyx0hAoGBANS1QnqaPsCT1aF5bx3CU7Hmqru7/e6trSu78lJ5p6waEKOtS4N6
SFc7TgT8CBR8T82uhigPX8/ZZ1wOViHOfzyMhxCNvB/jNB7VAKRFT8prvGaGJiu7
vdePFM67RavDBgrMS7MQUpWEINaLc8SU2872Y6WkXgAcrgkcldC19c9VAoGBAMLp
4FOv39mzj9PL4XULUBYYHP8KgcyWuNrYtTneY8OW6s3w+3oVSJ1eikTbd3l0FE1B
rTuXxC5tO9LXV5qa3qm9jDVKmVAdHdZmyqbpbNfK2xD90ZtwKUE0QeXcB5SI15lr
b7IizsfrxpV2QBjK49+d1ODZelHFPPRjvRrpjyqVAoGAH8pzhCV3iYrO3BJtNBJu
NeGW1PY07q5Qen/dqMv77nH62Ku25JCrLTZ047PTdVRbDQ+vh18837DLjOurnePi
CmeqbCPy4QUxLgaB0Qt28HcHsn8MR28I4aXF41wD/rboOUbtbXbcEPKtgcNX6yKg
c59Jp2EYl4Wx0TTPg2Eeuv0CgYB3dStdXv8Mx/YwUlY9i89rmx+6V9AxeXaV+hcn
/lqadxY1XapiqkS03kpT5UYWE8SVjNkFGwDLi3sMv5obUSuCUH9r8eqApTeyPZGa
NpnUr6kPguBCKb2/Dq4MmIu0xyGMD8KHJLoi4Sf2VmD2UPLUDEF6BQ/oqb+v8Kjn
o5lw+QKBgEkDddwDNZoLlomqnfG6KMfgwzh76BHkrCryMxUoaDx75ze+qgPnv77u
a6a+aJqsfrpzh+fYEQV+No1ko1SW7Hv7MX+C9JOYLZIY7ybV0bg9wkiAcWgvtvdu
OwaT6nVyI6JIdQK3RW25fGRFr+Olqd0Dwju2UeH3sTiHLmL5nGPn";                                        //商户私钥

            string out_trade_no = OrderNo;                                                    //订单号
            double total_fee    = (double)Money;                                              //交易金额
            string app_id       = "2017060907457467";                                         //app支付,支付宝中该应用的ID
            string charset      = "utf-8";                                                    //utf-8
            string timestamp    = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string notify_url   = Utility.Helper.GetHttpUrl("/api/sdk_callback_alipay.aspx"); //服务器异步通知页面路径 ;//回调地址
            string body         = bodyp;
            string subject      = subjectp;

            Dictionary <string, string> dic = new Dictionary <string, string>();

            Dictionary <string, object> dic2 = new Dictionary <string, object>();

            dic.Add("app_id", app_id);
            dic.Add("method", "alipay.trade.app.pay");
            dic.Add("version", "1.0");
            dic.Add("charset", charset);
            dic.Add("notify_url", notify_url);
            dic.Add("sign_type", "RSA2");
            dic.Add("timestamp", timestamp);

            dic2.Add("out_trade_no", out_trade_no); //商户订单号
            dic2.Add("total_amount", total_fee);    //支付金额
            dic2.Add("product_code", "QUICK_MSECURITY_PAY");
            dic2.Add("body", bodyp);
            dic2.Add("subject", subject);

            dic.Add("biz_content", JsonConvert.SerializeObject(dic2));

            //string sign = AlipaySignature.RSASign(dic, privateKeyPem, null, "RSA2");

            //AlipaySignature.RSASign方法是支付宝提供的签名方法,使用这个方法需要注意参数的传入,第一个参数为需要签名的参数,第二个参数为商户私钥,第4个参数如果传入fase,表示支付宝私钥以字符串的形式传入,true表示第二个参数要传存储私钥的文件地址,并且这个文件内容开头和结尾都要加“-----BEGIN RSA PRIVATE KEY----- 私钥 -----END RSA PRIVATE KEY-----”

            string sign = AlipaySignature.RSASign(dic, privateKeyPem, "utf-8", false, "RSA2");

            sign = HttpUtility.UrlEncode(sign, Encoding.GetEncoding(charset));

            string Parms     = string.Empty;
            var    testparms = string.Empty;

            //Parms = Aop.Api.Util.AlipaySignature.GetSignContent(dic);

            foreach (KeyValuePair <String, string> k in dic)
            {
                testparms += k.Key + "=" + k.Value + "&";
                if (Parms == string.Empty)
                {
                    Parms = k.Key + "=" + HttpUtility.UrlEncode(k.Value, Encoding.GetEncoding(charset));
                }
                else
                {
                    Parms += "&" + k.Key + "=" + HttpUtility.UrlEncode(k.Value, Encoding.GetEncoding(charset));
                }
            }

            Parms = Parms + "&sign=" + sign;

            //Parms = sign;
            return(Parms);
        }
Beispiel #28
0
        public T Execute <T>(IAopRequest <T> request, string accessToken, string appAuthToken) where T : AopResponse
        {
            if (string.IsNullOrEmpty(this.charset))
            {
                this.charset = "utf-8";
            }

            string apiVersion = null;

            if (!string.IsNullOrEmpty(request.GetApiVersion()))
            {
                apiVersion = request.GetApiVersion();
            }
            else
            {
                apiVersion = Version;
            }

            // 添加协议级请求参数
            AopDictionary txtParams = new AopDictionary(request.GetParameters());

            txtParams.Add(METHOD, request.GetApiName());
            txtParams.Add(VERSION, apiVersion);
            txtParams.Add(APP_ID, appId);
            txtParams.Add(FORMAT, format);
            txtParams.Add(TIMESTAMP, DateTime.Now);
            txtParams.Add(ACCESS_TOKEN, accessToken);
            txtParams.Add(SIGN_TYPE, signType);
            txtParams.Add(TERMINAL_TYPE, request.GetTerminalType());
            txtParams.Add(TERMINAL_INFO, request.GetTerminalInfo());
            txtParams.Add(PROD_CODE, request.GetProdCode());
            txtParams.Add(NOTIFY_URL, request.GetNotifyUrl());
            txtParams.Add(CHARSET, charset);
            txtParams.Add(APP_AUTH_TOKEN, appAuthToken);

            // 添加签名参数
            txtParams.Add(SIGN, AlipaySignature.RSASign(txtParams, privateKeyPem, charset));
            //txtParams.Add(SIGN, AopUtils.SignAopRequest(txtParams, privateKeyPem, charset));
            // 是否需要上传文件
            string body;


            if (request is IAopUploadRequest <T> )
            {
                IAopUploadRequest <T>          uRequest   = (IAopUploadRequest <T>)request;
                IDictionary <string, FileItem> fileParams = AopUtils.CleanupDictionary(uRequest.GetFileParameters());
                body = webUtils.DoPost(this.serverUrl + "?" + CHARSET + "=" + this.charset, txtParams, fileParams, this.charset);
            }
            else
            {
                body = webUtils.DoPost(this.serverUrl + "?" + CHARSET + "=" + this.charset, txtParams, this.charset);
            }

            T rsp = null;
            IAopParser <T> parser = null;

            if ("xml".Equals(format))
            {
                parser = new AopXmlParser <T>();
                rsp    = parser.Parse(body, charset);
            }
            else
            {
                parser = new AopJsonParser <T>();
                rsp    = parser.Parse(body, charset);
            }

            CheckResponseSign(request, rsp, parser, this.alipayPublicKey, this.charset);

            return(rsp);
        }
Beispiel #29
0
        public BaseResult AliPay(AliPayModel aliModel)
        {
            BaseResult br = new BaseResult();

            try
            {
                #region 构建支付宝调用数据
                var paramters = new Dictionary <string, string>();
                paramters.Add("app_id", aliModel.app_id);       //开发者帐号
                paramters.Add("method", aliModel.method);       //接口名称
                paramters.Add("charset", aliModel.charset);     //请求使用的编码格式,如utf - 8,gbk,gb2312等
                paramters.Add("sign_type", aliModel.sign_type); //商户生成签名字符串所使用的签名算法类型,目前支持RSA
                paramters.Add("timestamp", aliModel.timestamp); //发送请求的时间,格式"yyyy-MM-dd HH:mm:ss"
                paramters.Add("version", aliModel.version);     //调用的接口版本,固定为:1.0

                if (string.IsNullOrEmpty(aliModel.store_id))
                {
                    aliModel.store_id = "-999";
                }

                string bizContent = "{" +
                                    "    \"out_trade_no\":\"" + aliModel.out_trade_no + "\"," +
                                    "    \"scene\":\"" + aliModel.scene + "\"," +
                                    "    \"auth_code\":\"" + aliModel.auth_code + "\"," +
                                    "    \"total_amount\":" + aliModel.total_amount + "," +
                                    "    \"subject\":\"" + aliModel.subject + "\"," +
                                    "    \"store_id\":\"" + aliModel.store_id + "\"" +
                                    " }";
                bizContent = bizContent.Trim();
                paramters.Add("biz_content", bizContent);

                string mySign = AlipaySignature.RSASign(paramters, aliModel.sign, "utf-8", false, "RSA");//生成签名 其中aliModel.sign为定义的私钥值
                paramters.Add("sign", mySign);

                #endregion
                #region 构建调用内部接口数据
                var dataContent = AlipaySignature.GetSignContent(paramters);
                paramters.Clear();
                //paramters.Add("data",   dataContent);
                var eData = HttpUtility.UrlEncode(dataContent, Encoding.UTF8);
                paramters.Add("data", dataContent);
                string myNewSign = CYUtils.SignRequestNew(paramters, PublicSign.localKey);
                paramters.Add("sign", myNewSign);
                paramters.Remove("data");
                paramters.Add("data", eData);
                paramters.Add("amount", aliModel.total_amount.ToString());

                #endregion

                var result = new WebUtils().DoPost(PublicSign.aliPayUrl, paramters, 200000);
                AliPayResultModel retPayModel = Utility.JSON.Deserialize <AliPayResultModel>(result);
                if (retPayModel.alipay_trade_pay_response.code == "10000" && retPayModel.alipay_trade_pay_response.msg == "Success")
                {
                    retPayModel.out_trade_no = retPayModel.alipay_trade_pay_response.out_trade_no;
                    retPayModel.trade_no     = retPayModel.alipay_trade_pay_response.trade_no;
                    br.Success = true;
                    br.Data    = retPayModel;
                    return(br);
                }
                else
                {
                    if (retPayModel.alipay_trade_pay_response.sub_code == "ACQ.TRADE_HAS_SUCCESS")
                    {
                        br.Success = true;
                        br.Message.Add(string.Format("订单已被支付 描述:" + retPayModel.alipay_trade_pay_response.sub_msg));
                        retPayModel.out_trade_no = retPayModel.alipay_trade_pay_response.out_trade_no;
                        retPayModel.trade_no     = retPayModel.alipay_trade_pay_response.trade_no;
                        br.Success = true;
                        br.Data    = retPayModel;
                        return(br);
                    }
                    else if (retPayModel.alipay_trade_pay_response.sub_code == "ACQ.SYSTEM_ERROR")
                    {
                        br.Success = false;
                        br.Message.Add(string.Format("支付宝异常接口返回错误 需要查询订单结果 描述:" + retPayModel.alipay_trade_pay_response.sub_msg));
                        br.Level = ErrorLevel.Warning;
                        return(br);
                    }
                    else if (retPayModel.alipay_trade_pay_response.sub_code == "ACQ.USER_FACE_PAYMENT_SWITCH_OFF")
                    {
                        br.Success = false;
                        br.Message.Add(string.Format("用户当面付付款开关关闭 需要让用户在手机上打开当面付付款开关 描述:" + retPayModel.alipay_trade_pay_response.sub_msg));
                        br.Level = ErrorLevel.Warning;
                        return(br);
                    }
                    else
                    {
                        br.Success = false;
                        br.Message.Add(string.Format("支付宝支付 操作返回失败! 描述:" + retPayModel.alipay_trade_pay_response.sub_msg));
                        return(br);
                    }
                }
            }
            catch (Exception ex)
            {
                br.Success = false;
                br.Message.Add(string.Format("支付宝支付时发生异常 单号:" + aliModel.out_trade_no + " 请查询确定结果 以免带来损失!"));
                br.Level = ErrorLevel.Warning;
                return(br);
            }
        }