I have implemented a small PayPal PLUS Demo in ASP.NET:
protected void Page_Load(object sender, EventArgs e)
{
var config = ConfigManager.Instance.GetProperties();
config.Add("clientId", "XXXXXXXXXXXXXXXXXXXXXXXXX");
config.Add("clientSecret", "XXXXXXXXXXXXXXXXXXXXXXXXX");
config.Add("mode", "sandbox");
var accessToken = new OAuthTokenCredential(config).GetAccessToken();
var apiContext = new APIContext(accessToken);
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", details = details };
var transactionList = new List<Transaction> { new Transaction() { description = "Transaction description.", invoice_number = new Random().Next(999999).ToString(), amount = amount, item_list = itemList } };
var payment = new Payment() { intent = "sale", payer = payer, transactions = transactionList, redirect_urls = redirUrls };
var createdPayment = payment.Create(apiContext);
var approval_url = createdPayment.links.FirstOrDefault(x => x.rel == "approval_url").href;
hfApprovalUrl.Value = approval_url;
}
<asp:HiddenField runat="server" id="hfApprovalUrl"/>
<script src="https://www.paypalobjects.com/webstatic/ppplus/ppplus.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="ppplus"></div>
<script type="application/javascript">
var approval_url = $('#hfApprovalUrl').val();
var ppp = PAYPAL.apps.PPP({
"approvalUrl": approval_url,
"placeholder": "ppplus",
"mode": "sandbox",
"country": "DE"
});
</script>
Its works so far but if a choose a pay option (e.g. credit card) I will be redirected to PayPal.I want that the user stys on my own page. How can I do this?
Thanks!
Jan
Related
I have some data in activity which I want to get it in RoutingSlipCompleted consume method. I know we can send data with CompletedWithVariables from a activity to b activity. But I was wondering how it is possible to get data from activity in RoutingSlipCompleted. so this is my activity:
public class CheckInventoryActivity : IActivity<ICheckInventoryRequest, CheckInventoryRequestCompensate>
{
private readonly IInventoryService _inventoryService;
private readonly IEndpointNameFormatter _formatter;
public CheckInventoryActivity(IInventoryService inventoryService, IEndpointNameFormatter formatter)
{
_inventoryService = inventoryService;
_formatter = formatter;
}
public async Task<ExecutionResult> Execute(ExecuteContext<ICheckInventoryRequest> context)
{
CheckInventoryRequest model = new CheckInventoryRequest()
{
PartCode = context.Arguments.PartCode
};
var response = await _inventoryService.CheckInventory(model);
var checkInventoryResponse = new CheckInventoryResponse()
{
PartCode = response.Data.PartCode ?? model.PartCode,
Id = response.Data.Id ?? 0,
InventoryCount = response.Data.InventoryCount ?? 0
};
var checkInventoryCustomActionResult = new CustomActionResult<CheckInventoryResponse>()
{
Data = checkInventoryResponse,
IsSuccess = true,
ResponseDesc = "success",
ResponseType = 0
};
var result = response.IsSuccess;
if (!result)
return context.CompletedWithVariables<CheckInventoryRequestCompensate>(
new
{
Result = result,
LogDate = DateTime.Now,
MethodName = "CheckInventoryActivity",
}, new
{
Result = result,
LogDate = DateTime.Now,
MethodName = "CheckInventoryActivity",
CheckInventoryCustomActionResult = checkInventoryCustomActionResult
});
var queueName = _formatter.ExecuteActivity<CallSuccessActivity, ISuccessRequest>();
var uri = new Uri($"queue:{queueName}");
return context.ReviseItinerary(x => x.AddActivity("CallSuccessActivity", uri, new
{
LogDate = DateTime.Now,
MethodName = "CheckInventoryActivity",
CheckInventoryCustomActionResult = checkInventoryCustomActionResult
}));
}
so by the following line of codes I can get data in CallSuccessActivity:
return context.ReviseItinerary(x => x.AddActivity("CallSuccessActivity", uri, new
{
LogDate = DateTime.Now,
MethodName = "CheckInventoryActivity",
CheckInventoryCustomActionResult = checkInventoryCustomActionResult
}));
}
so I can get this data here:
public class CallSuccessActivity : IExecuteActivity<ISuccessRequest>
{
private readonly IRequestClient<ISuccessRequest> _requestClient;
public CallSuccessActivity(IRequestClient<ISuccessRequest> requestClient)
{
_requestClient = requestClient;
}
public async Task<ExecutionResult> Execute(ExecuteContext<ISuccessRequest> context)
{
var iModel = context.Arguments;
var model = new SuccessRequest()
{
LogDate = iModel.LogDate,
MethodName = iModel.MethodName,
CheckInventoryCustomActionResult = iModel.CheckInventoryCustomActionResult
};
//CustomActionResult< CheckInventoryResponse > CheckInventoryResponse = new ();
var rabbitResult = await _requestClient.GetResponse<CustomActionResult<SuccessResponse>>(model);
return context.Completed();
}
}
I want to get this iModel.CheckInventoryCustomActionResult in RoutingSlipCompleted :
public async Task Consume(ConsumeContext<RoutingSlipCompleted> context)
{
var requestId =
context.Message.GetVariable<Guid?>(nameof(ConsumeContext.RequestId));
var checkInventoryResponseModel = context.Message.Variables["CheckInventoryResponse"];
var responseAddress =
context.Message.GetVariable<Uri>(nameof(ConsumeContext.ResponseAddress));
var request =
context.Message.GetVariable< ICheckInventoryRequest > ("Model");
throw new NotImplementedException();
}
Instead of putting the value into the activity arguments, add it as a variable:
return context.ReviseItinerary(x =>
{
x.AddActivity("CallSuccessActivity", uri, new
{
LogDate = DateTime.Now,
MethodName = "CheckInventoryActivity"
});
x.AddVariable("CheckInventoryCustomActionResult", checkInventoryCustomActionResult);
});
How to consume web post service in C#? I did tests with POSTMAN and I got a response data, but in .net my response is empty. It works great in PostMan. The problem is how to format the Body Content and send it.
string idop = "";
List<ProductJSON> listProductsJSON = new List<ProductJSON>();
List<List<string>> productJSON = new List<List<string>>();
List<string> products = new List<string>();
products.Add("4");
products.Add("5");
products.Add("30.2");
products.Add("1");
products.Add("0");
products.Add("4");
productJSON.Add(products);
using (var client = new HttpClient())
{
var res = client.PostAsync("http://xyz.cti.lat/sant2/webservices/edd.php",
new StringContent(JsonConvert.SerializeObject(
new {
a = "pCatlog",
cnal = "RED",
tpo = "2",
fpago = "DETO",
pgdo = "0",
rc = "13123",
local = "BACK",
localorg = "BACK",
raz = "PPPPPP",
dir_ruc = "name",
log = "CREAVIR",
not = "DETO2",
del = "0",
dir = "",
ubi = "",
refe = "",
prod = productJSON
}),
Encoding.UTF8, "application/json")));
try
{
res.Result.EnsureSuccessStatusCode();
var x = res;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Can you try this code inside of the try block?
if (res.IsCompleted)
{
var result = res.Result;
var response = result.Content.ReadAsStringAsync();
var data = response.Result;
}
The ideal would be to declare this as an async method and use the await operations to get the result as follows.
var res = await client.PostAsync(<url>, <string_content>);
var result = await res.Content.ReadAsStringAsync();
I have an API that automatically pulls new order details from my Woocommerce store into a Google Sheet. It seems to be working however, it has failed to pull the first 7 orders into my google sheet. It has all of the orders after the first 7. How do I get it to pull the first 7 orders into the sheet?
Here is my Google App Script:
function start_sync() {
// Followed instructions at https://github.com/mithunmanohar/woocommerce-orders-google-sheets-integration
var sheet_name = "OrderDetails"
update_order_5_min(sheet_name)
}
function update_order_5_min(sheet_name) {
var ck = "ck_ed82fae51e5bafce28dde95224db9c9c4bd36dba";
var cs = "cs_9a16fd7b641769a65412f336de3e7a928f7e153c";
var website = "https://www.funtrackdayz.com";
var now = new Date();
var website_t ="240";
var min = website_t * 60
now.setMinutes(now.getMinutes() - min);
var n = now.toISOString();
var surl = website + "/wc-api/v3/orders?consumer_key=" + ck + "&consumer_secret=" + cs + "&status=processing&filter[created_at_min]=" + n //"&after=2016-10-27T10:10:10Z"
// var surl = website + "/wc-api/v3/orders?consumer_key=" + ck + "&consumer_secret=" + cs + "&status=processing"
// &filter[created_at_min]=" + n //"&after=2016-10-27T10:10:10Z"
var url = surl
var options = {
"method": "GET",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"muteHttpExceptions": true,
};
var result = UrlFetchApp.fetch(url, options);
if (result.getResponseCode() == 200) {
var params = JSON.parse(result.getContentText());
}
var doc = SpreadsheetApp.getActiveSpreadsheet();
var temp = doc.getSheetByName(sheet_name);
var consumption = {}
//"orders"
arrayLength = params["orders"].length
for (var i = 0; i < arrayLength; i++) {
var container = [];
a = container.push(params["orders"][i]["billing_address"]["first_name"]);
a = container.push(params["orders"][i]["billing_address"]["last_name"]);
a = container.push(params["orders"][i]["billing_address"]["address_1"] + ", " + params["orders"][i]["billing_address"]["address_2"]);
a = container.push("");
a = container.push(params["orders"][i]["billing_address"]["city"]);
a = container.push(params["orders"][i]["billing_address"]["state"]);
a = container.push(params["orders"][i]["billing_address"]["postcode"]);
a = container.push(params["orders"][i]["billing_address"]["phone"]);
a = container.push(params["orders"][i]["billing_address"]["email"]);
a = container.push(params["orders"][i]["total"]); //price
a = container.push(params["orders"][i]["payment_details"]["method_id"]);
c = params["orders"][i]["line_items"].length;
items = "";
skus="";
for (var k = 0; k < c; k++) {
item = params["orders"][i]["line_items"][k]["name"];
qty = params["orders"][i]["line_items"][k]["quantity"];
sku = params["orders"][i]["line_items"][k]["sku"];
meta = ""
try {
meta = params["orders"][i]["line_items"][k]["meta"][0]["value"];
meta = " - " + meta
} catch (err) {
meta = ""
}
item_f = qty + " x " + item + meta
items = items + item_f + ",\n"
skus = skus + ",\n"
}
a = container.push(items)
a = container.push(sku)
// a = container.push(params["orders"][i]["total_line_items_quantity"]); // Quantity
a = container.push(params["orders"][i]["order_number"]); //
a = container.push(params["orders"][i]["note"])
a = container.push(params["orders"][i]["created_at"]);
var doc = SpreadsheetApp.getActiveSpreadsheet();
var temp = doc.getSheetByName(sheet_name);
temp.appendRow(container);
removeDuplicates(sheet_name)
}
}
function removeDuplicates(sheet_name) {
var doc = SpreadsheetApp.getActiveSpreadsheet();
var sheet = doc.getSheetByName(sheet_name);
var data = sheet.getDataRange().getValues();
var newData = new Array();
for (i in data) {
var row = data[i];
var duplicate = false;
for (j in newData) {
if (row.join() == newData[j].join()) {
duplicate = true;
}
}
if (!duplicate) {
newData.push(row);
}
}
sheet.clearContents();
sheet.getRange(1, 1, newData.length, newData[0].length).setValues(newData);
}
Hi there i would like to let customers type a category name and get some search results. Currently when you type a category name it says no results.
public ActionResult AdvanceSearch(SearchModel model, CatalogPagingFilteringModel command)
{
//'Continue shopping' URL
_genericAttributeService.SaveAttribute(_workContext.CurrentCustomer,
SystemCustomerAttributeNames.LastContinueShoppingPage,
_webHelper.GetThisPageUrl(false),
_storeContext.CurrentStore.Id);
if (model == null)
model = new SearchModel();
var searchTerms = model.q;
if (searchTerms == null)
searchTerms = "";
searchTerms = searchTerms.Trim();
//sorting
PrepareSortingOptions(model.PagingFilteringContext, command);
//view mode
PrepareViewModes(model.PagingFilteringContext, command);
//page size
PreparePageSizeOptions(model.PagingFilteringContext, command,
_catalogSettings.SearchPageAllowCustomersToSelectPageSize,
_catalogSettings.SearchPagePageSizeOptions,
_catalogSettings.SearchPageProductsPerPage);
string cacheKey = string.Format(ModelCacheEventConsumer.SEARCH_CATEGORIES_MODEL_KEY,
_workContext.WorkingLanguage.Id,
string.Join(",", _workContext.CurrentCustomer.GetCustomerRoleIds()),
_storeContext.CurrentStore.Id);
var categories = _cacheManager.Get(cacheKey, () =>
{
var categoriesModel = new List<SearchModel.CategoryModel>();
//all categories
var allCategories = _categoryService.GetAllCategories(storeId: _storeContext.CurrentStore.Id);
foreach (var c in allCategories)
{
//generate full category name (breadcrumb)
string categoryBreadcrumb = "";
var breadcrumb = c.GetCategoryBreadCrumb(allCategories, _aclService, _storeMappingService);
for (int i = 0; i <= breadcrumb.Count - 1; i++)
{
categoryBreadcrumb += breadcrumb[i].GetLocalized(x => x.Name);
if (i != breadcrumb.Count - 1)
categoryBreadcrumb += " >> ";
}
categoriesModel.Add(new SearchModel.CategoryModel
{
Id = c.Id,
Breadcrumb = categoryBreadcrumb
});
}
return categoriesModel;
});
if (categories.Any())
{
//first empty entry
model.AvailableCategories.Add(new SelectListItem
{
Value = "0",
Text = _localizationService.GetResource("Common.All")
});
//all other categories
foreach (var c in categories)
{
model.AvailableCategories.Add(new SelectListItem
{
Value = c.Id.ToString(),
Text = c.Breadcrumb,
Selected = model.cid == c.Id
});
}
}
IPagedList<Product> products = new PagedList<Product>(new List<Product>(), 0, 1);
// only search if query string search keyword is set (used to avoid searching or displaying search term min length error message on /search page load)
if (Request.Params["q"] != null)
{
if (searchTerms.Length < _catalogSettings.ProductSearchTermMinimumLength)
{
model.Warning = string.Format(_localizationService.GetResource("Search.SearchTermMinimumLengthIsNCharacters"), _catalogSettings.ProductSearchTermMinimumLength);
}
else
{
var categoryIds = new List<int>();
int manufacturerId = 0;
decimal? minPriceConverted = null;
decimal? maxPriceConverted = null;
bool searchInDescriptions = false;
int vendorId = 0;
if (model.adv)
{
//advanced search
var categoryId = model.cid;
if (categoryId > 0)
{
categoryIds.Add(categoryId);
if (model.isc)
{
//include subcategories
categoryIds.AddRange(GetChildCategoryIds(categoryId));
}
}
manufacturerId = model.mid;
//min price
if (!string.IsNullOrEmpty(model.pf))
{
decimal minPrice;
if (decimal.TryParse(model.pf, out minPrice))
minPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(minPrice, _workContext.WorkingCurrency);
}
//max price
if (!string.IsNullOrEmpty(model.pt))
{
decimal maxPrice;
if (decimal.TryParse(model.pt, out maxPrice))
maxPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(maxPrice, _workContext.WorkingCurrency);
}
if (model.asv)
vendorId = model.vid;
searchInDescriptions = model.sid;
}
//var searchInProductTags = false;
var searchInProductTags = searchInDescriptions;
//products
products = _productService.SearchProducts(
categoryIds: categoryIds,
manufacturerId: manufacturerId,
storeId: _storeContext.CurrentStore.Id,
visibleIndividuallyOnly: true,
priceMin: minPriceConverted,
priceMax: maxPriceConverted,
keywords: searchTerms,
//searchDescriptions: searchInDescriptions,
searchProductTags: searchInProductTags,
searchSku: true,
languageId: _workContext.WorkingLanguage.Id,
orderBy: (ProductSortingEnum)command.OrderBy,
pageIndex: command.PageNumber - 1,
pageSize: command.PageSize,
vendorId: vendorId);
model.Products = PrepareProductOverviewModels(products).ToList();
model.NoResults = !model.Products.Any();
//search term statistics
if (!String.IsNullOrEmpty(searchTerms))
{
var searchTerm = _searchTermService.GetSearchTermByKeyword(searchTerms, _storeContext.CurrentStore.Id);
if (searchTerm != null)
{
searchTerm.Count++;
_searchTermService.UpdateSearchTerm(searchTerm);
}
else
{
searchTerm = new SearchTerm
{
Keyword = searchTerms,
StoreId = _storeContext.CurrentStore.Id,
Count = 1
};
_searchTermService.InsertSearchTerm(searchTerm);
}
}
//event
_eventPublisher.Publish(new ProductSearchEvent
{
SearchTerm = searchTerms,
SearchInDescriptions = searchInDescriptions,
CategoryIds = categoryIds,
ManufacturerId = manufacturerId,
WorkingLanguageId = _workContext.WorkingLanguage.Id,
VendorId = vendorId
});
}
}
model.PagingFilteringContext.LoadPagedList(products);
return View(model);
}
A public action method 'AdvanceSearch' was not found on controller 'Nop.Web.Controllers.CatalogController'.
I am trying this code for creating new campaign using MailChimp API in ASP.NET
public string CreateCampaignAndSend(string apiKey, string listID)
{
Int32 TemplateID = 100;
string campaignID = string.Empty;
MailChimpManager mc = new MailChimpManager("sampleAPIKeyXXXXXXXXXXXXXX-us12");
// compaign Create Options
campaignCreateOptions campaignCreateOpt = new campaignCreateOptions();
campaignCreateOpt.list_id = listID;
campaignCreateOpt.subject = "subject";
campaignCreateOpt.from_email = "wisdomthnkrs#gmail.com";
campaignCreateOpt.from_name = "abc";
campaignCreateOpt.template_id = TemplateID;
campaignCreateOpt.authenticate = true;
campaignCreateOpt.auto_footer = false;
campaignCreateOpt.tracking.opens = true;
campaignCreateOpt.tracking.html_clicks = true;
campaignCreateOpt.tracking.text_clicks = true;
// Content
Dictionary<string, string> content = new Dictionary<string, string>();
content.Add("html_ArticleTitle1", "ArticleTitle1");
content.Add("html_ArticleTitle2", "ArticleTitle2");
content.Add("html_ArticleTitle3", "ArticleTitle3");
content.Add("html_Article1", "Article1");
content.Add("html_Article2", "Article2");
//Conditions
List<campaignSegmentCondition> csCondition = new List<campaignSegmentCondition>();
campaignSegmentCondition csC = new campaignSegmentCondition();
csC.field = "interests-" + 123; // where 123 is the Grouping Id from listInterestGroupings()
csC.op = "all";
csC.value = "";
csCondition.Add(csC);
// Options
campaignSegmentOptions csOptions = new campaignSegmentOptions();
csOptions.match = "all";
// Type Options
Dictionary<string, string> typeOptions = new Dictionary<string, string>();
typeOptions.Add("offset-units", "days");
typeOptions.Add("offset-time", "0");
typeOptions.Add("offset-dir", "after");
// Create Campaigns
campaignCreateParms campaignCreateParms = new campaignCreateParms(mc.APIKey, EnumValues.campaign_type.regular, campaignCreateOpt, content, csOptions, typeOptions);
campaignCreateInput campCreateInput = new campaignCreateInput(campaignCreateParms);
campaignCreate campaignCreate = new campaignCreate(campCreateInput);
//xyz();
//string abc = xxxxxxxxxxxxxxxxx;
campaignCreateOutput ccOutput = campaignCreate.Execute(campCreateInput);
List<Api_Error> error = ccOutput.api_ErrorMessages; // Catching API Errors
string s = "null";
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);
s = s + ae.code;
s = s + ae.error;
}
}
return s;
}
but it shows an error while I am giving the right key.
here is the error,
null104Invalid MailChimp "Invalid MailChimp API key:
6ea29f158xxxxxxxxxxxx"