Trying to follow the PayPal .NET tutorial on GitHub.
I've fixed it the best I can but still getting a lot of errors related to missing functions etc. Here is what I have so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PayPal.Api;
using System.Configuration;
using PayPal.Sample.Utilities;
using System.Web.Providers.Entities;
/// <summary>
/// Summary description for OAuthTokenCredential
/// </summary>
public class CredentialManager
{
Dictionary<string, string> _Config = null;
string _AccessToken = string.Empty;
APIContext _APIConText = null;
public CredentialManager()
{
// Get a reference to the config
var config = ConfigManager.Instance.GetProperties();
_Config = config;
// Use OAuthTokenCredential to request an access token from PayPal
var accessToken = new OAuthTokenCredential(config).GetAccessToken();
_AccessToken = accessToken;
//API Context
var apiContext = new APIContext(accessToken);
_APIConText = apiContext;
// Initialize the apiContext's configuration with the default configuration for this application.
apiContext.Config = ConfigManager.Instance.GetProperties();
// Define any custom configuration settings for calls that will use this object.
apiContext.Config["connectionTimeout"] = "1000"; // Quick timeout for testing purposes
// Define any HTTP headers to be used in HTTP requests made with this APIContext object
//if (apiContext.HTTPHeaders == null)
//{
// apiContext.HTTPHeaders = new Dictionary<string, string>();
//}
//apiContext.HTTPHeaders["some-header-name"] = "some-value";
}
public Payment GetPAyment(APIContext apiContext, string paymentid)
{
var payment = Payment.Get(apiContext, paymentid);
return payment;
}
public bool CreatePayment()
{
try
{
bool Success = false;
//var apiContext = Configuration.GetAPIContext();
string payerId = Request.Params["PayerID"];
if (string.IsNullOrEmpty(payerId))
{
var itemList = new ItemList()
{
items = new List<Item>()
{
new Item()
{
name = "Item Name",
currency = "USD",
price = "15",
quantity = "5",
sku = "sku"
}
}
};
var payer = new Payer() { payment_method = "paypal" };
var baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/PaymentWithPayPal.aspx?";
var guid = Convert.ToString((new Random()).Next(100000));
var redirectUrl = baseURI + "guid=" + guid;
var redirUrls = new RedirectUrls()
{
cancel_url = redirectUrl + "&cancel=true",
return_url = redirectUrl
};
var details = new Details()
{
tax = "15",
shipping = "10",
subtotal = "75"
};
var amount = new Amount()
{
currency = "USD",
total = "100.00", // Total must be equal to sum of shipping, tax and subtotal.
details = details
};
var transactionList = new List<Transaction>();
transactionList.Add(new Transaction()
{
description = "Transaction description.",
invoice_number = Common.GetRandomInvoiceNumber(),
amount = amount,
item_list = itemList
});
var payment = new Payment()
{
intent = "sale",
payer = payer,
transactions = transactionList,
redirect_urls = redirUrls
};
var createdPayment = payment.Create(_APIConText);
var links = createdPayment.links.GetEnumerator();
while (links.MoveNext())
{
var link = links.Current;
if (link.rel.ToLower().Trim().Equals("approval_url"))
{
this.flow.RecordRedirectUrl("Redirect to PayPal to approve the payment...", link.href);
}
}
Session.Add(guid, createdPayment.id);
Session.Add("flow-" + guid, this.flow);
}
else
{
var guid = Request.Params["guid"];
var paymentId = Session[guid] as string;
var paymentExecution = new PaymentExecution() { payer_id = payerId };
var payment = new Payment() { id = paymentId };
var executedPayment = payment.Execute(apiContext, paymentExecution);
}
return Success;
}
catch(Exception ex)
{
return false;
}
}
}
I'm getting random errors on the following:
using PayPal.Sample.Utilities;
string payerId = Request.Params["PayerID"];
var baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/PaymentWithPayPal.aspx?";
invoice_number = Common.GetRandomInvoiceNumber(),
Session.Add(guid, createdPayment.id);
Session.Add("flow-" + guid, this.flow);
var guid = Request.Params["guid"];
var paymentId = Session[guid] as string;
var executedPayment = payment.Execute(_APIConText, paymentExecution);
Errors:
"Request" does not exist
"Common" does not exist
"flow" does not exist
"session" is not valid in its current type
I think I'm just missing a reference or something. I'm trying to do it for C# ASP .Net (not MVC)
You'll find the "Common" class here
Common.GetRandomInvoiceNumber() is just generating a random number. I think you would just replace that with your own generated invoice number.
Related
I am trying to use AWS SDK for .NET Core.
Create a table to count views on videos.
Add a view count for a day.
Increment existing count for a day.
Query for video counts between two dates for a video.
.NET Core AWS SDK uses Async methods which are not documented in AWS. There is a feature request on their github page for this to happen.... but it is dated from last year. (https://github.com/aws/aws-sdk-net/issues/787)
CREATE THE TABLE
This works and creates a table on the AWS Console.
var ctRequest = new CreateTableRequest
{
AttributeDefinitions = new List<AttributeDefinition>()
{
new AttributeDefinition
{
AttributeName = "ViewUid",
AttributeType = ScalarAttributeType.S
},
new AttributeDefinition
{
AttributeName = "ViewDate",
AttributeType = ScalarAttributeType.S
}
},
KeySchema = new List<KeySchemaElement>
{
new KeySchemaElement
{
AttributeName = "ViewUid",
KeyType = KeyType.HASH //Partition key
},
new KeySchemaElement
{
AttributeName = "ViewDate",
KeyType = KeyType.RANGE
}
},
ProvisionedThroughput = new ProvisionedThroughput
{
ReadCapacityUnits = 5,
WriteCapacityUnits = 6
},
TableName = _settings.AWSDynamoDBViewCountTable
};
var response = _client.CreateTableAsync(ctRequest).Result;
UPDATE AND ITEM WITH AUTO-INCREMENT A FIELD
This, sadly, is where i hit issues. The old docs are found here under the Atomic Counter section. (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetItemCRUD.html)
Invalid ConditionExpression: Syntax error; token: \"SET\", near: \"SET
VC\"
var viewData = new Document();
viewData["ViewUid"] = videoUid; //Table entry UID
viewData["VideoId"] = videoId; // Video ID
viewData["ViewDate"] = date;
viewData["ViewCount"] = 0;
//Document result = await _viewCountTable.PutItemAsync(viewData);
Expression expr = new Expression();
expr.ExpressionStatement = "SET #VC = #VC + :val";
expr.ExpressionAttributeValues[":val"] = 1;
expr.ExpressionAttributeNames["#VC"] = "ViewCount";
var updateConfig = new UpdateItemOperationConfig() {
ConditionalExpression = expr,
ReturnValues = ReturnValues.UpdatedNewAttributes
};
var result = await _viewCountTable.UpdateItemAsync(viewData, updateConfig);
return result;
QUERY FOR DATE RANGE
Get one video's view count for a date range.
string queryTimeSpanStartString = dateFrom.ToString(AWSSDKUtils.ISO8601DateFormat);
string queryTimeSpanEndString = dateTo.ToString(AWSSDKUtils.ISO8601DateFormat);
var request = new QueryRequest
{
TableName = _settings.AWSDynamoDBViewCountTable,
KeyConditions = new Dictionary<string, Condition>()
{
{
"VideoId", new Condition()
{
ComparisonOperator = "EQ",
AttributeValueList = new List<AttributeValue>()
{
new AttributeValue { S = videoId }
}
}
},
{
"ViewDate",
new Condition
{
ComparisonOperator = "BETWEEN",
AttributeValueList = new List<AttributeValue>()
{
new AttributeValue { S = queryTimeSpanStartString },
new AttributeValue { S = queryTimeSpanEndString }
}
}
}
}
};
var response = await _client.QueryAsync(request);
Any help would be appreciated.
I was able to update the ViewCount with the following code:
string tableName = "videos";
var request = new UpdateItemRequest
{
Key = new Dictionary<string, AttributeValue>() { { "ViewUid", new AttributeValue { S = "replaceVideoIdhere" } } },
ExpressionAttributeNames = new Dictionary<string, string>()
{
{"#Q", "ViewCount"}
},
ExpressionAttributeValues = new Dictionary<string, AttributeValue>()
{
{":incr", new AttributeValue {N = "1"}}
},
UpdateExpression = "SET #Q = #Q + :incr",
TableName = tableName
};
var response = await _dynamoDbClient.UpdateItemAsync(request);
I created a table called "videos" with a partition key named "ViewUid" as string. Let me know if this works for you.
Is there any options for sending OTP while Credit/Debit card payment in authorize.net.
if there is no option how to achieve this
This is the code for getting response from the Authorized.Net
public static ANetApiResponse Run(CustomerDetail cd,decimal amount)
{
ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = AuthorizeNet.Environment.SANDBOX;
ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = new merchantAuthenticationType()
{
name = ConfigurationManager.AppSettings["AuthorizeNetLogin"],
ItemElementName = ItemChoiceType.transactionKey,
Item = ConfigurationManager.AppSettings["AuthorizeNetTransactionKey"],
};
var creditCard = new creditCardType
{
cardNumber = Convert.ToString(cd.cardnumber),
expirationDate = cd.expirationdate,
};
var paymentType = new paymentType { Item = creditCard };
var transactionRequest = new transactionRequestType
{
transactionType = transactionTypeEnum.authOnlyTransaction.ToString(), // authorize only
amount = amount,
payment = paymentType
};
var request = new createTransactionRequest { transactionRequest = transactionRequest };
var controller = new createTransactionController(request);
controller.Execute();
var response = controller.GetApiResponse();
return response;
}
Authorize.Net does not support One Time Password as Authorize.Net does not support money transfers.
I'm trying to set up PayPal to accept payment from my site which calculate fees based on the number of photos they uploaded. Followed a tutorial, but I wanted to pass the price which I calculated in my other controller.
My PayPal controller:
public ActionResult PaymentWithPaypal()
{
APIContext apiContext = PayPalConfig.GetAPIContext();
try
{
string payerId = Request.Params["PayerID"];
if (string.IsNullOrEmpty(payerId))
{
string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/Paypal/PaymentWithPayPal?";
var guid = Convert.ToString((new Random()).Next(100000));
var createdPayment = this.CreatePayment(apiContext, baseURI + "guid=" + guid);
var links = createdPayment.links.GetEnumerator();
string paypalRedirectUrl = null;
while (links.MoveNext())
{
Links lnk = links.Current;
if (lnk.rel.ToLower().Trim().Equals("approval_url"))
{
paypalRedirectUrl = lnk.href;
}
}
Session.Add(guid, createdPayment.id);
return Redirect(paypalRedirectUrl);
}
else
{
var guid = Request.Params["guid"];
var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);
if (executedPayment.state.ToLower() != "approved")
{
return View("FailureView");
}
}
}
catch (Exception ex)
{
Logger.Log("Error" + ex.Message);
return View("FailureView");
}
return View("SuccessView");
}
private PayPal.Api.Payment payment;
private PayPal.Api.Payment ExecutePayment(APIContext apiContext, string payerId, string paymentId)
{
var paymentExecution = new PaymentExecution() { payer_id = payerId };
this.payment = new PayPal.Api.Payment() { id = paymentId };
return this.payment.Execute(apiContext, paymentExecution);
}
private PayPal.Api.Payment CreatePayment(APIContext apiContext, string redirectUrl)
{
var itemList = new ItemList() { items = new List<Item>() };
itemList.items.Add(new Item()
{
name = "Participation Fee",
currency = "USD",
price = "5",
quantity = "1",
sku = "sku"
});
var payer = new Payer() { payment_method = "paypal" };
var redirUrls = new RedirectUrls()
{
cancel_url = redirectUrl,
return_url = redirectUrl
};
var details = new Details()
{
tax = "1",
shipping = "1",
subtotal = "5"
};
var amount = new Amount()
{
currency = "USD",
total = "7",
details = details
};
var transactionList = new List<Transaction>();
transactionList.Add(new Transaction()
{
description = "Transaction description.",
invoice_number = "your invoice number",
amount = amount,
item_list = itemList
});
this.payment = new PayPal.Api.Payment()
{
intent = "sale",
payer = payer,
transactions = transactionList,
redirect_urls = redirUrls
};
return this.payment.Create(apiContext);
}
Controller where my price is calculated:
int Asection;
int Bsection;
int Csection;
int Dsection;
if (viewPhotos.GetA1.Any() || viewPhotos.GetA2.Any() || viewPhotos.GetA3.Any() || viewPhotos.GetA4.Any())
{
Asection = 1;
}
else
{
Asection = 0;
}
if (viewPhotos.GetB1.Any() || viewPhotos.GetB2.Any() || viewPhotos.GetB3.Any() || viewPhotos.GetB4.Any())
{
Bsection = 1;
}
else
{
Bsection = 0;
}
if (viewPhotos.GetC1.Any() || viewPhotos.GetC2.Any() || viewPhotos.GetC3.Any() || viewPhotos.GetC4.Any())
{
Csection = 1;
}
else
{
Csection = 0;
}
if (viewPhotos.GetD1.Any() || viewPhotos.GetD2.Any() || viewPhotos.GetD3.Any() || viewPhotos.GetD4.Any())
{
Dsection = 1;
}
else
{
Dsection = 0;
}
int TotalSection = Asection + Bsection + Csection + Dsection;
viewPhotos.MoneyValue = TotalSection;
int RequiredMoney;
if (TotalSection == 1)
{
RequiredMoney = 20;
}
else if (TotalSection == 2)
{
RequiredMoney = 25;
}
else if (TotalSection == 3)
{
RequiredMoney = 30;
}
else
{
RequiredMoney = 36;
}
viewPhotos.RequiredMoney = RequiredMoney;
return View(viewPhotos);
My view where price was shown to user:
<p>You will need to pay participation fees USD #Model.RequiredMoney.</p>
<h3>Total: USD #Model.RequiredMoney</h3>
#Html.ActionLink("Make Payment with PayPal", "PaymentWithPaypal", "Paypal")
So far the above codes work with the default testing item price and detail on the site. Would appreciate if anyone could help to show how do I set the amount to be collected by PayPal to my calculated price, without any shipping or tax. Thanks in advance.
After searching and reviewing the log for a while, here's how I solved my problem:
At the controller where I calculated my price, I used TempData to store my price:
TempData["ParticipationFee"] = RequiredMoney;
Then at the PaypalController, under CreatePayment function,
var itemList = new ItemList() { items = new List<Item>() };
string FeeAmount = TempData["ParticipationFee"].ToString();
itemList.items.Add(new Item()
{
name = "Participation Fee",
currency = "USD",
price = FeeAmount,
quantity = "1",
sku = "sku"
});
Hit F5 and got a successful response from Paypal Sandbox. Woot!
For customer with existing payment profile id(Saved credit card) we are using "createCustomerProfileTransactionController" as follow for authorization.
public createCustomerProfileTransactionResponse AuthorizePaymentProfile(int customerProfileId, int customerPaymentProfileId, decimal amount)
{
createCustomerProfileTransactionResponse response = null;
ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = environment;
// define the merchant information (authentication / transaction id)
ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = new merchantAuthenticationType()
{
name = apiLoginID,
ItemElementName = ItemChoiceType.transactionKey,
Item = apiTransactionKey,
};
//construct request
var request = new createCustomerProfileTransactionRequest
{
merchantAuthentication = new merchantAuthenticationType
{
name = apiLoginID,
ItemElementName = ItemChoiceType.transactionKey,
Item = apiTransactionKey
},
transaction = new profileTransactionType
{
Item = new profileTransAuthOnlyType
{
customerProfileId = customerProfileId.ToString(),
customerPaymentProfileId = customerPaymentProfileId.ToString(),
amount = amount
}
},
extraOptions = "x_duplicate_window=1"
};
//Prepare Request
var controller = new createCustomerProfileTransactionController(request);
controller.Execute();
//Send Request to EndPoint
response = controller.GetApiResponse();
return response;
}
And for customer without existing payment profile id we using "createTransactionRequest" as follow for authorization.
public createTransactionResponse AuthorizeOneTimePayment(Card cardInfo, decimal amount)
{
createTransactionResponse response = null;
ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = environment;
//define the merchant information (authentication / transaction id)
ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = new merchantAuthenticationType()
{
name = apiLoginID,
ItemElementName = ItemChoiceType.transactionKey,
Item = apiTransactionKey,
};
var creditCard = new creditCardType
{
cardNumber = cardInfo.CardNumber,// "4111111111111111",
expirationDate = cardInfo.ExpirationDate// "0718"
//cardCode=cardInfo.VerificationCode
};
//standard api call to retrieve response
var paymentType = new paymentType { Item = creditCard };
string firstName = string.Empty;
string lastName = string.Empty;
if (!string.IsNullOrWhiteSpace(cardInfo.BillingName))
{
string[] name = GetBillName(cardInfo.BillingName);
firstName = name[0];
lastName = name[1];
}
var transactionRequest = new transactionRequestType
{
transactionType = transactionTypeEnum.authOnlyTransaction.ToString(), // authorize only
amount = amount,
payment = paymentType,
billTo = new customerAddressType
{
firstName = firstName,
lastName = lastName,
address = cardInfo.BillingAddress,
city = cardInfo.BillingCity,
state = cardInfo.BillingState,
zip = cardInfo.BillingZipCode
}
};
var request = new createTransactionRequest { transactionRequest = transactionRequest };
// instantiate the controller that will call the service
var controller = new createTransactionController(request);
controller.Execute();
// get the response from the service (errors contained if any)
response = controller.GetApiResponse();
return response;
}
And following same technique for capture and void a transaction.
My question is can we use "createTransactionRequest" for all transaction like authorize, capture and void a transaction for both customer having payment profile id and one time customer.
I could find any clue in authorize.net on line documentation. Please guide us how to do that.
Yes, you can use createTransactionRequest for Auth/Capture, Auth Only, Prior Auth and Capture, Void and Refund by changing the transactionRequestType and paymentType.
For anyone with the same question, like me, here is the answer.
Note that Order is optional, and obviously profile is optional.
...
var transactionRequest = new transactionRequestType {
transactionType = transactionTypeEnum.authOnlyTransaction.ToString(),
amount = amount,
order = new orderType { invoiceNumber = OrderID, description = desc },
profile = getCustomerPaymentProfile(CustomerProfileId, creditProfileID)
};
...
private customerProfilePaymentType getCustomerPaymentProfile(string CustomerProfileId, string creditProfileID) {
return new customerProfilePaymentType {
customerProfileId = CustomerProfileId,
paymentProfile = new paymentProfile { paymentProfileId = creditProfileID }
};
}
I'm trying to send a mail chimp campaign using asp.net, actually i created successfully the campaign and i can see it through my profile but also i want to send it through my code here is my code so if any one can help!!
private static void CreateCampaignAndSend(string apiKey, string listID)
{
Int32 TemplateID = 0;
string campaignID = string.Empty;
// compaign Create Options
var campaignCreateOpt = new campaignCreateOptions
{
list_id = listID,
subject = "subject",
from_email = "cbx#abc.com",
from_name = "abc",
template_id = TemplateID
};
// Content
var content = new Dictionary<string, string>
{
{"html", "Lots of cool stuff here."}
};
// Conditions
var csCondition = new List<campaignSegmentCondition>();
var csC = new campaignSegmentCondition {field = "interests-" + 123, op = "all", value = ""};
csCondition.Add(csC);
// Options
var csOptions = new campaignSegmentOptions {match = "all"};
// Type Options
var typeOptions = new Dictionary<string, string>
{
{"offset-units", "days"},
{"offset-time", "0"},
{"offset-dir", "after"}
};
// Create Campaigns
var campaignCreate = new campaignCreate(new campaignCreateInput(apiKey, EnumValues.campaign_type.plaintext, campaignCreateOpt, content, csOptions, typeOptions));
campaignCreateOutput ccOutput = campaignCreate.Execute();
campaignSendNow c=new campaignSendNow();
List<Api_Error> error = ccOutput.api_ErrorMessages; // Catching API Errors
if (error.Count <= 0)
{
campaignID = ccOutput.result;
}
else
{
foreach (Api_Error ae in error)
{
Console.WriteLine("\n ERROR Creating Campaign : ERRORCODE\t:" + ae.code + "\t ERROR\t:" + ae.error);
}
}
}