I have stored an api key to invoke APigateway in secret manager. And I am trying to fetch that secret from cdk and attach to the rule's header parameter as given below
var secret = Amazon.CDK.AWS.SecretsManager.Secret.FromSecretAttributes(this, "SCMId", new Amazon.CDK.AWS.SecretsManager.SecretAttributes
{
SecretCompleteArn = apikeyArn
});
var apikey = secret.SecretValueFromJson("ApiKey").Resolve;
var httpParameters = new Amazon.CDK.AWS.Events.CfnRule.HttpParametersProperty { HeaderParameters = new Dictionary<string, string> { { "x-api-key", apikey.ToString() } } };
Then the event target with above http parameter
var eventRule = new Amazon.CDK.AWS.Events.CfnRule(this, ruleId, new Amazon.CDK.AWS.Events.CfnRuleProps
{
EventBusName = busName,
Name = ruleName,
Description = description,
EventPattern = eventPattern,
Targets = new[]
{
new Amazon.CDK.AWS.Events.CfnRule.TargetProperty
{
Id = id,
Arn = apiArn,
HttpParameters = httpParameters,
RoleArn = roleArn,
}
}
});
Still the api key is not working and I am getting 403 error when that particular event trying to invoke api.
Related
I want to integrate Stripe into my ASP.NET MVC application.
So, As the first step, I'm trying to do it with simple code.
This is my simple code below,
var customers = new CustomerService();
var charges = new ChargeService();
var publishableKey = "pk_test_51KseuBH1Mw1tyjglBiJls20038FcgbHr";
StripeConfiguration.SetApiKey(publishableKey);
StripeConfiguration.ApiKey = "sk_test_51KseuRqoYQ6YGD7TNzPp0051boOPvQ";
var customer = customers.Create(new CustomerCreateOptions
{
Email = "isanka.ad#gmail.com",
Source = publishableKey
});
var charge = charges.Create(new ChargeCreateOptions
{
Amount = 500,
Description = "Sample Charge",
Currency = "usd",
Customer = customer.Id
});
I have tried different codes on forams. But it always returns the same error below,
No such token: 'pk_test_51KseuBHaMw1tyjglBiJls20038FcgbHr'
This is my Stripe keys,
Did I define secret key and publishable key incorrectly?
The publishable key must not be used in your backend code. It is for your client-side code, as described in the documentation: https://stripe.com/docs/keys. Moreover, the Source property on the customer describes the payment method: https://stripe.com/docs/api/customers/create?lang=dotnet. I can recommend getting started with Stripe with the quick start guide: https://stripe.com/docs/payments/quickstart.
It seems you copied only the first line of the API Key.
Please make sure that you are using the complete API Key in your application, and you don't need to use publishable key in your backend integration.
The source value only accepts payment source created via the Token or Sources APIs.
When creating a customer in your sample code, the Source was assigned with publishableKey which is invalid and that's probably why "No such token" was returned.
If you do not have any source created upfront, then Source should be removed from your customer creation request.
I was missing creating the card and token
generate. Above I have assigned the publishable token as the source value, not generated token.
Here is the full working code.
public async Task<ProcessPaymentResult> ProcessPaymentAsync(ProcessPaymentRequest processPaymentRequest)
{
var processPaymentResult = new ProcessPaymentResult();
try
{
var customers = new CustomerService();
var charges = new ChargeService();
var options = new RequestOptions
{
ApiKey = // your Secret Key
};
#region Card payment checkout
var creditCardType = processPaymentRequest.CreditCardType.ToString();
var optionToken = new TokenCreateOptions
{
Card = new TokenCardOptions
{
Number = processPaymentRequest.CreditCardNumber,
ExpMonth = processPaymentRequest.CreditCardExpireMonth,
ExpYear = processPaymentRequest.CreditCardExpireYear,
Cvc = processPaymentRequest.CreditCardCvv2,
Name = processPaymentRequest.CreditCardName,
Currency = _workContext.WorkingCurrency.CurrencyCode
},
};
var tokenService = new TokenService();
Token paymentToken = await tokenService.CreateAsync(optionToken, options);
#endregion
#region Stripe Customer
var customer = new Customer();
var customerEmail = processPaymentRequest.CustomValues["CustomerEmail"].ToString();
// Search customer in Stripe
var stripeCustomer = await customers.ListAsync(new CustomerListOptions
{
Email = customerEmail,
Limit = 1
}, options);
if (stripeCustomer.Data.Count==0)
{
// create new customer
customer = await customers.CreateAsync(new CustomerCreateOptions
{
Source = paymentToken.Id,
Phone = processPaymentRequest.CustomValues["Phone"].ToString(),
Name = processPaymentRequest.CustomValues["CustomerName"].ToString(),
Email = customerEmail,
Description = $" { processPaymentRequest.CustomValues["RegisteredEmail"]};{ processPaymentRequest.CustomValues["CustomerName"] }",
}, options);
}
else
{
// use existing customer
customer = stripeCustomer.FirstOrDefault();
}
#endregion
#region Stripe charges
var charge = await charges.CreateAsync(new ChargeCreateOptions
{
Source = paymentToken.Id,//Customer = customer.Id,
Amount = (int)(Math.Round(processPaymentRequest.OrderTotal, 2) * 100),
Currency = _workContext.WorkingCurrency.CurrencyCode,
ReceiptEmail = customer.Email,
Description = $" { processPaymentRequest.CustomValues["RegisteredEmail"]};{ processPaymentRequest.CustomValues["CustomerName"] }",
}, options);
if (charge.Status.ToLower().Equals("succeeded"))
{
processPaymentResult.NewPaymentStatus = PaymentStatus.Paid;
processPaymentResult.CaptureTransactionId = charge.Id;
}
else
{
processPaymentResult.AddError("Error processing payment." + charge.FailureMessage);
}
#endregion
}
catch (Exception ex)
{
processPaymentResult.AddError(ex.Message);
}
return processPaymentResult;
}
You need to add secretKey in the setapikey function.
// StripeConfiguration.SetApiKey(publishableKey);
StripeConfiguration.SetApiKey(secretKey);
I have created a Azure data factory pipeline as follows:
Azure SQL Database --> CSV Blob storage --> Azure Hyperscale Citus.
But this pipeline was created on azure datafactory UI.
Now i want to create this pipeline through a console app.
1.) But i am not able to figure out how to authenticate the client and connect to data factory to execute a pipeline.
2.) And is this the best way to convert the sql DB --> hyperscale
If you want to create Azure Data Factory pipeline with C# console application, we can use package Microsoft.Azure.Management.DataFactory. For more details, please refer to the document
For example (I create a pipeline to copy blobs from one container to another container)
Create a service principal and assign Contributor role to the sp
z login
az account set --subscription "<your subscription id>"
# the sp will have Azure Contributor role
az ad sp create-for-rbac -n "readMetric"
Install SDk
Install-Package Microsoft.Azure.Management.DataFactory
Install-Package Microsoft.Azure.Management.ResourceManager -IncludePrerelease
Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory
Create a data factory client to manage data factory
string tenantID = "<your tenant ID>";
string applicationId = "<your application ID>";
string authenticationKey = "<your authentication key for the application>";
string subscriptionId = "<your subscription ID where the data factory resides>";
string resourceGroup = "<your resource group where the data factory resides>";
string region = "<the location of your resource group>";
string dataFactoryName =
"<specify the name of data factory ";
var context = new AuthenticationContext("https://login.windows.net/" + tenantID);
ClientCredential cc = new ClientCredential(applicationId, authenticationKey);
AuthenticationResult result = context.AcquireTokenAsync(
"https://management.azure.com/", cc).Result;
ServiceClientCredentials cred = new TokenCredentials(result.AccessToken);
var client = new DataFactoryManagementClient(cred) {
SubscriptionId = subscriptionId };
Create Linked service
string storageAccount = "<your storage account name to copy data>";
string storageKey = "<your storage account key>";
string storageLinkedServiceName = "AzureStorageLinkedService";
LinkedServiceResource storageLinkedService = new LinkedServiceResource(
new AzureStorageLinkedService
{
ConnectionString = new SecureString(
"DefaultEndpointsProtocol=https;AccountName=" + storageAccount +
";AccountKey=" + storageKey)
}
);
await client.LinkedServices.CreateOrUpdateAsync(
resourceGroup, dataFactoryName, storageLinkedServiceName, storageLinkedService);
Create dataset
string blobDatasetName = "BlobDataset";
DatasetResource blobDataset = new DatasetResource(
new AzureBlobDataset
{
LinkedServiceName = new LinkedServiceReference
{
ReferenceName = storageLinkedServiceName
},
FolderPath = new Expression { Value = "#{dataset().path}" },
Parameters = new Dictionary<string, ParameterSpecification>
{
{ "path", new ParameterSpecification { Type = ParameterType.String } }
}
}
);
await client.Datasets.CreateOrUpdateAsync(
resourceGroup, dataFactoryName, blobDatasetName, blobDataset);
Create pipeline
string pipelineName = "mypipeline";
PipelineResource pipeline = new PipelineResource
{
Parameters = new Dictionary<string, ParameterSpecification>
{
{ "inputPath", new ParameterSpecification { Type = ParameterType.String } },
{ "outputPath", new ParameterSpecification { Type = ParameterType.String } }
},
Activities = new List<Activity>
{
new CopyActivity
{
Name = "CopyFromBlobToBlob",
Inputs = new List<DatasetReference>
{
new DatasetReference()
{
ReferenceName = blobDatasetName,
Parameters = new Dictionary<string, object>
{
{ "path", "#pipeline().parameters.inputPath" }
}
}
},
Outputs = new List<DatasetReference>
{
new DatasetReference
{
ReferenceName = blobDatasetName,
Parameters = new Dictionary<string, object>
{
{ "path", "#pipeline().parameters.outputPath" }
}
}
},
Source = new BlobSource { },
Sink = new BlobSink { }
}
}
};
await client.Pipelines.CreateOrUpdateAsync(resourceGroup, dataFactoryName, pipelineName, pipeline);
Run the pipeline
// specify the container and input folder from which all files
string inputBlobPath =
"<path to existing blob(s) to copy data from, e.g. containername/inputdir>";
//specify the contains and output folder where the files are copied
string outputBlobPath =
"<the blob path to copy data to, e.g. containername/outputdir>";
Dictionary<string, object> parameters = new Dictionary<string, object>
{
{ "inputPath", inputBlobPath },
{ "outputPath", outputBlobPath }
};
var runResponse = await client.Pipelines.CreateRunWithHttpMessagesAsync(
resourceGroup, dataFactoryName, pipelineName, parameters: parameters
);
Check result
//Checking pipeline run status...
Console.WriteLine("Checking pipeline run status...");
PipelineRun pipelineRun;
while (true)
{
pipelineRun = client.PipelineRuns.Get(
resourceGroup, dataFactoryName, runResponse.Body.RunId);
Console.WriteLine("Status: " + pipelineRun.Status);
if (pipelineRun.Status == "InProgress" || pipelineRun.Status == "Queued")
System.Threading.Thread.Sleep(15000);
else
break;
}
// Check the copy activity run details
Console.WriteLine("Checking copy activity run details...");
RunFilterParameters filterParams = new RunFilterParameters(
DateTime.UtcNow.AddMinutes(-10), DateTime.UtcNow.AddMinutes(10));
ActivityRunsQueryResponse queryResponse = await client.ActivityRuns.QueryByPipelineRunAsync(
resourceGroup, dataFactoryName, runResponse.Body.RunId, filterParams);
if (pipelineRun.Status == "Succeeded")
Console.WriteLine(queryResponse.Value.First().Output);
else
Console.WriteLine(queryResponse.Value.First().Error);
Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();
So I finally figured out a way to successfully make detect intent calls and provide an input context. My question is whether or not this is the CORRECT (or best) way to do it:
(And yes, I know you can just call DetectIntent(agent, session, query) but I have to provide a input context(s) depending on the request)
var query = new QueryInput
{
Text = new TextInput
{
Text = model.Content,
LanguageCode = string.IsNullOrEmpty(model.Language) ? "en-us" : model.Language,
}
};
var commonContext = new global::Google.Cloud.Dialogflow.V2.Context
{
ContextName = new ContextName(agent, model.sessionId, "my-input-context-data"),
LifespanCount = 3,
Parameters = new Struct
{
Fields = {
{ "Source", Value.ForString(model.Source) },
{ "UserId" , Value.ForString(model.UserId.ToString())},
{ "Name" , Value.ForString(model.FirstName)}
}
}
};
var request = new DetectIntentRequest
{
SessionAsSessionName = new SessionName(agent, model.sessionId),
QueryParams = new QueryParameters
{
GeoLocation = new LatLng {Latitude = model.Latitude, Longitude = model.Longitude},
TimeZone = model.TimeZone ?? "MST"
},
QueryInput = query
};
request.QueryParams.Contexts.Add(commonContext);
// ------------
var creds = GetGoogleCredentials("myCredentials.json");
var channel = new Grpc.Core.Channel(SessionsClient.DefaultEndpoint.Host, creds.ToChannelCredentials());
var client = SessionsClient.Create(channel);
var response = client.DetectIntent(request);
channel.ShutdownAsync();
return response;
Note: I included the explicit ShutDownAsync (it's not in an async call) because I was getting some file locking issues when attempting to re-deploy the WebAPI project (and only after having executed this code).
Thanks
Chris
Updated 4/25: The most basic way I use this is to integrate the user's name into intent responses:
It can also be read from within the webhook/inline fulfillment index.js:
const name = request.body.queryResult && request.body.queryResult.outputContexts && request.body.queryResult.outputContexts[0].parameters.Name
I have some services that require rather complex objects. Every service uses almost the same base object but it needs to be extended for each service.
A simple example:
The Standard Object would be something like:
ContextObject {
params {
Device {
Name: "MyMobileDevice",
ID: 123455691919238
}
}
}
and for my service I need to add some properties under params,
something like:
ContextObject {
params {
Device {
Name: "MyMobileDevice",
ID: 123455691919238
},
requested_employee_id: 112929
}
}
I tried to get this by using JObject and got it working so far but now I cant find a proper example on how to send this object to my server using HttpClient.
Edit:
Here is my full JObject which all Requests need:
public static JObject DefaultContext (string ServiceMethod) {
var Context = new JObject();
Context["version"] = "1.1";
Context["method"] = ServiceMethod;
Context["params"] = JObject.FromObject( new {
Context = JObject.FromObject( new {
User = App.UserSettings.USERNAME,
Password = App.UserSettings.PASSWORD,
SerialNumber = "1234567890", // TODO: use generated id
Locale = "de-DE",
Timestamp = DateTime.Now.ToString("yyyy-MM-ddTHH\\:mm\\:ss.fffzzz"),
Device = JObject.FromObject( new {
DeviceType = "phone",
ProductType = "D6603", // TODO: Get from Device-Info
screen = JObject.FromObject( new {
Density = "xxhdpi", // TODO: Get from Device-Info
resolution = JObject.FromObject( new {
Height = "1920", // TODO: Get from Device-Info
Width = "1080" // TODO: Get from Device-Info
})
}),
version = JObject.FromObject( new {
AppVersion = "myAppVersion", // TODO: Get App-Information LayoutVersion = "1.0"
} )
})
})
});
return mobileContext;
}
For my Requests I need to add parameters under the "params"-Node. Which works with:
mobileContext["params"]["mynewparameter"] = "FOO";
Now I wanted to send this JObject via System.Net.Http-Client to my server with something like this:
var client = new HttpClient ();
client.BaseAddress = new Uri (App.UserSettings.HOST + ":" + App.UserSettings.PORT + App.UserSettings.TYPE);
client.Timeout = 3000;
var context = MyContext.DefaultContext (ServiceMethods.CUSTOMER_LIST_METHOD);
context ["params"] ["myrequestparam"] = "FOO";
var jsonString = JsonConvert.SerializeObject (context);
var responseData = await client.Get???????
Is my general approach correct? How would you do it? Is there a sample on how to handle such dynamic stuff?
I couldn't find a example on how to use httpclient correctly with the Newtonsoft.JSON-Library how far am I from actually working code?
I am using the PayPal sandbox in ASP.Net C# 4.0. I added the following web references:
https://www.sandbox.paypal.com/wsdl/PayPalSvc.wsdl
https://www.paypalobjects.com/wsdl/PayPalSvc.wsdl
When I run this code:
PayPalAPIHelper.PayPalSandboxWS.SetExpressCheckoutReq req = new PayPalAPIHelper.PayPalSandboxWS.SetExpressCheckoutReq()
{
SetExpressCheckoutRequest = new PayPalAPIHelper.PayPalSandboxWS.SetExpressCheckoutRequestType()
{
Version = Version,
SetExpressCheckoutRequestDetails = reqDetails
}
};
// query PayPal and get token
PayPalAPIHelper.PayPalSandboxWS.SetExpressCheckoutResponseType resp = BuildPayPalSandboxWebservice().SetExpressCheckout(req);
In my resp object, the error message says:
Security header is not valid
I was told to give it correct API credentials. I signed up on developer.paypal.com and i'm assuming the email address and password i used are my valid credentials. How and where do I give it my API credentials? Thanks
Did you check the endpoint addresses in your web.config file
Those should be referenced to following url's
For API Certificate => SOAP https://api.sandbox.paypal.com/2.0/
For API Signature => SOAP https://api-3t.sandbox.paypal.com/2.0/
If you are using Signature then use the following code
CustomSecurityHeaderType type = new CustomSecurityHeaderType();
type.Credentials = new UserIdPasswordType()
{
Username = ConfigurationManager.AppSettings["PayPalUserName"], //Not paypal login username
Password = ConfigurationManager.AppSettings["PayPalPassword"], //not login password
Signature = ConfigurationManager.AppSettings["PayPalSignature"]
};
To get Paypal signature follow the link
For more info click here
Update:
Please check the following code it is working for me
CustomSecurityHeaderType type = new CustomSecurityHeaderType();
type.Credentials = new UserIdPasswordType()
{
Username = ConfigurationManager.AppSettings["PayPalUserName"],
Password = ConfigurationManager.AppSettings["PayPalPassword"],
Signature = ConfigurationManager.AppSettings["PayPalSignature"]
};
PaymentDetailsItemType[] pdItem = new PaymentDetailsItemType[1];
pdItem[0] = new PaymentDetailsItemType()
{
Amount = new BasicAmountType(){currencyID = CurrencyCodeType.USD,Value = ItemPrice},
Name = ItemName,
Number = ItemNumber,
Description = ItemDescription,
ItemURL = ItemUrl
};
SetExpressCheckoutRequestDetailsType sdt = new SetExpressCheckoutRequestDetailsType();
sdt.NoShipping = "1";
PaymentDetailsType pdt = new PaymentDetailsType()
{
OrderDescription = OrderDesc,
PaymentDetailsItem = pdItem,
OrderTotal = new BasicAmountType()
{
currencyID = CurrencyCodeType.USD,
Value = ItemPrice
}
};
sdt.PaymentDetails = new PaymentDetailsType[] { pdt };
sdt.CancelURL = "http://localhost:62744/PaymentGateway/PaymentFailure.aspx";
sdt.ReturnURL = "http://localhost:62744/PaymentGateway/ExpressCheckoutSuccess.aspx";
SetExpressCheckoutReq req = new SetExpressCheckoutReq()
{
SetExpressCheckoutRequest = new SetExpressCheckoutRequestType()
{
SetExpressCheckoutRequestDetails = sdt,
Version = "92.0"
}
};
var paypalAAInt = new PayPalAPIAAInterfaceClient();
var resp = paypalAAInt.SetExpressCheckout(ref type, req);
if (resp.Errors != null && resp.Errors.Length > 0)
{
// errors occured
throw new Exception("Exception(s) occured when calling PayPal. First exception: " +
resp.Errors[0].LongMessage);
}
Response.Redirect(string.Format("{0}?cmd=_express-checkout&token={1}",
ConfigurationManager.AppSettings["PayPalOriginalUrl"], resp.Token));