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

namespace MySystem
{
    public class AlipayFunction
    {
        public readonly static AlipayFunction Instance = new AlipayFunction();
        private AlipayFunction()
        { }

        public string Pid = "2088720140260314";
        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/3PzhzQGjST1OIYwLZAwMDJlQxtmUNT5Ab55i8AAEO5ewi4Rq+Y3PKNeQ0a7gcCgYEArsg+nFa+8ekZsiFkl/IAe5EsJhl/NPrPhXPHsjp2y1CK3Zg2Y1hOYjBLnIi6ID6l+6uYwVKoe/UOphnIBuw9WkfdojrLAmDCge3eiXTrYTj5XnKMZZon3xDHnuEB5dTMZG2hW3BJfYUDdNYkjWmUoKD+1LmDztpDBiLC6Ubf9aUCgYAOctG7T63h009yArZHIIKmK8VyZ/8BhJePVIg21a+7hmAMidbaMbB1Ljyhqpkr21y2iX+m9Dh1RuCxfGzoptCqi+CNQfHmOaOwR6hhCPSrRvrKxZBPOtWMhHij3Rv3v5g9PBe9VloPDtbq2gOY56f1XP0IWpuzNhJRWToyNF3aMwKBgHu39snHhYXLUIsMpB4CCWFuU2fsqGSiHP8EA5kfVTN5obJVqjoMKf/K29rD1aw5bFiHEKvXjLehsWrV2Qc9dfhP4oyRPV5Di6tY6ys1fd/l6m52evb4dbyqLgNClotPZBa6m3sUMpEM9HNhmaIX2EMTcw60+p4TVVokhP+HUcSZAoGBAJkkJ1uPuKEq79zeqNEfDHFZHW+4YzT4xDlq0vm5YYhphcyr80Z0jLzGgmoRHKTfDwBHYF5TXdUsWgJEGx9jucPi0jFkK6HDAerUqG4WJc8iu+93pyYYfPIszWHEwzxEutjpUnU2HpXLMhgUXQrwSWrQpHTkuPMY8ZCQwKZ4TBMV";
        private string PublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhw2C7AypN/cSBNZU1LU2th58fzvLlhlfg7jZz3xNJQwpICtSF6hXXB2qChecEZv7ZGyiuuamTn/c+ZAKJAl3EZ8fMEgTrdK9M8+3DX6FIzWywCuPktsnxLIkTj4Lt/LjPI3P3yZLESuWzHIQ+TGnwEgm/Fx5ESWribFOddLRnNpINk36y+gtaVoXpQ742Wt6Yg1l4FZrzCAOHjLfVeTyAzmXXm8TGdzep83fyCqSBp+rdpb1CGQukHYpCapyk52hM4wqsAVdndAqO5qoRi5BfuyiVs2BR6Oe+8iF4rD5FJ/Wk6QguemWX8C/4jTnuNs1YsFuCTHqYwr8k8J6ekEdgwIDAQAB";
        public string AlipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxuS3Edgrruau8SO2DsK0f2KcE+A6pGJ1f8CdL395qwoX5RnEx9yRUotkwN0ZF6qMUojFKu/J/X2DpxBWBc6jIa+cnFwPUykefXcXj/AQsgiIbFzNXBH9NSz+hngXP6xDs8D1u9h+fJB+TYD+WFXKwOcGwcx23uHLHUDi1UIEZOhT2Eui+aMCYVygUWH7JynTtbFQZyZcSsD2Dxj5OJNJlK110jarFgvqY98WxqtaRtB9Y8whwRRlGfa5GP2r/Vt3xbGeAflRl5khFgRLZgeFIfxJpEj1TZV2tCtpFS0uhXJGEQbMnzFynx8UaOx/0hBCyik1MQuu3flym6nx7XxPSQIDAQAB";
        //"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnxj/9qwVfgoUh/y2W89L6BkRAFljhNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBoLPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilIZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB";
        


        #region 代商家签约

        //（开启事务）接口创建应用事务，返回生成代商户操作事务编号 batch_no
        public string GetBatchNo(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\":\"" + Email + "\"," +
            "\"contact_info\":{" +
            "\"contact_name\":\"" + Name + "\"," +
            "\"contact_mobile\":\"" + Mobile + "\"," +
            "\"contact_email\":\"" + Email + "\"" +
            "}" +
            "}";
            string result = "";
            try
            {
                AlipayOpenAgentCreateResponse response = client.Execute(request);
                result = response.Body;
                LogHelper.Instance.WriteLog(result, "开启事务");
                //{"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)
            {
                LogHelper.Instance.WriteLog(ex.ToString(), "接口创建应用事务异常");
                result = "";
            }
            return result;
        }
        //提交代商户签约、创建应用事务
        public string AgentConfirm(string BatchNo)
        {
            IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", AppId, PrivateKey, "json", "1.0", "RSA2", AlipayPublicKey, "utf-8", false);
            AlipayOpenAgentConfirmRequest request = new AlipayOpenAgentConfirmRequest();
            request.BizContent = "{" +
            "  \"batch_no\":\"" + BatchNo + "\"" +
            "}";
            string result = "";
            try
            {
                LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + Newtonsoft.Json.JsonConvert.SerializeObject(request), "提交代商户签约");
                AlipayOpenAgentConfirmResponse response = client.Execute(request);
                result = response.Body;
                LogHelper.Instance.WriteLog(result + "\n\n", "提交代商户签约");
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteLog(ex.ToString(), "提交代商户签约异常");
                result = "";
            }
            return result;
        }
        //代签约产品通用接口，代商家发起签约产品申请
        // public string CommonSign(string BatchNo, string MccCode, string BusinessLicenseNo = "", string BusinessLicensePicPath = "", string SpecialLicensePicPath = "", 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
        //     if(string.IsNullOrEmpty(SpecialLicensePicPath)) SpecialLicensePicPath = BusinessLicensePicPath;
        //     FileItem SpecialLicensePic = new FileItem(SpecialLicensePicPath);
        //     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 = "FACE_TO_FACE_PAYMENT"; //isv要代商户签约产品码，产品码是支付宝内部对产品的唯一标识，例如：QUICK_WAP_WAY:手机网站支付，FACE_TO_FACE_PAYMENT:当面付
        //     request.AppName = "客小爽";
        //     // FileItem AppDemo = new FileItem(BusinessLicensePicPath);
        //     // request.AppDemo = AppDemo;
        //     List<string> WebSites = new List<string>();
        //     WebSites.Add("http://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;
        //         LogHelper.Instance.WriteLog(result, "代商家发起签约产品申请");
        //         //{"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)
        //     {
        //         LogHelper.Instance.WriteLog(ex.ToString(), "代签约产品通用接口异常");
        //         result = "";
        //     }
        //     return result;
        // }
        public string  CommonSign(string BatchNo, string MccCode, string BusinessLicenseNo = "", string BusinessLicensePicPath = "", string SpecialLicensePicPath = "", string ShopScenePicPath = "", string ShopSignBoardPicPath = "")
        { 
            IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", AppId, PrivateKey, "json", "1.0", "RSA2", AlipayPublicKey, "utf-8", false);
            AlipayOpenAgentFacetofaceSignRequest request = new AlipayOpenAgentFacetofaceSignRequest() ;
            request.BatchNo = BatchNo;
            request.MccCode = MccCode;
            if (!string.IsNullOrEmpty(BusinessLicenseNo))
            {
                request.BusinessLicenseNo = BusinessLicenseNo;  //营业执照号码
            }
            if (!string.IsNullOrEmpty(BusinessLicensePicPath))
            {
                // FileItem BusinessLicensePic = new FileItem(function.getPath(BusinessLicensePicPath));
                FileItem BusinessLicensePic = PublicFunction.GetNetFileItem(AppConfig.Base.OssHost + BusinessLicensePicPath);
                request.BusinessLicensePic = BusinessLicensePic; //营业执照图片。被代创建商户运营主体为个人账户必填，企业账户无需填写
                // FileItem BusinessLicenseAuthPic = new FileItem(function.getPath(BusinessLicensePicPath));
                FileItem BusinessLicenseAuthPic = PublicFunction.GetNetFileItem(AppConfig.Base.OssHost + BusinessLicensePicPath);
                request.BusinessLicenseAuthPic = BusinessLicenseAuthPic;
            }
            if (!string.IsNullOrEmpty(SpecialLicensePicPath))
            {
                // FileItem SpecialLicensePic = new FileItem(function.getPath(SpecialLicensePicPath));
                FileItem SpecialLicensePic = PublicFunction.GetNetFileItem(AppConfig.Base.OssHost + SpecialLicensePicPath);
                request.SpecialLicensePic = SpecialLicensePic;
            }
            if (!string.IsNullOrEmpty(ShopScenePicPath))
            {
                if(ShopScenePicPath.Contains(","))
                {
                    ShopScenePicPath = ShopScenePicPath.Split(',')[0];
                }
                // FileItem ShopScenePic = new FileItem(function.getPath(ShopScenePicPath));
                FileItem ShopScenePic = PublicFunction.GetNetFileItem(AppConfig.Base.OssHost + ShopScenePicPath);
                request.ShopScenePic = ShopScenePic;
            }
            if (!string.IsNullOrEmpty(ShopSignBoardPicPath))
            {
                if(ShopSignBoardPicPath.Contains(","))
                {
                    ShopSignBoardPicPath = ShopSignBoardPicPath.Split(',')[0];
                }
                // FileItem ShopSignBoardPic = new FileItem(function.getPath(ShopSignBoardPicPath));
                FileItem ShopSignBoardPic = PublicFunction.GetNetFileItem(AppConfig.Base.OssHost + ShopSignBoardPicPath);
                request.ShopSignBoardPic = ShopSignBoardPic;
            }
            // FileItem SpecialLicensePic = new FileItem("C:/Downloads/ooopic_963991_7eea1f5426105f9e6069/16365_1271139700.jpg");
            // request.setSpecialLicensePic = "-";
            request.Rate = "0.38";
            // request.SignAndAuth = true;
            // request.BusinessLicenseNo = "1532501100006302";
            // FileItem BusinessLicensePic = new FileItem("C:/Downloads/ooopic_963991_7eea1f5426105f9e6069/16365_1271139700.jpg");
            // request.setBusinessLicensePic = "-";
            // FileItem BusinessLicenseAuthPic = new FileItem("C:/Downloads/ooopic_963991_7eea1f5426105f9e6069/16365_1271139700.jpg");
            // request.setBusinessLicenseAuthPic = "-";
            // request.LongTerm = true;
            // request.DateLimitation = "2017-11-11";
            // FileItem ShopScenePic = new FileItem("C:/Downloads/ooopic_963991_7eea1f5426105f9e6069/16365_1271139700.jpg");
            // request.setShopScenePic = "-";
            // FileItem ShopSignBoardPic = new FileItem("C:/Downloads/ooopic_963991_7eea1f5426105f9e6069/16365_1271139700.jpg");
            // request.setShopSignBoardPic = "-";
            // request.ShopName = "-";
            // SignAddressInfo signAddressInfo = new SignAddressInfo();
            // signAddressInfo.country_code = "156";
            // signAddressInfo.province_code = "370000";
            // signAddressInfo.city_code = "371000";
            // signAddressInfo.district_code = "371002";
            // signAddressInfo.detail_address = "xx街道xx小区xx楼xx号";
            // signAddressInfo.longitude = "120.760001";
            // signAddressInfo.latitude = "60.270001";
            // request.shop_address = signAddressInfo;
            // request.BusinessLicenseMobile = "13189652239";
            string result = "";
            try
            {
                LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + Newtonsoft.Json.JsonConvert.SerializeObject(request), "代商家发起签约产品申请");
                AlipayOpenAgentFacetofaceSignResponse response = client.Execute(request);
                result = response.Body;
                LogHelper.Instance.WriteLog(result, "代商家发起签约产品申请");
            }
            catch (Exception ex)
            {
                LogHelper.Instance.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;
                LogHelper.Instance.WriteLog(result, "提交信息确认");
                //{"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)
            {
                LogHelper.Instance.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;
                LogHelper.Instance.WriteLog(result, "查询签约申请的结果");
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteLog(ex.ToString(), "查询签约申请的结果异常");
                result = "";
            }
            return result;
            //{"alipay_open_agent_order_query_response":{"code":"10000","msg":"Success","order_no":"20230613034000100000035309978329","product_agent_status_infos":[{"product_code":"FACE_TO_FACE_PAYMENT","product_name":"当面付","status":"WAIT_CONFIRM"}],"order_status":"MERCHANT_CONFIRM","confirm_url":"https:\/\/b.alipay.com\/page\/message\/messageList?type=todoTasks","merchant_pid":"2088641405724089"},"sign":"nwPLGsIQRV25znCK+3G8Pf/sgF7G11jh2QQWwq+UsP2K3FyG9e14x3pPwf0NLOinFHV0AVRI8FhZLbChNl/PUjPzrhoa1OHwB1n4lvo/2uvYVU3KPPV6NKUuxy3YAB6jHDi1AuSqFVOckfm0tvm6p4a/5RYF+3pNEufDISueTdduyvOabcuf7PqQs9J4/7lAmvJxNdxkrgaHrQ4mWk102k2tc657wrRLguUULFF6+j7HtGA4WrAWxrA+KLkzjbFlFu4qtwwZUHpF666mPMQSV0IDEtqiEn3PYDtBztUu9JKTfEoUxlm36pbpp7zynthXAFyMCR8nchsFXxU4bXJcng=="}
        }

        #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)
            {
                LogHelper.Instance.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;
            }
            catch (Exception ex)
            {
                LogHelper.Instance.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)
            {
                LogHelper.Instance.WriteLog(ex.ToString(), "统一收单线下交易查询异常");
                result = "";
            }
            return result;
        }

        #endregion

        #region 退款

        public string Refund(string TradeNo, string RefundNo, string Amount, string Reason, string MerToken)
        {
            IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", AppId, PrivateKey, "json", "1.0", "RSA2", AlipayPublicKey, "utf-8", false);
            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
            request.BizContent = "{" +
            "\"trade_no\":\"" + TradeNo + "\"," +
            "\"refund_amount\":" + Amount + "," +
            "\"out_request_no\":\"" + RefundNo + "\"," +
            "\"refund_reason\":\"" + Reason + "\"" +
            // "\"refund_royalty_parameters\":[{" +
            // "\"royalty_type\":\"transfer\"," +
            // "\"trans_out_type\":\"userId\"," +
            // "\"trans_out\":\"" + MerPid + "\"," +
            // "\"amount\":" + Amount + "," +
            // "\"desc\":\"" + Reason + "\"" +
            // "}]" +
            "}";
            string result = "";
            try
            {
                AlipayTradeRefundResponse response = client.Execute(request, null, MerToken);
                result = response.Body;
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteLog(ex.ToString(), "退款异常");
                result = "";
            }
            return result;
        }

        #endregion

        #region 分账
        public string Settle(string OrderNo, string TradeNo, List<RoyaltyParameters> Parameters, string MerToken)
        {
            IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", AppId, PrivateKey, "json", "1.0", "RSA2", AlipayPublicKey, "utf-8", false);
            AlipayTradeOrderSettleRequest  request= new AlipayTradeOrderSettleRequest();
            string royalty_parameters = "";
            foreach (RoyaltyParameters Parameter in Parameters)
            {
                royalty_parameters += "    {" +
                // "      \"royalty_type\":\"transfer\"," +
                // "      \"trans_in_type\":\"loginName\"," +
                "      \"trans_in\":\"" + Parameter.Account + "\"," +
                "      \"amount\":" + Parameter.Amount + "" +
                // "      \"trans_in_name\":\"" + Parameter.Name + "\"" +
                "    },";
            }
            request.BizContent = "{" +
            "  \"out_request_no\":\"" + OrderNo + "\"," +
            "  \"trade_no\":\"" + TradeNo + "\"," +
            "  \"royalty_parameters\":[" +
            royalty_parameters.TrimEnd(',') +
            "  ]" +
            "}";
            string result = "";
            try
            {
                AlipayTradeOrderSettleResponse response = client.Execute(request, null, MerToken);
                result = response.Body;
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteLog(ex.ToString(), "分账异常");
                result = "";
            }
            return result;
        }

        #endregion

        #region 绑定分账关系
        public string BindSettleRelation(string RequestNo, string Account, string MerToken)
        {
            IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", AppId, PrivateKey, "json", "1.0", "RSA2", AlipayPublicKey, "utf-8", false);
            AlipayTradeRoyaltyRelationBindRequest request = new AlipayTradeRoyaltyRelationBindRequest();
            request.BizContent="{" +
            "  \"receiver_list\":[" +
            "    {" +
            "      \"type\":\"userId\"," +
            "      \"account\":\"" + Account + "\"" +
            // "      \"name\":\"测试名称\"," +
            // "      \"memo\":\"分账给测试商户\"," +
            // "      \"login_name\":\"test@alitest.xyz\"," +
            // "      \"bind_login_name\":\"test@alitest.xyz\"" +
            "    }" +
            "  ]," +
            "  \"out_request_no\":\"" + RequestNo + "\"" +
            "}";
            string result = "";
            try
            {
                AlipayTradeRoyaltyRelationBindResponse response = client.Execute(request, null, MerToken);
                result = response.Body;
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteLog(ex.ToString(), "绑定分账关系异常");
                result = "";
            }
            return result;
        }

        #endregion

        #region 查看分账
        public string QuerySettle(string OrderNo, string TradeNo, string MerToken)
        {
            IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", AppId, PrivateKey, "json", "1.0", "RSA2", AlipayPublicKey, "utf-8", false);
            AlipayTradeOrderSettleQueryRequest request = new AlipayTradeOrderSettleQueryRequest();
            request.BizContent="{" +
            "  \"out_request_no\":\"" + OrderNo + "\"," +
            "  \"trade_no\":\"" + TradeNo + "\"" +
            "}";
            string result = "";
            try
            {
                AlipayTradeOrderSettleQueryResponse response = client.Execute(request, null, MerToken);
                result = response.Body;
                LogHelper.Instance.WriteLog(request.BizContent + "\n" + result, "支付宝查询分账结果");
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteLog(ex.ToString(), "分账异常");
                result = "";
            }
            return result;
        }

        #endregion



    }
}
