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.MainModels;
using Newtonsoft.Json;

namespace MySystem
{
    public class AlipayFunction
    {
        private HttpContext _context;
        private string AppId = "2021004100667901";
        private string PrivateKey = "MIIEowIBAAKCAQEAhw2C7AypN/cSBNZU1LU2th58fzvLlhlfg7jZz3xNJQwpICtSF6hXXB2qChecEZv7ZGyiuuamTn/c+ZAKJAl3EZ8fMEgTrdK9M8+3DX6FIzWywCuPktsnxLIkTj4Lt/LjPI3P3yZLESuWzHIQ+TGnwEgm/Fx5ESWribFOddLRnNpINk36y+gtaVoXpQ742Wt6Yg1l4FZrzCAOHjLfVeTyAzmXXm8TGdzep83fyCqSBp+rdpb1CGQukHYpCapyk52hM4wqsAVdndAqO5qoRi5BfuyiVs2BR6Oe+8iF4rD5FJ/Wk6QguemWX8C/4jTnuNs1YsFuCTHqYwr8k8J6ekEdgwIDAQABAoIBAEob/PsBW56NYwLqhnSO2G4JvrGnI2nDlKlYt5VnFYI98RdpDkxTIVU4JgYRvJ/hI4uRHZ9IUHyFJ8J+60GpPACce+Xnt3zMRuz2j/HEutR+dA+GF+wzfNgwFUImRBH2JAIno6lFfy316HNaKLxGJlKahWI4cGsba81MUczQGhxi04XD9eVZNdeoRpt9eXTEuojjZIQB4JImHXI6jYxjhowP86D/hQ1lz78mC9mflSF0MC5gHtjdR0MScIKsewbJlRWpOw/UNuLXUoEjcXA4YXM1CPW4uSKpPm8j3S0eNT6vE8+DGViLrH5u5YxiLOlFMdkTsdyoq9teQDQl8eCW6skCgYEAxc8hbktBDnMLyEi+6JCzMDTQ5S16fhR8fjahXP5D+2gZZcNSu4X/Z5/WEWSHwH8YOGCXeXEujXe8bEy1dJ8B8c3KDDg2xU9NsxA9N1B4BHkva/3PzhzQGjST1OIYwLZAwMDJlQxtmUNT5Ab55i8AAEO5ew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e+8iF4rD5FJ/Wk6QguemWX8C/4jTnuNs1YsFuCTHqYwr8k8J6ekEdgwIDAQAB";
        public string AlipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxuS3Edgrruau8SO2DsK0f2KcE+A6pGJ1f8CdL395qwoX5RnEx9yRUotkwN0ZF6qMUojFKu/J/X2DpxBWBc6jIa+cnFwPUykefXcXj/AQsgiIbFzNXBH9NSz+hngXP6xDs8D1u9h+fJB+TYD+WFXKwOcGwcx23uHLHUDi1UIEZOhT2Eui+aMCYVygUWH7JynTtbFQZyZcSsD2Dxj5OJNJlK110jarFgvqY98WxqtaRtB9Y8whwRRlGfa5GP2r/Vt3xbGeAflRl5khFgRLZgeFIfxJpEj1TZV2tCtpFS0uhXJGEQbMnzFynx8UaOx/0hBCyik1MQuu3flym6nx7XxPSQIDAQAB";
        public AlipayFunction(HttpContext context)
        {
            _context = context;
        }
        public AlipayFunction()
        {
        }


        #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(string code)
        {
            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\":\"" + code + "\"" +
            "  }";
            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, decimal Amount, string BuyerId, string MerToken, string Notify_Url)
        {
            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);
            Dictionary<string, object> bizContent = new Dictionary<string, object>();
            bizContent.Add("out_trade_no", OrderNo);
            bizContent.Add("total_amount", Amount);
            bizContent.Add("subject", Subject);
            // bizContent.Add("seller_id", "2088641405724089");
            bizContent.Add("buyer_id", BuyerId);
            // bizContent.Add("buyer_open_id", BuyerId);
            bizContent.Add("timeout_express", "10m");

            // 结算信息，按需传入
            // Dictionary<string, object> settleInfo = new Dictionary<string, object>();
            // List<object> settleDetailInfos = new List<object>();
            // Dictionary<string, object> settleDetail = new Dictionary<string, object>();
            // settleDetail.Add("trans_in_type", "userId");
            // settleDetail.Add("trans_in", MerPid);
            // settleDetail.Add("amount", Amount);
            // settleDetailInfos.Add(settleDetail);
            // settleInfo.Add("settle_detail_infos", settleDetailInfos);
            // bizContent.Add("settle_info", settleInfo);

            string Contentjson = JsonConvert.SerializeObject(bizContent);
            request.BizContent = Contentjson;
            string result = "";
            try
            {
                AlipayTradeCreateResponse response = client.Execute(request, null, MerToken);
                result = response.Body;
                function.WriteLog(DateTime.Now.ToString() + "\n" + Contentjson + "\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 = "2021004100642805";
        //应用公钥
        // string PublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnTchC1mU0rFnRv8/eqDz1i/gS5Wd5fDD/TobKDBlj1UgQPRnT9g8wy/uTtqMnImR09ZQ5C/Ekw8B2GlN6bLbza0+7Fym7rNNKw3EvEL8tQ6pMe1GbIu68tCEjIslPXswGCgGRI30LeSj0BElaSAaqbvvyTHp+vxNLwav/hSGokPa8C76SzgCpvvzjXk9oGiNV5eutdoWEKbwyvw45kv70JHragNANTqU8DouzPLHenoD5V+QqJw1He9mZSb08QgSHCFW1dau8Hmxy0oXsfUVXXHJfzkhoyJOerYiR+oVuRqaIIF9xFlUPsNdpsAnJCP+HaAqRJpvuKfV4hNdg7uvIQIDAQAB";
        //支付宝公钥
        string MiniAlipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxuS3Edgrruau8SO2DsK0f2KcE+A6pGJ1f8CdL395qwoX5RnEx9yRUotkwN0ZF6qMUojFKu/J/X2DpxBWBc6jIa+cnFwPUykefXcXj/AQsgiIbFzNXBH9NSz+hngXP6xDs8D1u9h+fJB+TYD+WFXKwOcGwcx23uHLHUDi1UIEZOhT2Eui+aMCYVygUWH7JynTtbFQZyZcSsD2Dxj5OJNJlK110jarFgvqY98WxqtaRtB9Y8whwRRlGfa5GP2r/Vt3xbGeAflRl5khFgRLZgeFIfxJpEj1TZV2tCtpFS0uhXJGEQbMnzFynx8UaOx/0hBCyik1MQuu3flym6nx7XxPSQIDAQAB";
        string MiniPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmIK2EVxir9uspaS96y2giySdjv8jpekg8ZaLUluTv5DxbYbacAAVIxPs19yT2saFVhb3Qhwcx/03913J0v8DjEDQqiySZqV5y9z+C5NXGTGp5PyQK4q1wdAtg2TKkHlMRPrN/nhaFDEu6Hehoub1xEPm06qQU44A77yMnrZ5YJcS/Cv22lvcikVp6sThPmBMmmA+BF/v6hufYGWRlnWoAhl2lfmR9kSfuH1dGp/OT0WiDF7WD8ZR4iPAM8bpvBuq/UDiHBaZMJogtqkzBDH4EqiD+Tzg0ALn5zbSRiTk+GebjZNPkaW68v0LpyWOt8wbOmjh9EyaW4gEMOHxrJzZHwIDAQAB";
        //应用私钥
        string MiniPrivateKey = "MIIEowIBAAKCAQEAmIK2EVxir9uspaS96y2giySdjv8jpekg8ZaLUluTv5DxbYbacAAVIxPs19yT2saFVhb3Qhwcx/03913J0v8DjEDQqiySZqV5y9z+C5NXGTGp5PyQK4q1wdAtg2TKkHlMRPrN/nhaFDEu6Hehoub1xEPm06qQU44A77yMnrZ5YJcS/Cv22lvcikVp6sThPmBMmmA+BF/v6hufYGWRlnWoAhl2lfmR9kSfuH1dGp/OT0WiDF7WD8ZR4iPAM8bpvBuq/UDiHBaZMJogtqkzBDH4EqiD+Tzg0ALn5zbSRiTk+GebjZNPkaW68v0LpyWOt8wbOmjh9EyaW4gEMOHxrJzZHwIDAQABAoIBAARdmYCduGV4UFTdhmI5CCNzhN8XBpo1NjA0MwDEhlIxf/e2qIIUPoamh10Wf1T/4ck5FxLZYymGYhe+o4xaqGtXX6G/bOFrUzU2uj7ylMev2EEpyaa1bcaCgwsD05iXIEvJMiRapZl2XvVgl0vmeJqJpw3gEAmUQwqZxxyz9H2DSkPMaSqJFczM5vmOUCnf+gK5BTgO9H12r+IeoxfU1inu3tyuqlUAHbPmKFrQ4hJoiqHXMZKxddBxhSwfxkJj0494WErRsXdFqcu1CFtV8g2dXdrXCGsFq0cNl3Rq0sge/Q6otHrIIFLA7rRHEPe6Ub2uodQLpn0s+QTDC/nMVmECgYEAxwM5d63vht6FVIf4G1UnIOFqaPawpUmoxO2srNQtSlU+Jqi7aEXW4XNYihgZtIotmTaCHBwHrxPkdYI7kz2jn0WQmcnDjEwnARR1phOSJ+yCPUCbWMwQcorxaQn3gYu1ndoED87rqiUhTogyslTGvMeC7NIFnoLpWEn5UN7eQFsCgYEAxC6e2e1YF7vBwHHoYFvUwF57klBA9N9VMaw80mjGLuaTJwyxeFYH2QOpbeVs3upmfmmJSuOAVzg7QBkgBw0x6Wzrz831rCWGFRNZwDLnIP5h2G7SNmeNKe+HqV7M4jQ7Yelbgvgi/U6BedEyjfM4ekldBJkRsPP8QcWaeNeG5Y0CgYEAnZb4EsUxP2NFwUJKPZqYeXkGgkeWacyCUC7E5ba+hnYp2QMUI+Xp2m00V2XuNQCWSxTWwtuPWhwudL7D3jyZLK4xaxZSOu6ylDBXWUN2IRcvqsFWQmKVQ56yu7Kgw3yWPIE/ZiU8iGcOkNlZC84F8ccq7c0BlhukG724J0nURLECgYAWXTYwo7TqJ7ZDqPiTm4RaVasCl/F/uMHugrMATX9iM1jNF85XaH9GhvtWktPhaZk7ie5jwiGMT9W5TePvydpJwOf07Ya3FCP/3Q/bMDJW+YjP8no2R4G5KRwu+6ahltC6La8H9B+Q/tUVvPplYjerARgAgS6aHIZCPTOJ2RAAtQKBgGpJtAIZ8sE4wVCDwd1zuVTF40SkUeeoU6dRNVFV1Z++S4XHbjEGLf8ee95kpCv1jL1W70kh50zqSJP+3DnqOeTOvVudhTwBdtDd9YapmJMHh6vObP1WSXStq/LzULK2N8jxWiMJo32lE4HwsO3rH9aRe2ioObqo4zd+C6ZSzfqo";

        //小程序AES密钥，目前用于解密手机号
        string Key = "CxMrVGoYbx+XCEqGqJkP/A==";
        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);
                function.WriteLog(responseAccess_token.Body, "支付宝授权");
                string AlipayUserId = responseAccess_token.AlipayUserId; //20881043611849171819285350010300
                string UserId = responseAccess_token.UserId; //2088222145274001
                result = UserId + "|" + AlipayUserId;
                // JsonData jsonObj = JsonMapper.ToObject(responseAccess_token.Body);
                // result = jsonObj["alipay_system_oauth_token_response"]["open_id"].ToString();
            }
            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 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+nqfiX2co4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p6hV/6tfmpjMhV5DehHrg1vLdNGuqWgfyk+AwgS4uAL6CIJoahV1S7zmO0CgYBGMNtHyIsYbnYycat2SEOQOGbLAro+jRNDPCI3FGOf1fAOpXD9JgQMD7oXSRSnZRzwvsxNQ944UXqLrHPS5yEtcmAu6BdR1QjJlpj5ClRYuQuDK7k1LR3+0eI3FySbinAMspr6UVNo0UqUkLa2k/igH2yUyThIUDOiqkfuxsu/aA==";
            // set.AlipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxycehrmnTl2IaIAECP+0HWc1eWGM/T6x022K7K6fdf+xoyC97TBJaG4G3Bcon4gsJX+Sad5IA9OJIQ4eN1joM35hIlwcFZ6MmCuVXx/SMAKThIjK0jsRc6aTxVQG+GVCgS7dXMKb4Sm+vK2wEM6xtDeqcfYMB0BqGZRvxbIV59a2ooPrha4FkV6nNC9DQefzC0picHXV64oYUjMM2ed4ASTQVds7HP9BZfalz//APZcWdBV08f+xv7n79Twz/gNtVAadfuTAlcjsS6aK+G/OrZtr/diuemeRPRUKlVhcr5xOQDhqBgtdIw8M9Wp6I4ULXRlthKVBWToH9j6n9vDIiwIDAQAB";
        
            // set.AlipayAppId = "2021003126605468";
            // set.AlipayPrivateKey = "MIIEogIBAAKCAQEA1O3mknrWGkWsDiojx/hUgq5jnO/D8rjMGUpz8C7A88iJmm6ZSxssTz2+OkL75omlxRJcMZAYt+icZtLWVm6mSklCipieWZGEWiId6bsHwlEPOkwmhPw5bDBF+y6ZSkXtW+fofrmsk8/a9SZ/N3h+FJ5sqLbihn9pXNp4X1VgnZHGGNWsRTFgBdWdEWAEhDImAPNRv8IB7ZyVbbRo3aIvTCH4EDUu8Y5IMs8l5Ne0aUAkPgz81IbiSMzWqU5z9W5m1cPIOz/w5Bru/JvJliu2qkQrDlh9ccIcBIsrOddYAzxyXsxO+EqUM/m9HEtg5atvMIV9XMzgwnGpM3jVydRBywIDAQABAoIBAAdaO6b9NN1tYHaQv/GM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8Tk5M/WZkzGYTj7mrp0A7BXXRWMjnbrhq3W15P1Q45aU64NofOcQvX3LdKkpEWHYXktJaSKBlZgjSQVK7ZntF6LJCiMcQ0=";
            // set.AlipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnw14hKejqS+si/XZpNQpFAVOVXJIThj5Qn7H14n/vsb7uRLug1+Jcve8ehTkaN3s5ibrrELCnz0dvshi3cOz9svDSbLG5OdC1biAvZzpDkvVPswOd9f9jO8Jvqk3QTXTI3MSN9gOpKomI0te3qs5kkOQx6kRozzKjU/G//o/PbJCxpBxf/QNRV3XmCwJLZMBE7ukYqi1WO9Jra8jdczFKwrd/nhiKBKdupAtVVeKlylGD2i2YLkGAH1cLsPUN9DtzrXNblGXm2HK3l9SnMDjqnakiVdEQJTNYNpEiHaOJsVmPQL38nM6miz5wNd4gTchKzXPtoZWqto+eIvYaEA/KwIDAQAB";
            return set;
        }
    }
}
