public IActionResult SubmitModel(OnboardingModel model)
        {
            var persistence = new FilePersistenceService(model);

            persistence.Save();
            return(Ok(new OnboardingModel()));
        }
        public async Task <IActionResult> Onboarding(OnboardingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(await Configure());
            }

            var storeId = await _storeContext.GetActiveStoreScopeConfigurationAsync();

            var settings = await _settingService.LoadSettingAsync <PayPalCommerceSettings>(storeId);

            //try to onboard merchant with the passed email
            var(merchant, error) = await _serviceManager.OnboardAsync(model.Email);

            if (!string.IsNullOrEmpty(error))
            {
                var locale = await _localizationService.GetResourceAsync("Plugins.Payments.PayPalCommerce.Configuration.Error");

                var errorMessage = string.Format(locale, error, Url.Action("List", "Log"));
                _notificationService.ErrorNotification(errorMessage, false);
                return(await Configure());
            }

            settings.SetCredentialsManually = false;
            settings.UseSandbox             = false;
            settings.ClientId     = string.Empty;
            settings.SecretKey    = string.Empty;
            settings.Email        = merchant.Email;
            settings.SignUpUrl    = merchant.SignUpUrl;
            settings.MerchantGuid = merchant.MerchantGuid;
            var overrideSettings = model.Email_OverrideForStore;
            await _settingService.SaveSettingOverridablePerStoreAsync(settings, setting => setting.SetCredentialsManually, overrideSettings, storeId, false);

            await _settingService.SaveSettingOverridablePerStoreAsync(settings, setting => setting.UseSandbox, overrideSettings, storeId, false);

            await _settingService.SaveSettingOverridablePerStoreAsync(settings, setting => setting.ClientId, overrideSettings, storeId, false);

            await _settingService.SaveSettingOverridablePerStoreAsync(settings, setting => setting.SecretKey, overrideSettings, storeId, false);

            await _settingService.SaveSettingOverridablePerStoreAsync(settings, setting => setting.Email, overrideSettings, storeId, false);

            await _settingService.SaveSettingOverridablePerStoreAsync(settings, setting => setting.SignUpUrl, overrideSettings, storeId, false);

            await _settingService.SaveSettingOverridablePerStoreAsync(settings, setting => setting.MerchantGuid, overrideSettings, storeId, false);

            await _settingService.ClearCacheAsync();

            var emailSet = await _localizationService.GetResourceAsync("Plugins.Payments.PayPalCommerce.Onboarding.EmailSet");

            _notificationService.SuccessNotification(emailSet);

            return(await Configure());
        }
        public async Task <IActionResult> SignUp(OnboardingModel model)
        {
            await _serviceManager.SignUpAsync(model.MerchantGuid, model.AuthCode, model.SharedId);

            //clear URL since the merchant is already signed up
            var storeId = await _storeContext.GetActiveStoreScopeConfigurationAsync();

            var settings = await _settingService.LoadSettingAsync <PayPalCommerceSettings>(storeId);

            settings.SignUpUrl = null;
            await _settingService.SaveSettingOverridablePerStoreAsync(settings, setting => setting.SignUpUrl, model.Email_OverrideForStore, storeId, false);

            await _settingService.ClearCacheAsync();

            return(Ok());
        }
        //public IActionResult ProcessCode(string code, string error, string error_description, string resource, string state)
        public async Task <IActionResult> ProcessCode(OnboardingModel model)
        {
            //Find Tenant based on secret
            var t = m_db.Tenants.FirstOrDefault(p => p.Secret == model.state);

            if (t != null)
            {
                var authContext = new AuthenticationContext($"{m_aadOptions.AzureAdInstance}"); //MT
                var creds       = new ClientCredential(m_aadOptions.ClientId, m_aadOptions.ClientSecret);
                var redirectUri = new Uri($"{m_aadOptions.Domain}/MT/ProcessCode");
                //Get Tenant
                var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
                    model.code, redirectUri, creds,
                    "https://graph.microsoft.com/");

                //Do we already registered that tenant?
                var tenantID = authResult.TenantId.ToLower();
                if (m_db.Tenants.FirstOrDefault(p => p.TenantGuid == tenantID) == null)
                {
                    t.TenantGuid = tenantID;
                }
                else
                {
                    //m_db.Tenants.Remove(t);
                }
                m_db.SaveChanges();
            } //Else - wrong secret
            //Clean old
            var old = m_db.Tenants.Where(p => p.TenantGuid == "" && p.DtCreated < DateTime.UtcNow.AddMinutes(-5));

            if (old.Count() > 0)
            {
                foreach (var item in old)
                {
                    m_db.Tenants.Remove(item);
                }
                m_db.SaveChanges();
            }
            return(View(model));
        }
        private string GetSQLString(OnboardingModel obModel)
        {
            //TODO: Add to the SQL string if you want to do conditional services like the ones below

            /*
             * 2. Add Payment Services
             * -- 2.1 MOTO
             * EXEC ps.AddPBMerchantService '{}', '{}', {}, '{}', {}, '{}', '{}', '{}'
             * -- 2.2 CNP Recurring
             * EXEC ps.AddPBMerchantService '{}', '{}', {}, '{}', {}, '{}', '{}', '{}'
             * -- 2.3 MOTO Recurring
             * EXEC ps.AddPBMerchantService '{}', '{}', {}, '{}', {}, '{}', '{}', '{}'
             */


            FormattableString sqlString = $@"
            /* 
                USE [PaymentSwitch]
                EXEC sp_setapprole 'DevSupportWriteAccess', 'JQ#UWX<!D3RawdU4'
            */
            BEGIN TRAN
            DECLARE @return_value INT
            EXEC    @return_value = [PS].[CreateMerchant]
                    @merchantName = {StringToSqlNvarchar(obModel.Merchant.MerchantName)},                   --Merchant Name
                    @merchantGuid = {StringToSqlNvarchar(obModel.Merchant.MerchantGuid.ToString())},        --MerchantGUID generated After creating Merchant in Sandbox.Remove this if No Merchant Was Created in Sandbox.
		            
                    --Main Payment Service Type -> 3DSecure or MOTO
                    @registerCardNotPresent = {BoolToSQL(obModel.Merchant.RegisterCardNotPresent)},                               -- Set to 1 if 3DS is Required OR Set to 0 when MOTO is required.Run 2.1 to add CardNotPresentMOTO
                    @registerCardNotPresentRecurring = {BoolToSQL(obModel.CardNotPresent.RegisterCardNotPresentRecurring)},       -- Set to 0. Run 2.2 and 2.3 if Recurring is required
		            
                    --3DS Test Details Already Prepopulated.
                    @register3DSecure = {BoolToSQL(obModel.Merchant.Register3dSecure)},                                   -- Set to 1 if 3DS is Required OR Set to 0 when MOTO is required
                    @secure3DMerchantId = {StringToSqlNvarchar(obModel.Merchant.Secure3dMerchantId)},                     -- 0+MerchantID,
                    @secure3DProcessorId = {StringToSqlNvarchar(obModel.CardNotPresent.Secure3dProcessorId)},             -- No need to Edit this,
                    @secure3DTransactionPwd = {StringToSqlNvarchar(obModel.CardNotPresent.Secure3dTransactionPassword)},  -- No need to Edit this,
                    @secure3DServiceURL = {StringToSqlNvarchar(obModel.CardNotPresent.Secure3dServiceUrl)},               -- No need to Edit this,
                    @secure3DRiskProfile = {StringToSqlNvarchar(obModel.CardNotPresent.Secure3dRiskProfile)},             -- No need to Edit this,
		            
                    --Merchant Accepted Cards here
                    @registerVisaBin = {BoolToSQL(obModel.CardNotPresent.RegisterVisaBin)},               -- Set to 1 if Merchant wants to accept VISA cards, otherwise set to 0 if not Requested
                    @registerMasterCardBin = {BoolToSQL(obModel.CardNotPresent.RegisterMasterCardBin)},   -- Set to 1 if Merchant wants to accept MASTERCARD cards, otherwise set to 0 if not Requested
                    @registerDinnersBin = {BoolToSQL(obModel.CardNotPresent.RegisterDinersBin)},          -- Set to 1 if Merchant wants to accept DINERS cards, otherwise set to 0 if not Requested
                    @registerAmexBin = {BoolToSQL(obModel.CardNotPresent.RegisterDinersBin)},                                                                      -- Set to 1 if Merchant wants to accept AMERICAN EXPRESS cards, otherwise set to 0 if not Requested

		            --Merchant Bank Details here
                    @merchantType = {StringToSqlNvarchar(obModel.Merchant.MerchantType)},                                     -- Bank Details(MCC)
                    @cardAcceptorTerminalID = {StringToSqlNvarchar(obModel.Merchant.CardAcceptorTerminalId)},                 -- Bank Details 0000+Terminal ID
                    @cardAcceptorIdentificationCode = {StringToSqlNvarchar(obModel.Merchant.CardAcceptorIdentificationCode)}, -- Bank Details 00000000+MerchantID
		            -- Name Location Stencil  ---'Merchant Name         Cape Town    WP ZA'
                    @cardAcceptorNameLocation = {StringToSqlNvarchar(obModel.Merchant.CardAcceptorNameLocationStencil)},
                    @countryNumericCode = {StringToSqlNvarchar(obModel.Merchant.CountryNumericCode)},                          -- No need to Edit this, unless specified
                    @zeroPadRRN = {BoolToSQL(obModel.Merchant.ZeroPadRrn)},                                                    -- No need to Edit this, unless specified
                    @routingInformation = {StringToSqlNvarchar(obModel.Merchant.RoutingInformation)},                          -- No need to Edit this, unless specified
		            
                    --Notification Details
                    @notificationURL = {StringToSqlNvarchar(obModel.Notification.NotificationUrl)},                             --URL Provided by Merchant
                    @sendCompleteAdvice = {BoolToSQL(obModel.Notification.SendCompleteAdvice)},                                 --Always Set to 1 if URL is provided
                    @adviceVersion = {obModel.Notification.AdviceVersion},                                                      --Set to 1 for default, 2 for basic auth, 3 for expiry date, 4 for json
		            
                    --MasterPass Details Here
                    @registerMasterPass = {BoolToSQL(obModel.Merchant.RegisterMasterPass)},
                    @masterPassClientConfirmationURL = {StringToSqlNvarchar(obModel.MasterPass.MasterPassClientConfirmationUrl)},
                    @sendCompleteConfirmation = {StringToSqlNvarchar(obModel.MasterPass.SendCompleteConfirmation)},
                    @masterPassMerchantID = {StringToSqlNvarchar(obModel.MasterPass.MasterPassMerchantId)},
                    @decryptionKey = {StringToSqlNvarchar(obModel.MasterPass.DecryptionKey)},
		            
                    --WiCode Details here
                    @registerWiCode = {BoolToSQL(obModel.Merchant.RegisterWiCode)},
                    @wiCodeProcessorId = {StringToSqlNvarchar(obModel.WiCode.WiCodeProcessorId)},
                    @wiCodePassword = {StringToSqlNvarchar(obModel.WiCode.WiCodePassword)},
                    @wiCodeCashiedId = {StringToSqlNvarchar(obModel.WiCode.WiCodeCashiedId)},
                    @wiCodeStoreId = {StringToSqlNvarchar(obModel.WiCode.WiCodeStoreId)},
                    @wiCodePosId = {StringToSqlNvarchar(obModel.WiCode.WiCodePosId)},
		            
                    --SID Details here
                    @registerSid = {BoolToSQL(obModel.Merchant.RegisterSid)},
                    @sidMerchantID = {StringToSqlNvarchar(obModel.Sid.SidMerchantId)},
                    @sidDecryptKey = {StringToSqlNvarchar(obModel.Sid.SidDecryptKey)},
		            
                    --SnapScan details here
                    @registerSnapScan = {BoolToSQL(obModel.Merchant.RegisterSnapScan)},
                    @snapScanMerchantID = {StringToSqlNvarchar(obModel.SnapScan.SnapScanMerchantId)},
		            
                    --EFTSecure Details here
                    @registerEftSecure = {BoolToSQL(obModel.Merchant.RegisterEftSecure)},
                    @eftSecureMerchantID = {StringToSqlNvarchar(obModel.EftSecure.EftSecureMerchantId)},
                    @eftSecureUsername = {StringToSqlNvarchar(obModel.EftSecure.EftSecureUsername)},
                    @eftSecurePassword = {StringToSqlNvarchar(obModel.EftSecure.EftSecurePassword)},
		            
                    --Zapper Details here
                    @registerZapper = {BoolToSQL(obModel.Merchant.RegisterZapper)},
                    @zapperMerchantID = {StringToSqlNvarchar(obModel.Zapper.ZapperMerchantId)},
                    @zapperSiteID = {StringToSqlNvarchar(obModel.Zapper.ZapperSiteId)},
		            
                    --New MPGS details
		            --@registerMPGS = 0,
		            --@MPGSMerchantId = NULL,
		            --@MPGSUserName = NULL,
		            --@MPGSMerchantPwd = NULL,
		            --@MPGSRiskProfile = NULL,
		            --@MPGSFraudDetect = NULL,
		            --@MPGSPaymentConfiguration = NULL,

		            --OLD PAYMENT SERVICE AND OLD FRAUD SERVICE. DO NOT CONFIGURE ANYTHING BELOW
                    @registerPayD = 0,
                    @registerReD = 0,
                    @reDDivNum = NULL,
		            @reDEbtName = NULL,
		            @reDEbtService = NULL,
		            @reDUserId = NULL,
		            @reDReqTypeCode = NULL,
		            @reDSKeyID = NULL

            SELECT  'Return Value' = @return_value
            GO
            SELECT * FROM PS.Merchant M WITH(NOLOCK) WHERE M.name = '{obModel.Merchant.MerchantName}'
            ROLLBACK TRAN
            
            /*
            2. Add HPP and OPP Certificates if Merchant is using HPP
            */

            BEGIN TRAN
            EXEC ps.AddMerchantCertThumbPrint '{obModel.Merchant.MerchantGuid}', '7674780A239F11DA918EFDE030126BC7081355C7', 'HostedPaymentPage', '2040-01-01 01:59:59.000'
            EXEC ps.AddMerchantCertThumbPrint '{obModel.Merchant.MerchantGuid}', '6C9CF89686A7F22256146C6DCF673B2B99094F4C', 'OnlinePaymentsPortal', '2040-01-01 00:00:00.000'
            ROLLBACK TRAN

            /* 
            3. Add Merchant Certificates if Merchant is using API
            BEGIN TRAN
            EXEC ps.AddMerchantCertThumbPrint '{obModel.Merchant.MerchantGuid}', 'Certificate Thumbprint', '{obModel.Merchant.MerchantName}', 'Certificate Expiry Date'
            ROLLBACK TRAN
            */";

            return(sqlString.ToString());
        }
 public FilePersistenceService(OnboardingModel model)
 {
     Model = model;
 }