Getting the URL of the origin / referrer for user registration - c#

I have a piece of code that I've tested for a simple user registration code:
ReferrerURL = Request.UrlReferrer.AbsoluteUri
This property is set for user when he registers onto the website.
For example if user clicked onto the site via some ad, I'd like to get the origin site from where he came from.
With this piece of code I'm only getting the URL of my own site which looks like:
example.com/Registration
Regardless where the user came from... Is there any other way to fetch that information from where the user originally came (if it is available) - if not then just simply leave this field as null...
[ValidateAntiForgeryToken]
public async Task<ActionResult> DoRegister(UserRegistrationViewModel model)
{
var user = new Users()
{
FirstName = model.FirstName,
LastName = model.LastName,
Email = model.Email,
CountryId = 230,
Active = false,
PasswordSalt = salt,
PasswordHash = PasswordHelper.CreatePasswordHash(model.Password, salt),
GUID = _guid,
HasSpecialSubscription = false,
TotalScans = 0,
IsFreeTrialExpired = false,
DateOfRegistration = DateTime.Now,
ReferrerId = referrerId,
AffiliatePct = 0.15,
Cycles = 3,
ReferrerURL = Request.UrlReferrer.AbsoluteUri
};
}

A referrer is a header sent by browsers when the user navigates to another page, so the target site knows the originating site - if a browser is configured to send it (privacy settings or plugins may strip the header) and if the sites use the same scheme (referrers aren't sent when transferring from http to https or vice versa).
But every click resets the referrer to the current page. So if your users flow like this:
External Site -> Registration Page -> Registration POST Handler
Then in the last one, the referrer will be your registration page, not the external site's address.
So you need to save the referrer in the registration page, and forward it to your POST action. You could do so in a hidden form field, or by storing it in the session, or in a cookie. All approaches have their pros and cons.

Related

Authorize.net Accept Hosted Customer Profile Page has no button to return

I am using the Authorize.net Accept Hosted "Get Hosted Profile Page" action using redirect instead of iframe. Everything is working so far, redirect is happening, token is getting passed . . . but there is literally no button to proceed and/or go back to my site after the customer is redirected to this page (?). Am I missing something? I am passing a redirect URL in to get my token, so I'd expect there to be something happening.
I'm using the .NET SDK on my backend.
string token = null;
var settings = new settingType[]
{
new settingType
{
settingName = settingNameEnum.hostedProfileReturnUrl.ToString(),
settingValue = model.ReturnUrl.AbsoluteUri
// ^^^ here's why my redirect url goes
}
};
var profileReq = new getHostedProfilePageRequest();
profileReq.customerProfileId = model.CustomerProfileId;
profileReq.hostedProfileSettings = settings;
var controller = new getHostedProfilePageController(profileReq);
controller.Execute();
var resp = controller.GetApiResponse();
// ^^^ this all works fine, token is returned
Here's the page to which I'm redirected at https://test.authorize.net/customer/manage (the sandbox), below. There's no button to advance or go backwards. I've tried clicking everywhere.
How do I get back to my site?

Secure Stripe Payment

I'm running a Stripe test payment on an ASP Net site. When the user is ready to pay they are FORWARDED to their gateway to collect card details.
Once they complete a successful payment they are returned to the success URL i set with the {SESSION_ID} variable alongside the URL i.e. www.example.com/success?session_id{Session_ID}.
I then process the payment by getting the session first
StripeConfiguration.ApiKey = "sk_test_123";
var service = new SessionService();
Checkout.Session sess service.Get("cs_test_4561");
I then find the payment from my database using the session id i saved and passed when the user checked out.
My concern is that through a web sniffer tool the Session ID can be picked up and you can pass that manually to the successURL.
I can add HTTPS to the site but is there anything else i could do to make this a little more difficult i.e. expire the Session ID after some time or have a value from Strip to confirm the payment is successful?
Edit 1:
My code behind to set the SessionCreateOptions
var options = new SessionCreateOptions
{
PaymentMethodTypes = new List<string> { "card", },
LineItems = GetItems(),
SuccessUrl = "www.example.com/success?session_id={CHECKOUT_SESSION_ID}",
CancelUrl = "www.example.com/cancel",
PaymentIntentData = new SessionPaymentIntentDataOptions
{
Metadata = new Dictionary<string, string>{
{"orderID","123"}
}
},
Mode="payment",
};
var service = new SessionService();
Session session = service.Create(options);
When the user is returned back to the success page, i run this code to get the session i run the above code to get the Session but payment_intent is null if i type sess.PaymentIntent
When you retrieve the CheckoutSession by its id, you should check its payment_intent to verify that it shows status: succeeded. That shows that the payment went through without issue.
More details on the entire process here:
https://stripe.com/docs/payments/checkout/fulfillment

Facebook C# SDK not returning all information

My permission scope is defined in this:
var loginUrl = fb.GetLoginUrl(new
{
client_id = ConfigurationManager.AppSettings["facebookAppID"].ToString(),
client_secret = ConfigurationManager.AppSettings["facebookAppSecret"].ToString(),
redirect_uri = RedirectUri.AbsoluteUri,
response_type = "code",
scope = "public_profile, email, user_friends, user_about_me, user_birthday, user_education_history, user_work_history, user_location" // Add other permissions as needed
});
Then i get my access token this way:
var fb = new FacebookClient();
fb.AppId = ConfigurationManager.AppSettings["facebookAppID"].ToString();
fb.AppSecret = ConfigurationManager.AppSettings["facebookAppSecret"].ToString();
dynamic result = fb.Post("oauth/access_token", new
{
client_id = ConfigurationManager.AppSettings["facebookAppID"].ToString(),
client_secret = ConfigurationManager.AppSettings["facebookAppSecret"].ToString(),
redirect_uri = RedirectUri.AbsoluteUri,
code = code
});
Then i assign my access token to the Facebook client this way:
fb.AccessToken = accessToken;
I have a custom class to retrieve the data from Facebook SDK:
dynamic userDetails = fb.Get("me", new { fields = "name, email, gender, birthday, education, work" });
dynamic userEducation = fb.Get("me?fields=education");
//2. Store details to be used
var facebookUserDetails = new UserFacebookDetails();
facebookUserDetails.Name = userDetails.name;
facebookUserDetails.Email = userDetails.email;
facebookUserDetails.Gender = userDetails.gender;
facebookUserDetails.SetBirthDayVals(userDetails.birthday);
I get data for name, email and gender only. I don't get info on birthday, education or work. I check the same endpoint at Facebook API Explorer and i get information. What is happening? Can anyone please help me out?
I think i have figured the solution to this problem. The source of the problem stems at Facebook. I had not submitted my app for review and typically, those 3 scopes were among the set that needed submission before used.
Please check your FB app => APP Review => Approved Items.
email, public_profile, user_friends are all supported on initial.
All others required scope in login will not return!
You might retrieve correct permissions when you login same with app's owner and unexpected permissions when login as other accounts after make your app public.
If you want to more permission... you must to submit to FB.
This problem also fxxx me for 1 week :))
App Review ScreenShot

AuthorizationException while sending a payment request with braintree on Sandbox

No matter what I do I'm always getting the same AuthorizationException for the following request on sandbox with valid keys:
REQUEST:
{"CreditCard":
{
"CVV":"123",
"ExpirationMonth":"10",
"ExpirationYear":"2016",
"Number":"4111 1111 1111 1111"
},
"Amount":195.000000,
"OrderId":"bb461ebb-b894-4716-9ea2-7317f9e8c8d9",
"MerchantAccountId":"xxxxx",
"TaxAmount":0,
"Type":{},
"CustomFields":
{
"correlation_id":"bb461ebb-b894-4716-9ea2-7317f9e8c8d9"
},
"Options":
{
"StoreInVault":true,
"SubmitForSettlement":true
},
"CustomerId":"2012f124-2f00-477f-85fb-f6bc3f5fe275"
}
Here's the code that I'm using to create this request:
var request = new TransactionRequest
{
OrderId = message.Id.ToString(),
Amount = message.Amount,
CustomerId = message.CustomerId.ToString(),
MerchantAccountId = message.MerchantAccountId,
Options = new TransactionOptionsRequest
{
SubmitForSettlement = message.SubmitForSettlement
}
};
string expirationMonth = message.ExpirationMonth.GetValueOrDefault().ToString(CultureInfo.InvariantCulture);
string expirationYear = message.ExpirationYear.GetValueOrDefault().ToString(CultureInfo.InvariantCulture);
request.CreditCard = new TransactionCreditCardRequest
{
Token = message.CreditCardId.ToString(),
CardholderName = message.CardholderName,
Number = message.CardNumber,
ExpirationMonth = expirationMonth,
ExpirationYear = expirationYear,
CVV = message.CVV
};
request.Options.StoreInVault = true;
var result = _gateway.Transaction.Sale(request);
What I'm missing?
I work at Braintree. If you have any other questions, feel free to contact our support team directly.
This error can happen when you're attempting to use a merchant account that your user doesn't have access to. In this case, the merchant account ID you're passing (which you X'd out above) doesn't exist.
Take a look at our support pages for more information on merchant account IDs:
Merchant Account ID
With Braintree, you can have multiple merchant accounts processing via the same single gateway account. You could have multiple locations, multiple businesses, and multiple currencies all setup and processing under one single account. This makes it easy to keep track of all of your processing with unified reporting and access and can even save you money.
You can find the values for all merchant accounts in your gateway account by following these steps:
Log in to the Control Panel
Navigate to Settings -> Processing
Scroll to the bottom of the page to find the section labeled Merchant Accounts
If I only have a single merchant account, do I still need to send this value with API requests?
No, this is an optional value with all API requests that support it. If you only have a single merchant account, there's no need to include this value. If you have more than one merchant account you can specify which merchant account should be used with each API request. If you omit this value, all requests will automatically be routed through your default account.

Lost session/cookie when login as another user

I am building dnn module which allow logged in user to log in as another user.
But I have some wired issue here.
This is how I log out current user and login as another user:
UserInfo userInfo = UserController.GetUserById(portalId, userId);
if (userInfo != null)
{
DataCache.ClearUserCache(this.PortalSettings.PortalId, Context.User.Identity.Name);
if (Session["super_userId"] == null)
{
Session["super_userId"] = this.UserId;
Session["super_username"] = this.UserInfo.Username;
}
HttpCookie impersonatorCookie = new HttpCookie("cookieName");
impersonatorCookie.Expires = DateTime.Now.AddHours(1);
Response.Cookies.Add(impersonatorCookie);
Response.Cookies["cookieName"]["super_userId"] = this.UserId.ToString();
Response.Cookies["cookieName"]["super_username"] = this.UserInfo.Username;
PortalSecurity objPortalSecurity = new PortalSecurity();
objPortalSecurity.SignOut();
UserController.UserLogin(portalId, userInfo, this.PortalSettings.PortalName, Request.UserHostAddress, false);
Response.Redirect(Request.RawUrl, true);
}
And in PageLoad() I try to read value from this cookie but it doesn't read anything:
try
{
string super_userId = Request.Cookies["cookieName"]["super_userId"];
string super_username = Request.Cookies["cookieName"]["super_username"];
if (!String.IsNullOrEmpty(super_userId))
{
this.Visible = true;
this.lblSuperUsername.Text = Session["super_username"].ToString();
this.txtPassword.Enabled = true;
this.btnBackToMyAccount.Enabled = true;
}
...
I also have tried to do the same with session but nothing works, and I can't figure why?
As I find here, there can be problems with setting cookies in a request that gets redirected, and here is stated that cookies won't get set with a redirect when their domain is not /.
So you can try to not redirect using HTTP headers, but show a "Logged In" page instead that contains a "Home" link and a meta refresh or Javascript redirect.
By the way, setting a UserID in a cookie is not really the way to go. What if I change that cookie value to 1?
I suggest when you set a new cookie to always set the Domain, and probably and the Expires.
Response.Cookies[cookieName].Domain = RootURL;
Response.Cookies[cookieName].Expires = DateTime.UtcNow.AddDays(cDaysToKeep);
The domain is very importan to be the url with out the subdomain, eg only the mydomain.com with out the www. because if a cookie is set from www.mydomain.com and you try to read it from mydomain.com or vice versa, then the cookie will not be read and you may lost it / overwrite it.
So I suggest to make a function that when you set a cookie, you set at least 3 parametres, the Domain, the Expires, and the Value.
Similar questions and answers :
Multiple applications using same login database logging each other out
asp.net forms authentication logged out when logged into another instance
Put these two statements
Response.Cookies["cookieName"]["super_userId"] = this.UserId.ToString();
Response.Cookies["cookieName"]["super_username"] = this.UserInfo.Username;
after
UserController.UserLogin(portalId, userInfo, this.PortalSettings.PortalName, Request.UserHostAddress, false);
May be the UserLogin method is resetting the Session variables.
Hope it Helps :)

Categories