How to verify paypal payment if its authentic or not C# - c#

I want to verify user payment whether its authentic or not. I am getting response from pay pal but i want to resend that response to pay pal to verify it. I am getting all the details regarding payments and user.

You can verify your by using pay pal api.
First install payPal from nuget packages
Install-Package PayPal
Secondly configure your webconfig like this.
<configSections>
<section name="paypal" type="PayPal.SDKConfigHandler, PayPal" />
</configSections>
<configuration>
<paypal>
<settings>
<add name="mode" value="sandbox"/>
<add name="clientId" value="client_id"/>
<add name="clientSecret" value="client_secret_id"/>
</settings>
</paypal>
</configuration>
Then from server side i mean C# end you can verify your payment like this.
var config = ConfigManager.Instance.GetProperties();
var accessToken = new OAuthTokenCredential(config).GetAccessToken();
var apiContext = new APIContext(accessToken);
// --verify payment ---
var payment = Payment.Get(apiContext, "PAY-YourCheckNo");
Here payment variable will populate with different status defending upon your pay-yourcheckNo. This is how you can verify your payment done through paypal.

Related

Microsoft B2C Azure Demo Not Authorized Error

I am trying to learn ASP.Net with Azure AD B2C Login / Register flow. I am running the demo here:
https://learn.microsoft.com/en-us/azure/active-directory-b2c/tutorial-web-api-dotnet?tabs=app-reg-ga
The C# code for the demo can be downloaded from https://github.com/Azure-Samples/active-directory-b2c-dotnet-webapp-and-webapi/archive/master.zip
I have gone all the way through the demo from the beginning and have completed all of the pre-requisites.
I am at the point now where I have signed in successfully and when I click the To-Do List link while debugging the application, I get a User Not Authorized (404) error.
I apologize in advance if I am not explaining what I think I am seeing very well, as I am very new to Azure and web programming. I am most comfortable with Windows Desktop applications interfacing with SQL Server, but I am trying to expand my knowledge, so please bear with me.
As I stated before, I can successfully log-in to the application, which I believe happens in the TaskWebApp project.
Here is the code where the error is happening, which is in the TasksController.cs in the TaskWebApp project:
namespace TaskWebApp.Controllers
{
[Authorize]
public class TasksController : Controller
{
private readonly string apiEndpoint = Globals.ServiceUrl + "/api/tasks/";
// GET: Makes a call to the API and retrieves the list of tasks
public async Task<ActionResult> Index()
{
try
{
// Retrieve the token with the specified scopes
var scope = new string[] { Globals.ReadTasksScope };
IConfidentialClientApplication cca = MsalAppBuilder.BuildConfidentialClientApplication();
var accounts = await cca.GetAccountsAsync();
AuthenticationResult result = await cca.AcquireTokenSilent(scope, accounts.FirstOrDefault()).ExecuteAsync();
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, apiEndpoint);
// Add token to the Authorization header and make the request
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = await client.SendAsync(request);
// Handle the response
switch (response.StatusCode)
{
case HttpStatusCode.OK:
string responseString = await response.Content.ReadAsStringAsync();
JArray tasks = JArray.Parse(responseString);
ViewBag.Tasks = tasks;
return View();
case HttpStatusCode.Unauthorized:
return ErrorAction("Please sign in again. " + response.ReasonPhrase);
default:
return ErrorAction("Error. Status code = " + response.StatusCode + ": " + response.ReasonPhrase);
}
}
catch (MsalUiRequiredException ex)
{
/*
If the tokens have expired or become invalid for any reason, ask the user to sign in again.
Another cause of this exception is when you restart the app using InMemory cache.
It will get wiped out while the user will be authenticated still because of their cookies, requiring the TokenCache to be initialized again
through the sign in flow.
*/
return new RedirectResult("/Account/SignUpSignIn?redirectUrl=/Tasks");
}
catch (Exception ex)
{
return ErrorAction("Error reading to do list: " + ex.Message);
}
}
The response status code in the Switch statement is 404.
When I debug, here is what I see:
var scope returns https://ShoppingCartB2C.onmicrosoft.com/tasks/demo.read
cca returns (I am questioning the format of the Authority property):
accounts returns nothing. A count of 0.
I believe 0 accounts is the problem.
When I try to get result, it goes to the catch block.
Here is the Web.config for the TaskWebApp project:
<configuration>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="ida:Tenant" value="ShoppingCartB2C.onmicrosoft.com" />
<!--MSAL cache needsĀ a tenantId along with the user's objectId to function. It retrieves these two from the claims returned in the id_token.
As tenantId is not guaranteed to be present in id_tokens issued by B2C unless the steps listed in this
document (https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/AAD-B2C-specifics#caching-with-b2c-in-msalnet).
If you are following the workarounds listed in the doc and tenantId claim (tid) is available in the user's token, then please change the
code in <ClaimsPrincipalsExtension.cs GetB2CMsalAccountId()> to let MSAL pick this from the claims instead -->
<add key="ida:TenantId" value="db1b052a-415c-4604-887c-e27b59860001" />
<add key="ida:ClientId" value="975f1457-e3e2-4cb8-b069-6b0b6b46611d" />
<add key="ida:ClientSecret" value="Gw4.3o-DRDr.j_828H-JMfsk_Jd1d-jQ5p" />
<add key="ida:AadInstance" value="https://ShoppingCartB2C.b2clogin.com/tfp/{0}/{1}" />
<add key="ida:RedirectUri" value="https://localhost:44316/" />
<add key="ida:SignUpSignInPolicyId" value="B2C_1_signupsignin1" />
<add key="ida:EditProfilePolicyId" value="b2c_1_profileediting1" />
<add key="ida:ResetPasswordPolicyId" value="b2c_1_passwordreset1" />
<add key="api:TaskServiceUrl" value="https://localhost:44332/" />
<!-- The following settings is used for requesting access tokens -->
<add key="api:ApiIdentifier" value="https://ShoppingCartB2C.onmicrosoft.com/tasks/" />
<add key="api:ReadScope" value="demo.read" />
<add key="api:WriteScope" value="demo.write" />
</appSettings>
And for the TaskService project:
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="ida:AadInstance" value="https://ShoppingCartB2C.b2clogin.com/{0}/{1}/v2.0/.well-known/openid-configuration" />
<add key="ida:Tenant" value="ShoppingCartB2C.onmicrosoft.com" />
<add key="ida:ClientId" value="975f1457-e3e2-4cb8-b069-6b0b6b46611d" />
<add key="ida:SignUpSignInPolicyId" value="B2C_1_signupsignin1" />
<!-- The following settings is used for requesting access tokens -->
<add key="api:ReadScope" value="demo.read" />
<add key="api:WriteScope" value="demo.write" />
</appSettings>
If you would like screen shots from Azure, or have questions about how that is configured, feel free to ask.
I am not concerned about exposing client secrets or AppId's because I am just following a demo. This is never going to be a production app.
I have not made any code modifications to the demo. Thanks for your help.
Edit: Showing API Permissions

The X.509 certificate could not be loaded from the file

I am using the API SAML2.0 for ASP.net MVC and I used openssl to create the private and public key files and used a password for the private file. It generated two files ca.key and cas.pem, I used the ca.key file as the private key but I am getting this error
Additional information: The X.509 certificate could not be loaded from the file D:\Test Web Projects\TestSaml\TestSaml\Certificates\ca.key.
My users login to my mvc application the login process has nothing to do with SAML. I just check the users against my DB. The reason I am using SAML2.0 is because I need to direct my users for payment process to another external page which is my service provider. So once they click on a button on my page they should be redirected to the other website. The following is the sample code I built to verify if its working.
Web.config
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301880
-->
<configuration>
<appSettings>
<add key="TargetURL" value="https://btat2.paybill.com/consumer/SSO/SSOLogin?clientId=ReadyCapital"/>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
</configuration>
Saml.config
<?xml version="1.0"?>
<SAMLConfiguration xmlns="urn:componentspace:SAML:2.0:configuration">
<IdentityProvider Name="https://TestSaml"
Description="Test Identity Provider"
LocalCertificateFile="Certificates\ca.key"
LocalCertificatePassword="readycapital"/>
<PartnerServiceProviders>
<!-- MVC example -->
<PartnerServiceProvider Name="urn:oasis:names:tc:SAML:2.0:assertion"
Description="MVC Example Service Provider"
SignSAMLResponse="true"
SignAssertion="false"
EncryptAssertion="true"
AssertionConsumerServiceUrl="http://www.paybill.com/V2/Test/Login.aspx"
PartnerCertificateFile="Certificates\btat2.cert"/>
</PartnerServiceProviders>
</SAMLConfiguration>
Controller
public ActionResult Index(Profile profile)
{
string targetUrl = WebConfigurationManager.AppSettings["TargetURL"];
string userName = "00373219101";// WebConfigurationManager.AppSettings["SubjectName"];
SAMLAttribute[] attributes = new SAMLAttribute[2];
SAMLAttribute attribute = new SAMLAttribute("UserEmailAddress", SAMLIdentifiers.AttributeNameFormats.Unspecified, null, string.Empty);
attributes[0] = attribute;
SAMLAttribute attribute2 = new SAMLAttribute("MiscellaneousData", SAMLIdentifiers.AttributeNameFormats.Unspecified, null, string.Empty);
attributes[1] = attribute2;
SAMLIdentityProvider.InitiateSSO(Response, userName, attributes, targetUrl);
}
Did you check that the WebServer can actually access the files? Maybe use Microsoft Windows Sysinternals Process Monitor and check that the read operation is successful.
Replace the standalone .key file with a .pfx file both containing the certificate as well as the private key and link to that in IdentityProvider/#LocalCertificateFile

Paypal API: Getting list of orders

So I am trying to get the list of the items that I have to deliver based off of orders between certain dates from paypal. I couldn't find any solution or explanation on paypal developer documentation on this.
So I use "paypal here" to receive POS payments for orders during the week. I wanted to essentially get an order list if you will (I was surprised that paypal didn't offer an api call for this). By order list I mean a list of customers and each customer's list of items(shopping cart) that they have ordered. I believe "paypal here" treats all orders as an invoice.
So after a lot of research, I got a list of invoices from the api. However, none of the invoices include the shopping cart information (the items they have ordered.). I would greatly appreciate any suggestions or help.
Config file --->
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!--<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>-->
<configSections>
<section name="paypal" type="PayPal.SDKConfigHandler, PayPal" />
</configSections>
<!-- PayPal SDK settings -->
<paypal>
<settings>
<add name="mode" value="live" />
<add name="clientId" value=" client id" />
<add name="clientSecret" value="client Secret" />
</settings>
</paypal>
</configuration>
C# Code --->
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PayPal.Api;
namespace PaypalConsoleApp
{
class Program
{
static void Main(string[] args)
{
// Authenticate with PayPal
var config = ConfigManager.Instance.GetProperties();
var accessToken = new OAuthTokenCredential(config).GetAccessToken();
var apiContext = new APIContext(accessToken);
var test = Invoice.GetAll(apiContext, pageSize: 10, totalCountRequired: true);
}
}
}
Update:
Link to SDK--> https://github.com/paypal/PayPal-NET-SDK

Setting up of Selenium Web driver for SpecBind

I have been asked to create a remote selenium web driver using browserstack to test the functionality across all browsers. I have checked the repository to which I have received some of the felds needed:
RemoteUrl: http://hub.browserstack.com:80/wd/hub/
browserstack.user = username
browserstack.key = password
browserstack.debug = true/false
browserstack.tunnel = true/false
os
OS_version
Version = the browser version
I have got the code to create the driver below:
DesiredCapabilities capability = DesiredCapabilities.Firefox();
capability.SetCapability("browserstack.user", "username");
capability.SetCapability("browserstack.key", "password");
driver = new RemoteWebDriver(
new Uri("http://hub.browserstack.com/wd/hub/"), capability
);
this creates the remote webdriver. However as i am using this with specbind I need to create this driver within the app.config. which will be stored under a <browserfactory> however I am unsure on how to do this, please help!
I have now resolved this issue. From the start URL you need to then put in this browser factory setting:
<browserFactory
provider="SpecBind.Selenium.SeleniumBrowserFactory, SpecBind.Selenium">
<settings>
<add name="RemoteUrl" value="http://hub.browserstack.com:80/wd/hub/"/>
<add name="browser" value="IE" />
<add name="browser_version" value="8.0"/>
<add name="os" value ="Windows"/>
<add name="os_version" value="7" />
<add name="browserstack.user" value="username" />
<add name="browserstack.key" value="key" />
</settings>
The various settings configure this to Windows 7 and IE 8. This can be changed accordingly and the Username and Key is given to you by browser stack.

IIS: Access Microsoft CRM 2013 with AppPool Identity

My IIS MVC web site connects to Microsoft CRM 2013. User/Domain/Password are set in web.config, this works fine.
Now I want to remove hard coded credentials in web.config. To Access CRM I want to use credentials of AppPool Identity. This user has enough rights on server and administrator role in MS CRM. I tried this way:
Uri organizationUri = new Uri(WebConfigurationManager.AppSettings["CrmUrl"]);
var credentials = new ClientCredentials();
credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
var orgProxy = new OrganizationServiceProxy(organizationUri, null, credentials, null);
This does not work. DefaultNetworkCredentials are empty.
I need help to manage this problem. Thanks!
Instead of creating the credentials and the organization service proxy yourself, rather let CrmConfiguration handle this:
Your Web.config will look something like this:
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="microsoft.xrm.client" type="Microsoft.Xrm.Client.Configuration.CrmSection, Microsoft.Xrm.Client"/>
</configSections>
<connectionStrings>
<!-- On-Premise with integrated Authentication -->
<add name="MyOnPremiseConnection" connectionString="Url=http://SERVER-NAME/ORG-NAME/XRMServices/2011/Organization.svc;" />
</connectionStrings>
<microsoft.xrm.client>
<contexts default="MyOnPremiseContext">
<!-- On Premise CRM-->
<add name="MyOnPremiseContext" connectionStringName="MyOnPremiseConnection" serviceName="MyService" />
</contexts>
<services default="MyService">
<add name="MyService" serviceCacheName="Xrm" />
</services>
<serviceCache default="Xrm">
<add name="Xrm" type="Microsoft.Xrm.Client.Services.OrganizationServiceCache, Microsoft.Xrm.Client" cacheMode="Disabled" />
</serviceCache>
</microsoft.xrm.client>
</configuration>
Your code will connect to CRM like this:
using (var servicecontext = CrmConfigurationManager.CreateContext("MyOnPremiseConnection", true) as CrmOrganizationServiceContext)
{
var query = new QueryExpression
{
EntityName = "account",
ColumnSet = new ColumnSet("name"),
TopCount = 10,
};
var top10accounts = servicecontext.RetrieveMultiple(query).Entities;
}
Reference: Simplified connection to Microsoft Dynamics CRM

Categories

Resources