I am using Vault to stored credit card information to Paypal sandbox account which is done.
Now i want to integrate the payment process using stored credit card id. please guide how achieve this. Below are code block.
public class HomeController : Controller
{
public ActionResult Index()
{
//
PaypalCCModel ccmodel = new PaypalCCModel();
ccmodel.Number = "5555555555554444"; //"4111111111111111"; //"4012888888881881";// "4417119669820331"; // Visa
ccmodel.ExpireMonth = "11";
ccmodel.ExpireYear = "2021";
//ccmodel.cvv2 = "222";
ccmodel.Type = "MasterCard";
PaymentViaStoredCard(StoreCreditCardInPaypal(ccmodel));
return View();
}
// It return Vault Credit Card Id
private string StoreCreditCardInPaypal(PaypalCCModel ccmodel)
{
Address billingAddress = new Address();
billingAddress.city = "Johnstown";
billingAddress.country_code = "US";
billingAddress.line1 = "52 N Main ST";
billingAddress.postal_code = "43210";
billingAddress.state = "OH";
//Creating the CreditCard Object and assigning values
CreditCard credtCard = new CreditCard();
credtCard.expire_month = int.Parse(ccmodel.ExpireMonth);
credtCard.expire_year = int.Parse(ccmodel.ExpireYear);
credtCard.number = ccmodel.Number;
credtCard.type = ccmodel.Type.ToLower();
//credtCard.cvv2 = ccmodel.cvv2;
credtCard.first_name = "pankaj";
credtCard.last_name = "Kumar";
credtCard.billing_address = billingAddress;
try
{
//Getting the API Context to authenticate the call to Paypal Server
PayPal.Api.APIContext apiContext = Configuration.GetAPIContext();
Dictionary<string, string> headers = new Dictionary<string, string>();
//headers.Add("Content-Type", "application/json");
//headers.Add("Authorization", "Bearer "+ apiContext.AccessToken.ToString());
apiContext.HTTPHeaders = headers;
// Storing the Credit Card Info in the PayPal Vault Server
CreditCard createdCreditCard = credtCard.Create(apiContext);
//Saving the User's Credit Card ID returned by the PayPal
//You can use this ID for future payments via User's Credit Card
//SaveCardID(User.Identity.Name, createdCreditCard.id);
return createdCreditCard.id;
}
catch (PayPal.PayPalException ex)
{
//Logger.LogError("Error: " + ex.Message);
return "-1";
}
catch (Exception ex)
{
//Logger.LogError("Error: " + ex.Message);
}
return "-1";
}
public void PaymentViaStoredCard(string CardID)
{
// Preparing Item
Item item = new Item();
item.name = "Item Name";
item.currency = "USD";
item.price = "1";
item.quantity = "1";
item.sku = "sku-1123324";
List<Item> itms = new List<Item>();
itms.Add(item);
ItemList itemList = new ItemList();
itemList.items = itms;
//Here is the Credit Card detail which we need to use from our database
CreditCardToken credCardToken = new CreditCardToken();
//Here, we are assigning the User's Credit Card ID which we saved in Database
credCardToken.credit_card_id = CardID;
//Specify Payment Details
Details details = new Details();
details.shipping = "1";
details.subtotal = "1";
details.tax = "1";
//Specify the Total Amount
Amount amnt = new Amount();
amnt.currency = "USD";
// Total must be equal to the sum of shipping, tax and subtotal.
amnt.total = "3";
amnt.details = details;
//Create Transaction Object
Transaction tran = new Transaction();
tran.amount = amnt;
tran.description = "This is the recurring payment transaction";
tran.item_list = itemList;
//Adding the transaction above to the list
List<Transaction> transactions = new List<Transaction>();
transactions.Add(tran);
//Specifying the funding Instrument here.
//Notice that we are not using any credit card details here
//But we are using the Credit Card Object which has the Card ID
FundingInstrument fundInstrument = new FundingInstrument();
fundInstrument.credit_card_token = credCardToken;
//Adding the Funding Instrument to the list
List<FundingInstrument> fundingInstrumentList = new List<FundingInstrument>();
fundingInstrumentList.Add(fundInstrument);
//Specify the fundind Instrument List and Payment Method as Credit Card
//Because we are making the payment using the store Credit Card
Payer payr = new Payer();
payr.funding_instruments = fundingInstrumentList;
payr.payment_method = "credit_card";
//Finally Making payment Object and filling it with values
Payment pymnt = new Payment();
pymnt.intent = "sale";
pymnt.payer = payr;
pymnt.transactions = transactions;
try
{
//Getting the API Context to authenticate the Call to Paypal Server
PayPal.Api.APIContext apiContext = Configuration.GetAPIContext();
// Making the payment using a valid APIContext
Payment createdPayment = pymnt.Create(apiContext);
}
catch (PayPal.PayPalException ex)
{
//Logger.LogError("Error: " + ex.Message);
}
}
}
The PaymentViaStoredCard method is stored credit card information on PayPal sandbox vault and return vault Card id which is passed to PaymentViaStoredCard method to pay amount PayPal. But I am getting error in PaymentViaStoredCard method like internal server error.
The full error description is
{"name":"INTERNAL_SERVICE_ERROR","message":"An internal service error occurred.","information_link":"developer.paypal.com/docs/api/payments/…"}
Related
How can I retrieve the payers email address from a webhook event using the .NET SDK? I need the email to create a purchase with LeadDyno.
UPDATE
Here's how you do it...
var requestBody = string.Empty;
using (var reader = new StreamReader(HttpContext.Request.InputStream))
{
requestBody = reader.ReadToEnd();
}
JObject webhookEvent = JObject.Parse(requestBody);
payerEmail = webhookEvent["resource"]["payer"]["payer_info"]["email"].ToString();
I'm currently using the Adaptive Payments on my website. When a buyer purchases a product from one of my merchants, I get my commission and then the seller gets the rest of the profit.
The issue is that the payment that the seller receives is of payment type SERVICES, instead of GOODS. When this happens, my sellers lose seller protection.
I have tried setting the paymentType property of the Reciever class but no luck, the transaction still comes to my seller as paymentType SERVICES.
Please advise. Can I set the Receiver paymentType = GOODS is it possible?
Thanks!
ReceiverList receiverList = new ReceiverList();
decimal merchantFee = new decimal(0.04);
decimal baseCommission = (orderAmount * merchantFee);
double finalCommission = Convert.ToDouble(baseCommission);
finalCommission = GlobalHelper.RoundUp(finalCommission, 2);
receiverList.receiver = new List<Receiver>();
Receiver primaryReceiver = new Receiver();
primaryReceiver.amount = orderAmount;
primaryReceiver.email = primaryRecieverEmail;
primaryReceiver.primary = true;
primaryReceiver.paymentType = "GOODS";
receiverList.receiver.Add(primaryReceiver);
Receiver secondaryReceiver = new Receiver();
secondaryReceiver.amount = Convert.ToDecimal(finalCommission);
secondaryReceiver.email = secondaryRecieverEmail;
secondaryReceiver.primary = false;
receiverList.receiver.Add(secondaryReceiver);
RequestEnvelope requestEnvelope = new RequestEnvelope("en_US");
string actionType = "PAY";
string returnUrl = System.Configuration.ConfigurationManager.AppSettings["PaypalReturnUrl"];
string cancelUrl = System.Configuration.ConfigurationManager.AppSettings["PaypalCancelUrl"];
string currencyCode = "USD";
PayRequest payRequest = new PayRequest(requestEnvelope, actionType, cancelUrl, currencyCode, receiverList, returnUrl);
payRequest.ipnNotificationUrl = System.Configuration.ConfigurationManager.AppSettings["PaypalNotifyUrl"];
payRequest.trackingId = (orderId).ToString();
payRequest.memo = String.Format("{0} {1}","Payment for",title);
Dictionary<string, string> sdkConfig = new Dictionary<string, string>();
sdkConfig.Add("mode", System.Configuration.ConfigurationManager.AppSettings["API_MODE"]);
sdkConfig.Add("account1.apiUsername", System.Configuration.ConfigurationManager.AppSettings["API_USERNAME"]);
sdkConfig.Add("account1.apiPassword", System.Configuration.ConfigurationManager.AppSettings["API_PASSWORD"]);
sdkConfig.Add("account1.apiSignature", System.Configuration.ConfigurationManager.AppSettings["API_SIGNATURE"]);
sdkConfig.Add("account1.applicationId", System.Configuration.ConfigurationManager.AppSettings["APPLICATION-ID"]);
AdaptivePaymentsService adaptivePaymentsService = new AdaptivePaymentsService(sdkConfig);
PayResponse payResponse = adaptivePaymentsService.Pay(payRequest);
return payResponse;
How to send successfully push notification of APNS in production
When I use in development, it's work.
But use in production,it appear error.
My app is in App Store, so p12 file is production.
My server side is asp.net.
asp.net code:
//key
//True if you are using sandbox certificate, or false if using production
bool sandbox = false;
string p12File = "InspirePass.p12";
string p12Filename = System.IO.Path.Combine(MapPath("~"), p12File);
string p12FilePassword = "xxxxxxxx";
NotificationService service = new NotificationService(sandbox, p12Filename, p12FilePassword, 1);
//send
foreach (DataRow eachUserRow in userTable.Rows)
{
//Create a new notification to send
if (eachUserRow["pushStatus"].ToString() == "N")
{ //////no repeat
Notification alertNotification = new Notification(eachUserRow["device_token"].ToString());
alertNotification.Payload.Alert.Body = eachUserRow["menuMessage"].ToString() + "(" + eachUserRow["menuTitle"].ToString() + ")";
alertNotification.Payload.Sound = "default";
alertNotification.Payload.Badge = selectEventPush_IOS.Rows.Count + selectSignPush_IOS.Rows.Count;
// alertNotification.Payload. = 1;
string[] items = new string[1];
string[] items2 = new string[1];
if (userTable.Rows.Count > 0)
{
items[0] = Convert.ToString(selectEventPush_IOS.Rows.Count);
items2[0] = Convert.ToString(selectSignPush_IOS.Rows.Count);
}
alertNotification.Payload.CustomItems.Add("items2", items2);
alertNotification.Payload.CustomItems.Add("items", items);
//Queue the notification to be sent
if (service.QueueNotification(alertNotification))
result = 1;
else
result = -1;
///////change chat_document/pushStatus=Y
string Identifier = "";
Identifier = eachUserRow["Identifier"].ToString();
DataRow yespushuser = DBiphone.UpdatedPushStatus(Identifier);
}
}//end if
service.Close();
service.Dispose();
Response.Write(result.ToString());
i have a mission to make a plug-in in crm 4 which should 1. put in the subject field of an email the name of the account and then 2. put the contact list of account to the cc field of the email.
the first thing i did and it work, but the second... not so much...
i have seen some samples but none of them was close to halp me...
i would like to have help and explain of how to find the list of the contact that belong to the account and then put the list in the cc field.
here is the begining...:
namespace mail
{
public class Class1 : IPlugin
{
public void Execute(IPluginExecutionContext context)
{
DynamicEntity entity = null;
if (context.InputParameters.Properties.Contains("Target") &&
context.InputParameters.Properties["Target"] is DynamicEntity)
{
entity = (DynamicEntity)context.InputParameters.Properties["Target"];
if (entity.Name != EntityName.account.ToString())
{
return;
}
}
else
{
return;
}
try
{
// updating the subject of the email
ICrmService service = context.CreateCrmService(true);
account accountRecord = (account)service.Retrieve("account", ((Key)entity.Properties["accountid"]).Value, new ColumnSet(new string[] { "name" }));
String str = String.Empty;
str = accountRecord.name.ToString();
DynamicEntity followup = new DynamicEntity();
followup.Name = EntityName.email.ToString();
followup.Properties = new PropertyCollection();
followup.Properties.Add(new StringProperty("subject", str));
//updating the CC of the email
TargetCreateDynamic targetCreate = new TargetCreateDynamic();
targetCreate.Entity = followup;
CreateRequest create = new CreateRequest();
create.Target = targetCreate;
CreateResponse created = (CreateResponse)service.Execute(create);
}
catch
{
throw new InvalidPluginExecutionException(
"An error occurred in the AccountUpdateHandler plug-in.");
}
}
}
}
You can try something like this,
List<BusinessEntity> contactList = GetNeededContacts(crmService, sourceEntity);
email targetEmail = GetTargetEmail(crmService, emailid);
foreach (DynamicEntity contact in contactList)
{
activityparty contActParty = new activityparty() { partyid = new Lookup("contact", contact.contactid.Value };
List<activityparty> tmpList = targetEmail.cc.ToList();
tmpList.Add(contActParty);
targetEmail.cc = tmpList.ToArray();
}
crmService.Update(targetEmail);
You only have to develop the function to get the contact, user or account references.
Is it possible to send out an email with multiple email addresses specified in the "to" field? I have it working for single recipients, but can't figure out how to send to multiple, here is my current code for emailing a single user:
public static void sendCRMNotification(string userGuid, string emailSubject, string emailBody, string recipientType)
{
//Set up CRM service
crmService crmservice = GetCrmService();
// Create a FROM activity party for the email.
activityparty fromParty = new activityparty();
fromParty.partyid = new Lookup();
fromParty.partyid.type = EntityName.systemuser.ToString();
fromParty.partyid.Value = new Guid(/*guid of sending user*/);
//Create a TO activity party for email
activityparty toParty = new activityparty();
toParty.partyid = new Lookup();
toParty.partyid.type = EntityName.contact.ToString();
toParty.partyid.Value = new Guid(userGuid);
//Create a new email
email emailInstance = new email();
//set email parameters
emailInstance.from = new activityparty[] { fromParty };
emailInstance.to = new activityparty[] { toParty };
emailInstance.subject = emailSubject;
emailInstance.description = emailBody;
//Create a GUId for the email
Guid emailId = crmservice.Create(emailInstance);
//Create a SendEmailRequest
SendEmailRequest request = new SendEmailRequest();
request.EmailId = emailId;
request.IssueSend = true;
request.TrackingToken = "";
//Execute request
crmservice.Execute(request);
}
This is what I have done in the past. Create the array in the beginning before you set it to the email property.
activityparty[] toParty = new activityparty[2];
toParty[0] = new activityparty();
toParty[0].partyid = new Lookup(EntityName.contact.ToString(), userGuid);
toParty[1] = new activityparty();
toParty[1].partyid = new Lookup(EntityName.contact.ToString(), anotherUserGuid);
emailMessage.to = toParty;