using System;
using System.Collections.Generic;
using System.Linq;
using Aop.Api;
using Library;
using LitJson;
using Microsoft.AspNetCore.Http;
using Aop.Api.Request;
using Aop.Api.Response;
using Aop.Api.Util;
using System.Collections;
using MySystem.Models.KxsMainModels;

namespace MySystem
{
    public class AlipayFunctionForKxs
    {
        private HttpContext _context;
        private string AppId = "2021003116616751";
        private string PrivateKey = "MIIEpAIBAAKCAQEA1KjMzZJIRG6QQ3+c/euVrc+8RR0xMw6A+EONSKhJq4Bg+rtxQPCfdF2bpZ4NMaSqfalSiLoxrZSYBYOZhpDP67i9LXGUoFCWdRL7ROTqJvuU6KyEeMplQ6Q3uwWbuKbh9COt0vhqn/pjlUsomTwq+DRQv10awynkZikqceXdP0EH4iGZG0hyerEP5yLHpHiggf4f7TOsovHX+fGLPmWFO1zUTHHbz7HxU4BQKn3yuje4yMhoyv5h/wZzeVwvj+Qti8Hlh351rF0f5BHwN1YMGIrWuPU5bF8OMHS/UXPxh7Bs795ZZyplYztTz26QfKfLWVVsLOng4pvgPS+OgzZydwIDAQABAoIBAEu6mMQT9Zw46zK+PP/HZxPwSBEsphqSbab7F1LqauGh4+cl3NzNU1szAnxl3jjxdK0vIO8DrzErGz/Lb16WLxS4QtXt/olgaVPjoIsWIbQkHxEEbmA9YvZFgnsdMij9dLVmBz57rCywE8pUa262GG8u4hpjY2Zggq9GtZC91J3zOeETBG828gU+FLHGcDpfz7pD1jC0noDfDRxmIImOMZvChIvvY+tm6MpySXN8lw1vxhLc0aZbKSQkuVyCyB4fIsdJJvh2dRPiY+BA0jXNK3mWwnnHzac/9JXqWFlwk6iPIIjXPUldz7Zq3EpCI+9p+UqLtIu6BAUbk1biFTt8xMECgYEA+2iIxZfdl1N1suA/aEbUdjd0kxeeOsGv7Ps0rOYn+4/q1dkUukg2V6VRy3E8BUt+9zLPTR8DmL7oBi+kDsGehjHlH7U6Pe8qKszB4ufQBDHc71yg9liqOWa4s9VoBD0VIU9CO0HtYjRor7rVuUzp+j58SLP7wIEPGE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YztTz26QfKfLWVVsLOng4pvgPS+OgzZydwIDAQAB";
        private string AlipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxycehrmnTl2IaIAECP+0HWc1eWGM/T6x022K7K6fdf+xoyC97TBJaG4G3Bcon4gsJX+Sad5IA9OJIQ4eN1joM35hIlwcFZ6MmCuVXx/SMAKThIjK0jsRc6aTxVQG+GVCgS7dXMKb4Sm+vK2wEM6xtDeqcfYMB0BqGZRvxbIV59a2ooPrha4FkV6nNC9DQefzC0picHXV64oYUjMM2ed4ASTQVds7HP9BZfalz//APZcWdBV08f+xv7n79Twz/gNtVAadfuTAlcjsS6aK+G/OrZtr/diuemeRPRUKlVhcr5xOQDhqBgtdIw8M9Wp6I4ULXRlthKVBWToH9j6n9vDIiwIDAQAB";
        public AlipayFunctionForKxs(HttpContext context)
        {
            _context = context;
        }


        #region 代商家签约

        //（开启事务）接口创建应用事务，返回生成代商户操作事务编号 batch_no
        public string GetBatchNo(string AlipayAccount, string Name, string Mobile, string Email)
        {
            IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", AppId, PrivateKey, "json", "1.0", "RSA2", AlipayPublicKey, "utf-8", false);
            AlipayOpenAgentCreateRequest request = new AlipayOpenAgentCreateRequest();
            request.BizContent = "{" +
            "\"account\":\"" + AlipayAccount + "\"," +
            "\"contact_info\":{" +
            "\"contact_name\":\"" + Name + "\"," +
            "\"contact_mobile\":\"" + Mobile + "\"," +
            "\"contact_email\":\"" + Email + "\"" +
            "}" +
            "}";
            string result = "";
            try
            {
                AlipayOpenAgentCreateResponse response = client.Execute(request);
                result = response.Body;
                //{"alipay_open_agent_create_response":{"code":"10000","msg":"Success","batch_no":"2022021011321326200059849","batch_status":"init"},"sign":"su+weyK1CZEXES8mdckalg16J4BELTQeVNJSpXVYg3nh5g3E7jDh/mQctkjH8HbM0RybQSahZ2j60aUTossPMXqdq2nPRkR4c/kM34toFFNU/2p7jqo9k/MbB1JotW+qFI+C/GCX/9mZQqm2tSQdYIiZlCsEtP13ZP2EQ6momEZrApyLQYUl1H54PojJgqo6zGKDXTnXuZcpi/VPP5YoWhYMx8WPFMS6+T3zr+LNPDOI94j5vDdUHQdjFAGiQMyyhfNOBcFFi18bAfWhPqlLWwblCZamTHN/QaOHo+fkBZeo9uKqrnSHPn8XW0tDAIf1qNUfY2eBzYZUIqWKbz509A=="}
            }
            catch (Exception ex)
            {
                function.WriteLog(ex.ToString(), "接口创建应用事务异常");
                result = "";
            }
            return result;
        }
        //代签约产品通用接口，代商家发起签约产品申请
        public string CommonSign(string BatchNo, string MccCode, string BusinessLicenseNo = "", string BusinessLicensePicPath = "", string ShopScenePicPath = "", string ShopSignBoardPicPath = "")
        { 
            IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", AppId, PrivateKey, "json", "1.0", "RSA2", AlipayPublicKey, "utf-8", false);
            AlipayOpenAgentCommonSignRequest request = new AlipayOpenAgentCommonSignRequest();
            request.BatchNo = BatchNo;
            request.MccCode = MccCode; //软件系统商 D_D05_7372
            FileItem SpecialLicensePic = new FileItem(BusinessLicensePicPath);
            request.SpecialLicensePic = SpecialLicensePic;
            if (!string.IsNullOrEmpty(BusinessLicenseNo))
            {
                request.BusinessLicenseNo = BusinessLicenseNo;  //营业执照号码
            }
            if (!string.IsNullOrEmpty(BusinessLicensePicPath))
            {
                FileItem BusinessLicensePic = new FileItem(BusinessLicensePicPath);
                request.BusinessLicensePic = BusinessLicensePic; //营业执照图片。被代创建商户运营主体为个人账户必填，企业账户无需填写
            }
            FileItem BusinessLicenseAuthPic = new FileItem(BusinessLicensePicPath);
            request.BusinessLicenseAuthPic = BusinessLicenseAuthPic;
            request.LongTerm = true;
            request.DateLimitation = "长期";
            if (!string.IsNullOrEmpty(ShopScenePicPath))
            {
                FileItem ShopScenePic = new FileItem(ShopScenePicPath);
                request.ShopScenePic = ShopScenePic;
            }
            if (!string.IsNullOrEmpty(ShopSignBoardPicPath))
            {
                FileItem ShopSignBoardPic = new FileItem(ShopSignBoardPicPath);
                request.ShopSignBoardPic = ShopSignBoardPic;
            }
            request.ProductCode = "QUICK_WAP_WAY"; //isv要代商户签约产品码，产品码是支付宝内部对产品的唯一标识
            request.AppName = "客小爽";
            // FileItem AppDemo = new FileItem(BusinessLicensePicPath);
            // request.AppDemo = AppDemo;
            List<string> WebSites = new List<string>();
            WebSites.Add("www.kexiaoshuang.com");
            request.WebSites = WebSites;
            request.AlipayLifeName = "客小爽";
            request.WechatOfficialAccountName = "客小爽";
            // FileItem WebSitesLoa = new FileItem(BusinessLicensePicPath);
            // request.WebSitesLoa = WebSitesLoa;
            request.WebTestAccount = "testAccount";
            request.WebTestAccountPassword = "testPassword";
            FileItem WebHomeScreenshot = new FileItem(BusinessLicensePicPath);
            request.WebHomeScreenshot = WebHomeScreenshot;
            FileItem WebItemScreenshot = new FileItem(BusinessLicensePicPath);
            request.WebItemScreenshot = WebItemScreenshot;
            FileItem WebPayScreenshot = new FileItem(BusinessLicensePicPath);
            request.WebPayScreenshot = WebPayScreenshot;
            request.WebStatus = "已上线";
            string result = "";
            try
            {
                AlipayOpenAgentCommonSignResponse response = client.Execute(request);
                result = response.Body;
                //{"alipay_open_agent_common_sign_response":{"code":"10000","msg":"Success"},"sign":"qt0DiXFXIJ7mX+W2+IX+cyYXx8ROGe8yxesXHGNltxpEv/s/zW16xzf4HQLtUlaAiWf3DiD2QV7Hj+REyoZw9AcktDAmlobcjQ28lTYufPECZoUJHpkn9VpGB932FC0hScVwCbsxQakH84MGT4cmjr1hCuSs7+XogdhlCTIKjau1e7ZglLnt7f1NqT8JnljVhmvkkE9gJTLq5H+Zq6XbFfBVptvM9w09HdjfhrsxAXJyQ4yU6JYX2tUYsRGz8ZrveDQMvXKTN9jnwKE9hh8ik6Sq49eUqfutV9GkKqhC96+Vy3nOTOTnPoECXZkco1wP5jsqHottWVsRV+NxdylnTw=="}
            }
            catch (Exception ex)
            {
                function.WriteLog(ex.ToString(), "代签约产品通用接口异常");
                result = "";
            }
            return result;
        }
        //代商户签约，提交信息确认接口
        public string CommonSignConfirm(string BatchNo)
        {
            IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", AppId, PrivateKey, "json", "1.0", "RSA2", AlipayPublicKey, "utf-8", false);
            AlipayOpenAgentCommonsignConfirmRequest request= new AlipayOpenAgentCommonsignConfirmRequest();
            request.BizContent="{" +
            "\"batch_no\":\"" + BatchNo + "\"" +
            "}";
            string result = "";
            try
            {
                AlipayOpenAgentCommonsignConfirmResponse response = client.Execute(request);
                result = response.Body;
                //{"alipay_open_agent_order_query_response":{"code":"10000","msg":"Success","order_no":"20220210034000100000015895929361","product_agent_status_infos":[{"product_code":"QUICK_WAP_WAY","product_name":"手机网站支付","status":"WAIT_CONFIRM"}],"order_status":"MERCHANT_CONFIRM","confirm_url":"https:\/\/openhome.alipay.com\/isv\/settling\/confirm.htm?orderNo=20220210034000100000015895929361","merchant_pid":"2088012934025363"},"sign":"mgdhauHMV9352S3FVrQmesXvHOrk633FX/EOXRYdc2ix5phCBZJ2KZRRP9MWJ566YEtWbnQlAJzHVS9X29hjgiJWOQ/wCidql4AoSAYYeqPtxiqKAZw/QEM/du5AdbWC0xBmmkQljXF9Hx8cm+IrOyPMSJXIw4Tqpm/T96YBwhsjw4Xr5dcUcvF6HX9h/i5FSdIJODxQ26PJcqQ98GQ3Y50YhTpPQkIPDFVE2QzcL6dvuhBOpwu5KbTxvgzS8Wtm3G6nMbzJ33Cv/I2lhTCIMHz90c9bvyjJpWxPWBzywO2zzv7+EZCbDkZGkdRic9l5s6qac+ZVMHkPbveaZ2wyig=="}
            }
            catch (Exception ex)
            {
                function.WriteLog(ex.ToString(), "接口创建应用事务异常");
                result = "";
            }
            return result;
        }

        #endregion

        #region （查询申请单状态）查询签约申请的结果
        public string QuerySignStatus(string BatchNo)
        {
            IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", AppId, PrivateKey, "json", "1.0", "RSA2", AlipayPublicKey, "utf-8", false);
            AlipayOpenAgentOrderQueryRequest  request= new AlipayOpenAgentOrderQueryRequest() ;
            request.BizContent="{" +
            "  \"batch_no\":\"" + BatchNo + "\"" +
            "}";
            string result = "";
            try
            {
                AlipayOpenAgentOrderQueryResponse response = client.Execute(request);
                result = response.Body;
            }
            catch (Exception ex)
            {
                function.WriteLog(ex.ToString(), "查询签约申请的结果异常");
                result = "";
            }
            return result;
        }

        #endregion
        
        #region 小程序支付请调用MySystemLib下的统一收单交易创建，返回交易号返给小程序请求支付my.tradePay
        public string GetToken()
        {
            IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", AppId, PrivateKey, "json", "1.0", "RSA2", AlipayPublicKey, "utf-8", false);
            AlipayOpenAuthTokenAppRequest request = new AlipayOpenAuthTokenAppRequest();
            request.BizContent = "{" +
            "\"grant_type\":\"authorization_code\"," +
            "\"code\":\"P16be77ee92264acc99553528b8a7103\"" +
            "  }";
            string result = "";
            try
            {
                AlipayOpenAuthTokenAppResponse response = client.Execute(request);
                result = response.Body;
                //{"alipay_open_auth_token_app_response":{"code":"10000","msg":"Success","tokens":[{"app_auth_token":"202202BBd8c1365cd09b4a27a0c0f0b7f8cabX03","app_refresh_token":"202202BB539f0f5aa99f4b509aa3628b0af25X03","auth_app_id":"2021003116654736","expires_in":31536000,"re_expires_in":32140800,"user_id":"2088141704579033"}]},"sign":"VZINXguZZFvVDyhVp/iMK5BWXYnDYLvxYEMEZTZOVUl9MUy6xQesDzpwBBUclLLU+QgrKpeekaxj9zgwRXdh7cKlVot2lkVPkGdfkqcK/B9t8kxPXa13WIszcROCqIutlcBZW9pCIUAbWRjorDvzRCc5rLNfSBAjEldZDA0rGOPeWJXM/5uLi/70oTwyO6eaEbKdRyHLjUwp0qtolhXIvyf9HL1HbZMGtyY/Hzq35BmhB/jQ4XIVdcOEpFtNoC/1S/viLOsBCD2m4aNCGUY0i24lr92dRsEinZlCxAQq+FK6ILNUnDmBUjNkPTycDrJFw+w9sEC6AcZodNB6OC8XTw=="}
            }
            catch (Exception ex)
            {
                function.WriteLog(ex.ToString(), "支付宝统一收单交易创建(获取authtoken)异常");
                result = "";
            }
            return result;
        }

        public string CreateTrade(string OrderNo, string Subject, string Amount, string BuyerId, string Notify_Url, string Token)
        {
            IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", AppId, PrivateKey, "json", "1.0", "RSA2", AlipayPublicKey, "utf-8", false);
            AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
            request.SetNotifyUrl(Notify_Url);
            request.BizContent = "{" +
            "\"out_trade_no\":\"" + OrderNo + "\"," +
            "\"total_amount\":" + Amount + "," +
            "\"subject\":\"" + Subject + "\"," +
            "\"buyer_id\":\"" + BuyerId + "\"," +
            "\"timeout_express\":\"10m\"" +
            "}";
            string result = "";
            try
            {
                AlipayTradeCreateResponse response = client.Execute(request, null, Token);
                result = response.Body;
                function.WriteLog(DateTime.Now.ToString() + "\n" + result, "支付宝统一收单交易创建");
            }
            catch (Exception ex)
            {
                function.WriteLog(ex.ToString(), "支付宝统一收单交易创建异常");
                result = "";
            }
            return result;
        }

        public string QueryTrade(string OrderNo, string Token)
        {
            IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", AppId, PrivateKey, "json", "1.0", "RSA2", AlipayPublicKey, "utf-8", false);
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            request.BizContent = "{" +
            "\"out_trade_no\":\"" + OrderNo + "\"" +
            "}";
            string result = "";
            try
            {
                AlipayTradeQueryResponse response = client.Execute(request, null, Token);
                result = response.Body;
            }
            catch (Exception ex)
            {
                function.WriteLog(ex.ToString(), "统一收单线下交易查询异常");
                result = "";
            }
            return result;
        }

        #endregion









        //小程序
        string MiniAppId = "2021003116654736";
        //应用公钥
        // string PublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnTchC1mU0rFnRv8/eqDz1i/gS5Wd5fDD/TobKDBlj1UgQPRnT9g8wy/uTtqMnImR09ZQ5C/Ekw8B2GlN6bLbza0+7Fym7rNNKw3EvEL8tQ6pMe1GbIu68tCEjIslPXswGCgGRI30LeSj0BElaSAaqbvvyTHp+vxNLwav/hSGokPa8C76SzgCpvvzjXk9oGiNV5eutdoWEKbwyvw45kv70JHragNANTqU8DouzPLHenoD5V+QqJw1He9mZSb08QgSHCFW1dau8Hmxy0oXsfUVXXHJfzkhoyJOerYiR+oVuRqaIIF9xFlUPsNdpsAnJCP+HaAqRJpvuKfV4hNdg7uvIQIDAQAB";
        //支付宝公钥
        string MiniAlipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxycehrmnTl2IaIAECP+0HWc1eWGM/T6x022K7K6fdf+xoyC97TBJaG4G3Bcon4gsJX+Sad5IA9OJIQ4eN1joM35hIlwcFZ6MmCuVXx/SMAKThIjK0jsRc6aTxVQG+GVCgS7dXMKb4Sm+vK2wEM6xtDeqcfYMB0BqGZRvxbIV59a2ooPrha4FkV6nNC9DQefzC0picHXV64oYUjMM2ed4ASTQVds7HP9BZfalz//APZcWdBV08f+xv7n79Twz/gNtVAadfuTAlcjsS6aK+G/OrZtr/diuemeRPRUKlVhcr5xOQDhqBgtdIw8M9Wp6I4ULXRlthKVBWToH9j6n9vDIiwIDAQAB";
        //应用私钥
        string MiniPrivateKey = "MIIEogIBAAKCAQEAnTchC1mU0rFnRv8/eqDz1i/gS5Wd5fDD/TobKDBlj1UgQPRnT9g8wy/uTtqMnImR09ZQ5C/Ekw8B2GlN6bLbza0+7Fym7rNNKw3EvEL8tQ6pMe1GbIu68tCEjIslPXswGCgGRI30LeSj0BElaSAaqbvvyTHp+vxNLwav/hSGokPa8C76SzgCpvvzjXk9oGiNV5eutdoWEKbwyvw45kv70JHragNANTqU8DouzPLHenoD5V+QqJw1He9mZSb08QgSHCFW1dau8Hmxy0oXsfUVXXHJfzkhoyJOerYiR+oVuRqaIIF9xFlUPsNdpsAnJCP+HaAqRJpvuKfV4hNdg7uvIQIDAQ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JBdyqbq+UighHXQD0wci8b3E35SsR/QqDAvOgEpKhmjrt63KcfdJax4VztPwroKRTz+Iy/HwGcBSVwnUn8XPTlHFkTufUtPScWuYjSXTJ+MyIMif2rcaJubvSGyZOKNMbcvAQx5tnNbF5SrVU=";

        //小程序AES密钥，目前用于解密手机号
        string Key = "2Krm6dSew4NAL+l0mQf0fA==";
        public string GetAlipayUserId(string Auth_code)
        {
            string result = "";
            try
            {
                IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", MiniAppId, MiniPrivateKey, "json", "1.0", "RSA2", MiniAlipayPublicKey, "UTF-8", false);
                //获取access_token
                AlipaySystemOauthTokenRequest requestAccess_token = new AlipaySystemOauthTokenRequest();
                requestAccess_token.GrantType = "authorization_code";
                requestAccess_token.Code = Auth_code;
                AlipaySystemOauthTokenResponse responseAccess_token = client.Execute(requestAccess_token);
                string AlipayUserId = responseAccess_token.AlipayUserId; //20881043611849171819285350010300
                string UserId = responseAccess_token.UserId; //2088222145274001
                result = UserId + "|" + AlipayUserId;
            }
            catch (Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "支付宝授权报错日志");
            }
            return result;
        }


        public string GetAlipayMobile(string response)
        {
            function.WriteLog(response, "解密报文");
            //1. 获取验签和解密所需要的参数
            IDictionary openapiResult = Jayrock.Json.Conversion.JsonConvert.Import(response) as IDictionary;
            string signType;
            if (openapiResult.Contains("sign_type"))
            {
                signType = openapiResult["sign_type"].ToString();
            }
            else
            {
                signType = "RSA2";
            }
            string charset;
            if (openapiResult.Contains("charset"))
            {
                charset = openapiResult["charset"].ToString();
            }
            else
            {
                charset = "UTF-8";
            }
            string encryptType;
            if (openapiResult.Contains("encrypt_type"))
            {
                encryptType = openapiResult["encrypt_type"].ToString();
            }
            else
            {
                encryptType = "AES";
            }
            string sign = openapiResult["sign"].ToString();
            string content = openapiResult["response"].ToString();
            // 是否为加密报文
            bool isDataEncrypted = !content.StartsWith("{", StringComparison.Ordinal);
            // bool signCheckPass = false;
            //2. 验签
            string signContent = content;
            signContent = "\"" + signContent + "\"";
            string signVeriKey = MiniAlipayPublicKey;
            string decryptKey = MiniPrivateKey;
            string result = "";
            try
            {
                function.WriteLog(content, "解密报文");
                result = AlipayEncrypt.AesDencrypt(Key, content, charset);
                JsonData obj = JsonMapper.ToObject(result);
                if (obj["code"].ToString() == "10000")
                {
                    result = "success|" + obj["mobile"].ToString();
                }
                //{\"code\":\"10000\",\"msg\":\"Success\",\"mobile\":\"14781419364\"}
            }
            catch (Exception ex)
            {
                //解密异常, 记录日志        
                function.WriteLog(ex.ToString(), "获取手机号解密异常");
            }
            return result;
            // 如果是加密的报文则需要在密文的前后添加双引号
            // if (isDataEncrypted)
            // {
            //     signContent = "\"" + signContent + "\"";
            // }
            // try
            // {
            //     signContent = signContent.Trim('"');
            //     signCheckPass = AlipaySignature.RSACheckContent(signContent, sign, signVeriKey, charset, signType);
            // }
            // catch (Exception ex)
            // {
            //     //验签异常, 日志    
            //     throw new Exception("验签失败", ex);
            // }
            // if (!signCheckPass)
            // {
            //     //验签不通过（异常或者报文被篡改），终止流程（不需要做解密）   
            //     throw new Exception("验签失败");
            // }
            // //3. 解密
            // string plainData = null;
            // if (isDataEncrypted)
            // {
            //     try
            //     {
            //         plainData = AlipayEncrypt.AesDencrypt(decryptKey, content, charset);
            //     }
            //     catch (Exception ex)
            //     {
            //         //解密异常, 记录日志        
            //         throw new Exception("解密异常", ex);
            //     }
            // }
            // else
            // {
            //     plainData = content;
            // }
            // return result;
        }

        public string test()
        {
            string result = "";
            string str = "PsQMXBobiYsZPG5q2dbsX5Zvnee73Zpg55guE2FTxMijl+xdj+oCjEErUpZNxRK0S132GVcWBQUjFeA5fcLq1A==";
            try
            {
                result = AlipayEncrypt.AesDencrypt(Key, str, "UTF-8");
                JsonData obj = JsonMapper.ToObject(result);
                if (obj["code"].ToString() == "10000")
                {
                    result = "success|" + obj["mobile"].ToString();
                }
                //{\"code\":\"10000\",\"msg\":\"Success\",\"mobile\":\"14781419364\"}
            }
            catch (Exception ex)
            {
                //解密异常, 记录日志        
                function.WriteLog(ex.ToString(), "获取手机号解密异常");
            }
            return result;
        }















        // 支付宝参数
        public PublicAccountSet SetData(int UserId = 0)
        {
            WebCMSEntities db = new WebCMSEntities();
            PublicAccountSet set = db.PublicAccountSet.FirstOrDefault() ?? new PublicAccountSet();
            // set.AlipayAppId = "2021003122642236";
            // set.AlipayPrivateKey = "MIIEpAIBAAKCAQEAmfSplznW6H+wCyKh806jBxVdRabpK2P9RP4QNSGsHNIAscuH2yPbI1dNfKESC+QXAfWVRg90Vb+7yQz1I/S2vT159yY7ZH6duCopPpScfpNmICtjVukc1V5PZX+ptuDZc0YQSsRnn5WVKNO0bBR6iS3Jl9HQT949I3rHttA1+iqBn2LWyvGcUSDCOFNwstOYFM3FJTg7rQEdjmEQonEPXSbTQl1aw+fx1D+NcGx9BFSVAbE+nqfiX2co4V6yQ++N1RMlnBtbMZmTgvcoHZujqqBmjRcfRUW8I0B9aPJGNji94STBRPf0hP7yN4PHP2LixAK5gfzZ5NP2iK99sQ9tmwIDAQABAoIBAAR0N5PQcI85YnZwAg9v7vd9fr1NHuHKesFMOFvRJZGP4cVDBiMo3mYfWHaKkmMVrjS4TiFAwTTZ3yzp2w23PrIq3SRxTraRky6Iybitw/lFembj2nPhOpxRpiphjx9jUecr17zSAc10HmSX+1hFH2ZolLR3tXcaDtq/6pc3Xthl5uT0HIkisgbgxG5M8B+x26ZWnu8pbk+nT9bsAh9LrkQX+xaxTCgpmWpUTFMhG2t9pl04jT/LPOWXCmrs1BYEadqMirivcZdAXEiRbisSVrDI8cGKvPZpNZU9jfg9W5DEgfUdhnaZfRZzeAWORrBogXV1Osjlcjh2XXA3pAzCP8ECgYEA1jKv/S4RVCswh5LZTVFqVTAVyMBL/nLSu1L4mgaim19QDINxCDpN8kOfIBIBatwvkg7HzzQquotbDqj8pKgCFHTyf5gof6iFA1uGGP6AYBdL0k5tAG+uKwpo9rtRAUlO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uemeRPRUKlVhcr5xOQDhqBgtdIw8M9Wp6I4ULXRlthKVBWToH9j6n9vDIiwIDAQAB";
        
            // set.AlipayAppId = "2021003126605468";
            // set.AlipayPrivateKey = "MIIEogIBAAKCAQEA1O3mknrWGkWsDiojx/hUgq5jnO/D8rjMGUpz8C7A88iJmm6ZSxssTz2+OkL75omlxRJcMZAYt+icZtLWVm6mSklCipieWZGEWiId6bsHwlEPOkwmhPw5bDBF+y6ZSkXtW+fofrmsk8/a9SZ/N3h+FJ5sqLbihn9pXNp4X1VgnZHGGNWsRTFgBdWdEWAEhDImAPNRv8IB7ZyVbbRo3aIvTCH4EDUu8Y5IMs8l5Ne0aUAkPgz81IbiSMzWqU5z9W5m1cPIOz/w5Bru/JvJliu2qkQrDlh9ccIcBIsrOddYAzxyXsxO+EqUM/m9HEtg5atvMIV9XMzgwnGpM3jVydRBywIDAQABAoIBAAdaO6b9NN1tYHaQv/GMwqZMjUYDBXohJXMOHhjCFImWeCHsBcERLCOEV0g9veMFB8NZUfOoLSJUlun6B8quQXG5O+H7SSSAoNhX6z6B5c+w6tyxencHGpiAxjnZLxPgfES7Kk0N7kagW8gxTx1EPN5LZichQYsxZRr+tD9efFqUeOnutUjECdvYNb6FsJ46tgCVRSEl7kBueR+VmFl5FXjc7B3bREGzaNylu846BK4vK6u1/IKIDczJKfZDRtwSpvMPUGwscfZAkPHOxtneKCyB1itouUyrhjaBb9AJMKIaCi7j5btazo81B3BZVK9uHV+B+gVA3d+aWwSteU9WMukCgYEA6bk0ua6285e/N6YC5KvqRTaangjtSJckx3FRVuK6799mIDyyvScz6Befi/EJ0kwF0J0HPI+GKGa7XWzk1CR4pz1Zd85uzL8TIcn9AHqjeYe62hKLSPQMlR+GTP/J604rHERlGVoo7LEHT7MrVmQhTJWmJGezldPpmwbuKoWgel8CgYEA6TlShy3qO5LYVmd360BRWrR7k6cZkkTaC/ivjLZNENLXG7nJeUKkS4LaexLu7RB2L45IWzDqhCrPqfG5P/XkxvskkzntEUmChN58xhfpS20yeTpfDhjvdbJEEYgbmkNqOD8L2Q25XRMAJ8vomzgIEIw9aDQCM3ZBK1s0zyXwyBUCgYARqthbeOOHgl8H+9qYIo6w8LG7ZH1bUWGMWfqGENmErGRx52Sze7UmxDJhR7UwWmLOJDCZ2VeQ0kMzirm5d5BPRAnxTn99pqvxj+06DgsxcpsjROeWeixBUYK7a1J+IQiNOHZT9kbFrZQZ6DdMboE94soOUnB20PAFsf5q5HL/DQKBgHXVmHTkJexjjRpavKQHoxMJDUbUrn7QerqBs3CMyvMtE7HWdIzntsrQGkMEleMA5jWw1a39UP/mAXYDw20ld6lxSlF4eua5FVC8eJ49homtaksFyvD8eEAnCW0yL4AJf6lbcUkBPh5gczuoMqX58VkrAfucC2Ck5thZBJ2EtdrhAoGAVeQbC4m789Yr+kXKPECGxI7RwIVV5xjc3TCvfE6JKztmn0IZyWT53vqvxi2LpqeAMlwc8PrCpiqd/8Tk5M/WZkzGYTj7mrp0A7BXXRWMjnbrhq3W15P1Q45aU64NofOcQvX3LdKkpEWHYXktJaSKBlZgjSQVK7ZntF6LJCiMcQ0=";
            // set.AlipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnw14hKejqS+si/XZpNQpFAVOVXJIThj5Qn7H14n/vsb7uRLug1+Jcve8ehTkaN3s5ibrrELCnz0dvshi3cOz9svDSbLG5OdC1biAvZzpDkvVPswOd9f9jO8Jvqk3QTXTI3MSN9gOpKomI0te3qs5kkOQx6kRozzKjU/G//o/PbJCxpBxf/QNRV3XmCwJLZMBE7ukYqi1WO9Jra8jdczFKwrd/nhiKBKdupAtVVeKlylGD2i2YLkGAH1cLsPUN9DtzrXNblGXm2HK3l9SnMDjqnakiVdEQJTNYNpEiHaOJsVmPQL38nM6miz5wNd4gTchKzXPtoZWqto+eIvYaEA/KwIDAQAB";
            return set;
        }
    }
}
