ASP.NET PayPal Parallel Payments - c#

I am needing some assistance with paypal Parallel payments C# I have tried the Classic API and the REST API that paypal has. I am running into cycles and don't know what else to do, I have tried to get chained payments working and I have google'd and there is a huge lack of support so Im now trying Parallel. Let you know i get an 500 internal Server error..
ReceiverList receiverList = new ReceiverList();
receiverList.receiver = new List<Receiver>();
Receiver secondaryReceiver = new Receiver((decimal?)2.00);
secondaryReceiver.email = "xxxxxxxxx#gmail.com";
secondaryReceiver.primary = false;
secondaryReceiver.paymentType = "GOODS";
receiverList.receiver.Add(secondaryReceiver);
Receiver primaryReceiver = new Receiver((decimal?)10.00);
primaryReceiver.email = "xxxxxxxxxxxxxxxxxx-facilitator#gmail.com ";
primaryReceiver.primary = true;
primaryReceiver.paymentType = "GOODS";
primaryReceiver.invoiceId = "123456789";
receiverList.receiver.Add(primaryReceiver);
RequestEnvelope requestEnvelope = new RequestEnvelope("en_US");
string actionType = "Pay";
string returnUrl = "https://devtools-paypal.com/guide/ap_chained_payment/dotnet?success=true";
string cancelUrl = "https://devtools-paypal.com/guide/ap_chained_payment/dotnet?cancel=true";
string currencyCode = "USD";
PayRequest payRequest = new PayRequest(requestEnvelope, actionType, cancelUrl, currencyCode, receiverList, returnUrl);
payRequest.ipnNotificationUrl = "http://replaceIpnUrl.com";
payRequest.feesPayer = "PRIMARYRECEIVER";
payRequest.trackingId = "123456789";
Dictionary<string, string> paypalConfig = new Dictionary<string, string>();
paypalConfig.Add("account1.apiUsername", "xxxxxxxxxxxxxxx-facilitator_api1.gmail.com");
paypalConfig.Add("account1.apiPassword", "xxxxxxxxxxxxxxxxxxx");
paypalConfig.Add("account1.apiSignature", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
paypalConfig.Add("account1.applicationId", "APP-80W284485P519543T");
paypalConfig.Add("IPNEndpoint", "https://www.paypal.com/cgi-bin/webscr");
paypalConfig.Add("url", "https://www.paypal.com/webscr&cmd=_express-checkout&token=");
paypalConfig.Add("endpoint", "https://api-3t.paypal.com/2.0/");
paypalConfig.Add("mode", "sandbox");
PayPal.AdaptivePayments.AdaptivePaymentsService service = new PayPal.AdaptivePayments.AdaptivePaymentsService(paypalConfig);
PayResponse response = service.Pay(payRequest);
string redirectUrl = null;
if (!response.responseEnvelope.ack.ToString().Trim().ToUpper().Equals(AckCode.FAILURE.ToString()) && !response.responseEnvelope.ack.ToString().Trim().ToUpper().Equals(AckCode.FAILUREWITHWARNING.ToString()))
{
redirectUrl = "https://www.sandbox.paypal.com/webscr?cmd=_ap-payment&paykey=" + response.payKey;
}
Now as for the web.config I dont know exactly how to do it or really what to do. i Have found a few things but need of help.
Thanks

Related

Get PayPal Live Transactions

This is an attempt to obtain transactions of my paypal account so I can later insert these into a database for safekeeping on my server. The code below is suppose to get the transactions, between two dates, and return them to me, so I can got through them and obtain the most important information such as email, amount, etc.
It comes back with nothing, when I login to my paypal I can clearly see I have plenty of transactions in this month and the previous month.
What does it to get this list:
public static void GetPayment(CommandArgs args)
{
var config = new Dictionary<string, string>();
config.Add("mode", PayPal.Api.BaseConstants.LiveMode);
config.Add("clientId", "Ady0Bn3J1ik4Bpc29-rTbDYGKaQIY");
config.Add("clientSecret", "EDSRVBfnRLNsBO4k4ewBBUWnXHjJgWJ");
config[PayPal.Api.BaseConstants.HttpConnectionTimeoutConfig] = "30000";
config[PayPal.Api.BaseConstants.HttpConnectionRetryConfig] = "3";
string accessToken = new PayPal.Api.OAuthTokenCredential(config).GetAccessToken();
args.Player.SendInfoMessage("Access Token Obtained");
var apiContext = new PayPal.Api.APIContext(accessToken) { Config = config };
args.Player.SendInfoMessage("Access Token Successful");
var payments = PayPal.Api.Payment.List(apiContext, null, "", null, "", "", DateTime.Now.AddDays(-25).ToString(), DateTime.Now.ToString());
args.Player.SendInfoMessage("{0}", payments.count);
//var payment = PayPal.Api.Payment.Get(apiContext, invoices.invoices[0].id);
}
I attempted to use this code for Transactions:
Dictionary<string, string> config = new Dictionary<string, string>();
config.Add("mode", "live");
config.Add("account1.apiUsername", "marcus1****");
config.Add("account1.apiPassword", "3EB8K");
config.Add("account1.apiSignature", "AFcWx8rxJyxut23nTV");
PayPal.PayPalAPIInterfaceService.PayPalAPIInterfaceServiceService search = new PayPal.PayPalAPIInterfaceService.PayPalAPIInterfaceServiceService(config);
PayPal.PayPalAPIInterfaceService.Model.TransactionSearchReq s = new PayPal.PayPalAPIInterfaceService.Model.TransactionSearchReq();
s.TransactionSearchRequest.StartDate = DateTime.Now.AddDays(-25).ToString();
s.TransactionSearchRequest.EndDate = DateTime.Now.ToString();
var newsearch = search.TransactionSearch(s, "marcus101rr_api1.gmail.com");
args.Player.SendInfoMessage("Found: {0}", newsearch.PaymentTransactions.Count());

C# post JSON data to REST API

I am new to REST API JSON but have been able to consume a few API with asp.net. Here is the problem I am currently facing.
I have been able to send JSON data to an API using this method.
public void PostData()
{
string sName = sysName.Text;
string sDescrip = sysDescrip.Text;
var httpclient = new HttpClient();
httpclient.BaseAddress = new Uri("http://33.248.292.99:8094/bizzdesk/sysconfig/api/");
var sys = new Bizsys(){name= sName, description= sDescrip};
httpclient.PostAsJsonAsync("system", sys);
}
it work just fine.
Now I modify the code in order to accommodate more values thus:
var httpclient = new HttpClient();
// ArrayList paramList = new ArrayList();
httpclient.BaseAddress = new Uri("http://179.683.197.115:9091/tua-slte/api/organisations/");
var org = new Organisation() { id=1, name = "inno", abbreviation = "abx", type="school", sort = 7, isShow = true, createdBy=8, createdDate = "10/04/2017", editedBy = 11, editDate="11/04/2017"};
var bas = new Basic() { id=1, username = "inno", password = "123", firstName="Innocent", lastName="Ujata", email = "ea#bizz.co", mobile = "123456", photo="10201001", loginIp="127.0.0.1", loginDate="10/04/2017", locked=false, organisation = org, createdDate = "10/04/2017", editedBy = 11, editDate="11/04/2017", admin=true};
var org2 = new Organisation2() { id=1, name = "inno", abbreviation = "abx", type="school", sort = 7, isShow = true, createdBy=17, createdDate = "10/04/2017", editedBy = 09, editDate="11/04/2017"};
var hq = new HeadQuarter() { zonId=09, organisation = org2, zonCode = "123", zonName = "Abuja", zonAddress = "123456", zonCity = "Abuja", zonPostalCode = "120076", zonEmail = "answers", zonPhoneNumber = "0908765", zonFaxNumber = "1212", zonState = "FCT", createdBy=17, createdDate = "10/04/2017", editedBy = 11, editDate="11/04/2017", version=1};
var examp = new RootObject() {basic=bas, headQuarter=hq };
var status = httpclient.PostAsJsonAsync("register", examp);
return status;
It keep returning this:
Id = 19, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}"
I hard coded the data to see it work first before making it dynamic.
I have tried using await async method too the result is the same.
all the questions and answers I have seen here are not similar.
What does that mean, and what am I getting wrong?
You are calling an async method, but not awaiting it's results.
Change:
var status = httpclient.PostAsJsonAsync("register", examp);
to
var status = await httpclient.PostAsJsonAsync("register", examp);
Extension method PostAsJsonAsync returns Task<HttpResponseMessage>. You grab this task and see it's details. If you want to return status code of completed request, you should await for task completion and then grab status code from response message:
private async Task<HttpStatusCode> PostSomethingAsync()
{
...
var response = await httpclient.PostAsJsonAsync("register", examp);
return response.StatusCode;
}
Or you can synchronously wait for request completion:
private HttpStatusCode PostSomething()
{
...
var response = httpclient.PostAsJsonAsync("register", examp).Result;
return response.StatusCode;
}
That's cause you are not awaiting the call like
var status = await httpclient.PostAsJsonAsync("register", examp);
Or, use ConfigureAwait()
var status = httpclient.PostAsJsonAsync("register", examp).ConfigureAwait(false);

paypal sandbox test account in windows form application in C# for POS credit card swipe

I create sample a windows form application.
I download pay pal sdk in visual studio.
I create paypal sandbox test account
whre to add the credential details?
where we put app id:
Sandbox test AppID:
APP-80W284485P519543T
I have copy some code for winform app while click a button that is.
Dictionary<string, string> sdkConfig = new Dictionary<string, string>();
sdkConfig.Add("mode", "sandbox");
accessToken = new OAuthTokenCredential("AQkquBDf1zctJOWGKWUEtKXm6qVhueUEMvXO_-MCI4DQQ4-LWvkDLIN2fGsd", "EL1tVxAjhT7cJimnz5-Nsx9k2reTKSVfErNQF-CmrwJgxRtylkGTKlU4RvrX", sdkConfig).GetAccessToken();
HttpContext CurrContext = HttpContext.Current;
APIContext apiContext = new APIContext(accessToken);
Item item = new Item();
item.name = _ItemDescription;
item.currency = "USD";
item.price = _Amount;
item.quantity = "1";
item.sku = _UPC;
List<Item> itms = new List<Item>();
itms.Add(item);
ItemList itemList = new ItemList();
itemList.items = itms;
Address billingAddress = new Address();
billingAddress.city = "Chennai";
billingAddress.country_code = "US";
billingAddress.line1 = "11/12";
billingAddress.line2 = "Andavar nager main street";
billingAddress.postal_code = "600089";
billingAddress.state = "Tamil nadu";
CreditCard crdtCard = new CreditCard();
crdtCard.billing_address = billingAddress;
crdtCard.cvv2 = 2222;
crdtCard.expire_month = 4;
crdtCard.expire_year = 2020;
crdtCard.first_name = "Arul";
crdtCard.last_name = "Murugan";
crdtCard.number = "4032039053301695";
crdtCard.type = "visa";
Details details = new Details();
details.tax = "0";
details.shipping = "0";
details.subtotal = _Amount;
Amount amont = new Amount();
amont.currency = "USD";
amont.total = _Amount;
amont.details = details;
Transaction tran = new Transaction();
tran.amount = amont;
tran.description = _ItemDescription;
tran.item_list = itemList;
List<Transaction> transactions = new List<Transaction>();
transactions.Add(tran);
FundingInstrument fundInstrument = new FundingInstrument();
fundInstrument.credit_card = crdtCard;
List<FundingInstrument> fundingInstrumentList = new List<FundingInstrument>();
fundingInstrumentList.Add(fundInstrument);
PayerInfo pi = new PayerInfo();
pi.email = "sysumurugan-facilitator#gmail.com";
pi.first_name = "Arul";
pi.last_name = "Murugan";
Payer payr = new Payer();
payr.funding_instruments = fundingInstrumentList;
payr.payment_method = "credit_card";
payr.payer_info = pi;
pi.shipping_address = new ShippingAddress
{
city = "San Mateo",
country_code = "US",
line1 = "SO TEST",
line2 = "",
postal_code = "94002",
state = "CA",
};
Payment paymnt = new Payment();
paymnt.intent = "sale";
paymnt.payer = payr;
paymnt.transactions = transactions;
try
{
Payment createdPayment = paymnt.Create(apiContext);
CurrContext.Items.Add("ResponseJson", JObject.Parse(createdPayment.ConvertToJson()).ToString(Formatting.Indented));
}
catch (PayPal.Exception.PayPalException ex)
{
if (ex.InnerException is PayPal.Exception.ConnectionException)
{
CurrContext.Response.Write(((PayPal.Exception.ConnectionException)ex.InnerException).Response);
}
else
{
CurrContext.Response.Write(ex.Message);
}
}
catch (Exception es)
{
MessageBox.Show( es.ToString());
}
CurrContext.Items.Add("RequestJson", JObject.Parse(paymnt.ConvertToJson()).ToString(Formatting.Indented));
my reference link is
http://pastebin.com/H7VuPQs4
Parsing a PayPal REST Credit Card Transaction Response (JSON),
C# PayPal REST API Checkout with Credit Card
please explian to me any other way for credit card transaction for POS(Point Of Sale) through win form application.
The PayPal .NET SDK is meant for server applications (e.g. ASP.NET) where application credentials are stored in a secure manner. Using the SDK directly from a WinForms application running on a POS system presents a security risk because your merchant account credentials are not stored in a secure manner. Ideally, the POS system should be communicating back to a secure server somewhere that performs the processing.
With that said, this use case is what PayPal Here is designed for.

Unable Post tweet From C# Aaplication

i'm using oauth and twitterizer in my C# apps, and after trying for several times. and it won't get any exception, error. but it's doesn't want to post it to twitter.
here is my code
protected void Page_Load(object sender, EventArgs e)
{
BLTgUser objBLTgUser = new BLTgUser();
if (!objBLTgUser.IsLogin) objBLTgUser.GoToLoginPage(HttpContext.Current.Request.Url.AbsoluteUri);
m_strIdGods = objBLTgUser.IdGods;
BLGodsProfile objGods = new BLGodsProfile();
tbmgodsprofile objGodsProfile = objGods.GetGodsByIdGods(m_strIdGods);
string reqToken = Request.QueryString["oauth_token"].ToString();
string pin = Request.QueryString["oauth_verifier"].ToString();
var oauth_consumerKey = System.Configuration.ConfigurationManager.AppSettings["TwitterConsumerKey"];
var oauth_consumerSecret = System.Configuration.ConfigurationManager.AppSettings["TwitterConsumerSecret"];
var tokens = OAuthUtility.GetAccessToken(
oauth_consumerKey,
oauth_consumerSecret,
reqToken,
pin);
string accessToken = tokens.Token;
string accessTokenSecret = tokens.TokenSecret;
objGodsProfile.twittertoken = accessToken;
objGodsProfile.twitterpin = accessTokenSecret;
objGodsProfile.twitterstatus = "1";
objGods.UpdateGodsProfile(objGodsProfile);
}
i'm trying store the token and tokensecret to Database, it's for the next uses.
string v_str = "";
BLEnumHelper m_BLEnumHelper = new BLEnumHelper();
BLGodsProfile userprofile = new BLGodsProfile();
tbmgodsprofile godsAccessToken = userprofile.GetGodsByIdGods(m_strIdGods);
string reqToken = godsAccessToken.twittertoken;
string reqTokenAccess = godsAccessToken.twitterpin;
var oauth_consumerKey = System.Configuration.ConfigurationManager.AppSettings["TwitterConsumerKey"];
var oauth_consumerSecret = System.Configuration.ConfigurationManager.AppSettings["TwitterConsumerSecret"];
OAuthTokens accesstoken = new OAuthTokens()
{
AccessToken = reqToken,
AccessTokenSecret = reqTokenAccess ,
ConsumerKey = oauth_consumerKey,
ConsumerSecret = oauth_consumerSecret
};
TwitterResponse<TwitterStatus> response = TwitterStatus.Update(accesstoken,p_strMessage);
if (response.Result == RequestResult.Success)
{
Response.Write("we did it!");
}
else
{
Response.Write("it's all bad.");
}
and after the 2nd code be called, it wont' post to twitter.
Twitterizer is no longer maintained.
https://github.com/Twitterizer/Twitterizer/blob/develop/README.mediawiki
Twitterizer not supporting Twitter's new API version 1.1, you can't use it for development.
As an alternative, I recommend CoreTweet for you.

GeoCodeRequest() constructor returns null

I'm trying to create a wcf service that consumes Bing's Geocoding soap service. But when ever i try to set init a new GeoCodeRequest using it's constructor it returns a null.
When I call request.Query = address; I get a null value error referring to request .
public string RequestLocation(string address)
{
const string key = "mybingapplicationId";
var request = new GeocodeRequest();
request.Credentials.ApplicationId = key;
request.Query = address;
var filters = new ConfidenceFilter[1];
filters[0] = new ConfidenceFilter { MinimumConfidence = Confidence.High };
var geocodeOptions = new GeocodeOptions { Filters = filters };
request.Options = geocodeOptions;
// Make the geocode request
var geocodeService = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
var geocodeResponse = geocodeService.Geocode(request);
return geocodeResponse.Results[0].DisplayName;
}
[UnitTest]
[TestMethod()]
[HostType("ASP.NET")]
[AspNetDevelopmentServerHost("C:\\Development\\WcfService1\\WcfService1", "/")]
[UrlToTest("http://localhost:24842/")]
[DeploymentItem("WcfService1.dll")]
public void RequestLocationTest()
{
var target = new TestService.BingEngineClient();
var address = string.Format("1600 Pennsylvania Avenue, {0}, {1}","Washington", "DC");
var expected = string.Empty;
var actual = target.RequestLocation(address);
Assert.IsNotNull(actual);
Assert.Inconclusive("Verify the correctness of this test method.");
}
First the code is missing initialization of the Credentials.
request.Credentials = new GeocodeService.Credentials();
When you go through Creating a Bing Maps Account you have to use their application to
Create a Bing Maps Key for the specific application in question. Note that this is different from your account key.
public string RequestLocation(string address)
{
var request = new GeocodeRequest {Credentials = new Credentials {ApplicationId = _key}, Query = address};
var filters = new ConfidenceFilter[1];
filters[0] = new ConfidenceFilter { MinimumConfidence = Confidence.High };
var geocodeOptions = new GeocodeOptions { Filters = filters };
request.Options = geocodeOptions;
// Make the geocode request
var geocodeService = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
var geocodeResponse = geocodeService.Geocode(request);
return string.Format("Longitude:{0},Latitude:{1}", geocodeResponse.Results[0].Locations[0].Longitude,
geocodeResponse.Results[0].Locations[0].Latitude);
}

Categories

Resources