Adding Google contacts won't work - c#

I got this code to "work" (read not throwing an exception). But the contact is not added to my gmail contacts as it should (nor on my android phone which sync contacts).
Note that I can read the contacts correctly so the credentials are right.
I read that I should check for a Status on the request, but the only Status I see is a property of ContactEntry and it's always null.
This is a console app for tests.
public static void AddContact(ContactDetail contact)
{
GContactService = new ContactsService("Contact Infomation");
GContactService.setUserCredentials("myemail#gmail.com", "mypassword");
ContactEntry newEntry = new ContactEntry();
newEntry.Title.Text = contact.Name;
newEntry.Name = new Name() { FullName = "Tristan Savage", GivenName = "Tristan", FamilyName = "Savage"};
EMail primaryEmail = new EMail(contact.EmailAddress1);
primaryEmail.Primary = true;
primaryEmail.Rel = ContactsRelationships.IsWork;
newEntry.Emails.Add(primaryEmail);
PhoneNumber phoneNumber = new PhoneNumber(contact.Phone);
phoneNumber.Primary = true;
phoneNumber.Rel = ContactsRelationships.IsMobile;
newEntry.Phonenumbers.Add(phoneNumber);
PostalAddress postalAddress = new PostalAddress();
postalAddress.Value = contact.Address;
postalAddress.Primary = true;
postalAddress.Rel = ContactsRelationships.IsCompanyMain;
newEntry.PostalAddresses.Add(new StructuredPostalAddress() { City = "montreal", Label = "Bureau"});
newEntry.Content.Content = contact.Details;
Uri feedUri = new Uri(ContactsQuery.CreateContactsUri("default")); //default
ContactEntry createdEntry = (ContactEntry)GContactService.Insert(feedUri, newEntry);
}

I finally figured it out. The GroupMembership is required in order for the contact to get to the mobile device!
Here is the missing part:
var groupMembership = new GroupMembership
{
HRef = "http://www.google.com/m8/feeds/groups/" + utilisateur.CourrielGmailContacts + "/base/6"
};
newEntry.GroupMembership.Add(groupMembership);

Try commenting some lines. With only the name and email, you should be able to create your contact.
I'm able to create a contact with the .NET example here:
https://developers.google.com/google-apps/contacts/v3/?hl=fr#creating_contacts
with Request initialized this way:
ContactsRequest Request = new ContactsRequest(new RequestSettings("appName", "user#gmail.com", "password"));
Please note that your new contact is not associated to a group. So you won't see the contact appearing in "My Contacts"/"Mes Contacts". You should see it in "Other contacts"/"Autres contacts".

Related

Stripe Payment integration error 'No such token'

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);

Xero invoice send email using standard .NET library

Here I have created my project on the standard .NET library to GET/POST invoices. But as I want to email the invoice to which it's being created on that name. Here is my sample code below to create invoice.
public async Task<ActionResult> Create(string Name, string LineDescription, string LineQuantity, string LineUnitAmount, string LineAccountCode)
{
var xeroToken = TokenUtilities.GetStoredToken();
var utcTimeNow = DateTime.UtcNow;
var serviceProvider = new ServiceCollection().AddHttpClient().BuildServiceProvider();
var httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();
XeroConfiguration XeroConfig = new XeroConfiguration
{
ClientId = ConfigurationManager.AppSettings["XeroClientId"],
ClientSecret = ConfigurationManager.AppSettings["XeroClientSecret"],
CallbackUri = new Uri(ConfigurationManager.AppSettings["XeroCallbackUri"]),
Scope = ConfigurationManager.AppSettings["XeroScope"],
State = ConfigurationManager.AppSettings["XeroState"]
};
if (utcTimeNow > xeroToken.ExpiresAtUtc)
{
var client = new XeroClient(XeroConfig, httpClientFactory);
xeroToken = (XeroOAuth2Token)await client.RefreshAccessTokenAsync(xeroToken);
TokenUtilities.StoreToken(xeroToken);
}
string accessToken = xeroToken.AccessToken;
string xeroTenantId = xeroToken.Tenants[0].TenantId.ToString();
//string xeroTenantId = xeroToken.Tenants[1].TenantId.ToString();
var contact = new Contact();
contact.Name = Name;
var line = new LineItem()
{
Description = LineDescription,
Quantity = decimal.Parse(LineQuantity),
UnitAmount = decimal.Parse(LineUnitAmount),
AccountCode = LineAccountCode
};
var lines = new List<LineItem>() { line };
//var lines = new List<LineItem>();
//for (int j = 0;j < 5;j++)
//{
// lines.Add(line);
//}
var invoice = new Invoice()
{
Type = Invoice.TypeEnum.ACCREC,
Contact = contact,
Date = DateTime.Today,
DueDate = DateTime.Today.AddDays(30),
LineItems = lines
};
var invoiceList = new List<Invoice>();
invoiceList.Add(invoice);
var invoices = new Invoices();
invoices._Invoices = invoiceList;
var AccountingApi = new AccountingApi();
var response = await AccountingApi.CreateInvoicesAsync(accessToken, xeroTenantId, invoices);
RequestEmpty _request = new RequestEmpty();
//trying this method to send email to specified invoice....
//var test = await AccountingApi.EmailInvoiceAsync(accessToken, xeroTenantId, Guid.NewGuid(), null);
var updatedUTC = response._Invoices[0].UpdatedDateUTC;
return RedirectToAction("Index", "InvoiceSync");
}
Now as I learned that Xero allows sending email to that specified invoice, here is a link which I learned.
https://developer.xero.com/documentation/api/invoices#email
But as try to find method in the .NET standard library for Xero I stumble upon this method.
var test = await AccountingApi.EmailInvoiceAsync(accessToken, xeroTenantId, Guid.NewGuid(), null);
How can I use this method to send email to a specified invoice ..?
It throws me an error regarding Cannot assign void to an implicitly-typed variable.
There is another method also in this library.
var test2 = await AccountingApi.EmailInvoiceAsyncWithHttpInfo(accessToken, xeroTenantId, Guid.NewGuid(), null);
As Guid.NewGuid() i have used is for only testing will add created GUID when I understand how these two methods operate.
Update 1:
Here is the method second method i used.
await AccountingApi.EmailInvoiceAsyncWithHttpInfo(accessToken, xeroTenantId, Guid.NewGuid(), null)
Update 2:
Here is the code i used.
public async Task EmailInvoiceTest(string accessToken,string xeroTenantId,Guid invoiceID, RequestEmpty requestEmpty)
{
var AccountingApi = new AccountingApi();
await AccountingApi.EmailInvoiceAsync(accessToken, xeroTenantId, invoiceID, requestEmpty).ConfigureAwait(false);
}
The return type of method EmailInvoiceAsync seems to be Task with return type void. If you await the task, there is no return type which could be assigned to a variable. Remove the variable assignment and pass a valid argument for parameter of type RequestEmpty to solve the problem.
RequestEmpty requestEmpty = new RequestEmpty();
await AccountingApi.EmailInvoiceAsync(accessToken, xeroTenantId, Guid.NewGuid(), requestEmpty);
For an example test see here
IMPORTANT: According to the documentation (see section Emailing an invoice) the invoice must be of Type ACCREC and must have a valid status for sending (SUMBITTED, AUTHORISED or PAID).

Google Shared Contacts - Not appearing in directory

I am creating shared contacts in google, it creates the contact, but I can't see the contacts in the directory in google contacts.
I have looked for answers and found this probably closest.. but I can't seem to get it right...
Here is some code:
string s = "https://www.google.com/m8/feeds";
string targetUri = #"https://www.google.com/m8/feeds/contacts/mycompany.com/full";
string serviceAccountEmail = "123456789012-xxxx1x1xx11x1xxxxxxx11xxxx1xxx11#developer.gserviceaccount.com";
string serviceClientId = "123456789012-xxxx1x1xx11x1xxxxxxx11xxxx1xxx11.apps.googleusercontent.com";
X509Certificate2 certificate = new X509Certificate2(#"C:\All\mygcertificate-1xx1xxx1xx11.p12", "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[]
{
"http://www.google.com/m8/feeds/contacts/"
},
User = "my.user#mycompany.com"
}.FromCertificate(certificate));
string AuthenticationToken1 = string.Empty;
if (credential.RequestAccessTokenAsync(CancellationToken.None).Result)
{
AuthenticationToken1 = credential.Token.AccessToken;
}
Service service = new Service(s, serviceClientId);
GAuthSubRequestFactory factory = new GAuthSubRequestFactory(s, serviceClientId);
factory.Token = AuthenticationToken1;
service.RequestFactory = factory;
Contact ct = new Contact();
ct.Name = new Google.GData.Extensions.Name() { GivenName = "Ron", FamilyName = "Swanson", FullName = "Ron Swanson" };
ct.Emails.Add(new Google.GData.Extensions.EMail("Ron.Swanson#someclient.com", #"http://schemas.google.com/g/2005#work") { Primary = true });
ct.Phonenumbers.Add(new Google.GData.Extensions.PhoneNumber("2345555522") { Rel = #"http://schemas.google.com/g/2005#work", Primary = true});
AtomCategory atc = new AtomCategory();
atc.Term = #"http://schemas.google.com/contact/2008#contact";
atc.Scheme = #"http://schemas.google.com/g/2005#kind";
ct.Categories.Add(atc);
var atomentrytoinsert = ct.AtomEntry;
var result = service.Insert(new Uri(targetUri), atomentrytoinsert);
//Stream getresult = service.Query(new Uri(targetUri)); //this read actually gets the records i inserted...
If i run that last commented out line, i can see the entries I created ... but when I go to google contacts and click directory - They are not there. Also not on autocomplete when I compose email... Am I missing a attribute somewhere.
I have left the entries over 24 hours (I created them on Friday).
Would appreciate any input.
I tryed the sharedcontact API yesterday, the new contacts were not visible in directory.
But this morning the autocomplete has suggested the new contacts! To make them visible in the directory I had to open the Admin google Console->google apps-> contacts -> advanced settings and checked the " shows both the profiles of the domain is the Domain Shared Contacts"
It worked immediately for me, I hope help you!

Code connect to Google Analytics API with C# error

I trying using Google Analytics with C# to get stats information to display in my webiste
Here is my code
public ActionResult Index()
{
string userName = "admin#email.com";
string passWord = "mypass";
string profileId = "ga:xxxxxxxx";
string key = "2d751338cb092ef8da65f716e37a48604386c9sw";
string dataFeedUrl = "https://www.google.com/analytics/feeds/data"+key;
var service = new AnalyticsService("API Project");
service.setUserCredentials(userName, passWord);
var dataQuery = new DataQuery(dataFeedUrl)
{
Ids = profileId,
Metrics = "ga:pageviews",
Sort = "ga:pageviews",
GAStartDate = new DateTime(2010, 3, 1).ToString("yyyy-MM-dd"),
GAEndDate = DateTime.Now.ToString("yyyy-MM-dd")
};
var dataFeed = service.Query(dataQuery);
var totalEntry = dataFeed.Entries[0];
ViewData["Total"] = ((DataEntry)(totalEntry)).Metrics[0].Value;
dataQuery.GAStartDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
dataQuery.GAEndDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
dataFeed = service.Query(dataQuery);
var yesterdayEntry = dataFeed.Entries[0];
ViewData["Yesterday"] = ((DataEntry)(yesterdayEntry)).Metrics[0].Value;
dataQuery.GAStartDate = DateTime.Now.ToString("yyyy-MM-dd");
dataQuery.GAEndDate = DateTime.Now.ToString("yyyy-MM-dd");
dataFeed = service.Query(dataQuery);
var todayEntry = dataFeed.Entries[0];
ViewData["Today"] = ((DataEntry)(todayEntry)).Metrics[0].Value;
return View(dataFeed.Entries);
}
But when i run the code it always said "{"Invalid credentials"}"
Not sure why i facing this error while i checked many time about the key,username,password and profileId
Anyone facing this problem,can help me?
Many thanks
I think that your url is wrong. try in this way (you are missing ?key=).
string dataFeedUrl = "https://www.google.com/analytics/feeds/data?key="+key;
refer this google example where there is this example that should help you
public DataFeedExample()
{
// Configure GA API.
AnalyticsService asv = new AnalyticsService("gaExportAPI_acctSample_v2.0");
// Client Login Authorization.
asv.setUserCredentials(CLIENT_USERNAME, CLIENT_PASS);
// GA Data Feed query uri.
String baseUrl = "https://www.google.com/analytics/feeds/data";
DataQuery query = new DataQuery(baseUrl);
query.Ids = TABLE_ID;
query.Dimensions = "ga:source,ga:medium";
query.Metrics = "ga:visits,ga:bounces";
query.Segment = "gaid::-11";
query.Filters = "ga:medium==referral";
query.Sort = "-ga:visits";
query.NumberToRetrieve = 5;
query.GAStartDate = "2010-03-01";
query.GAEndDate = "2010-03-15";
Uri url = query.Uri;
Console.WriteLine("URL: " + url.ToString());
// Send our request to the Analytics API and wait for the results to
// come back.
feed = asv.Query(query);
}
refer also this guide to configure your project
Also follow this guide to use OAuth 2.0

'Security header is not valid' using PayPal sandbox in .NET

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));

Categories