Creating Orders from Code

For general questions and discussions specific to the AbleCommerce 7.0 Asp.Net product.
User avatar
heinscott
Captain (CAPT)
Captain (CAPT)
Posts: 375
Joined: Thu May 01, 2008 12:37 pm

Creating Orders from Code

Post by heinscott » Mon Jan 19, 2009 2:19 pm

Hello.
I'm in the process of creating an import for Ebay orders in Able. I have gotten to the point of being able to import all order information from ebay, and am now wondering what is the best way to create an order from code. Should I create an anonymous user, and populate a basket? Or could I just create a new Order object, and add orderitems, etc??
I guess I'm just looking for the easiest way to accomplish this. I could try 1,000 things over the next day, I suppose, but I'm sure that someone here has already done this, (Joe, maybe??) and could give me some helpful advice.
Thanks for any help you can give me!

Scott

User avatar
AbleMods
Master Yoda
Master Yoda
Posts: 5170
Joined: Wed Sep 26, 2007 5:47 am
Location: Fort Myers, Florida USA

Re: Creating Orders from Code

Post by AbleMods » Tue Jan 20, 2009 6:55 am

Never actually tried it yet through code. I've imported some through Dataport.

From what I have tried, importing directly by creating a new order instance and issuing .Save() doesn't work like I expected it to work. I think it was because I didn't populate enough mandatory fields but I'm not entirely sure.

The only other route I could see (at the time) was sniffing through CreditCardPaymentForm.ascx and following the Able technique for initiating checkout via a basket instance. In other words, build all the sub-objects first like addresses, payment record, user record etc. But setting that up in advance seemed equally difficult so I moved on.
Joe Payne
AbleCommerce Custom Programming and Modules http://www.AbleMods.com/
AbleCommerce Hosting http://www.AbleModsHosting.com/
Precise Fishing and Hunting Time Tables http://www.Solunar.com

User avatar
heinscott
Captain (CAPT)
Captain (CAPT)
Posts: 375
Joined: Thu May 01, 2008 12:37 pm

Re: Creating Orders from Code

Post by heinscott » Tue Jan 20, 2009 8:10 am

Right on, thanks Joe.
Yeah, the only way I can see to do it now, is to somehow imitate the process gone through on the admin "add an order" side (/admin/orders/PlaceOrder1(&2).aspx). I've already done adding a user, address, basket, etc though code, but, not a manual payment. Since it's ebay, of course everything has already been processed payment wise. I only need to create a manual payment record.
I guess I too, though, am not sure what is all mandatory in order to successfully add the order.
Is there any kind of documentation that would point to all the necessary events in order creation perchance??

Thanks,

Scott

User avatar
AbleMods
Master Yoda
Master Yoda
Posts: 5170
Joined: Wed Sep 26, 2007 5:47 am
Location: Fort Myers, Florida USA

Re: Creating Orders from Code

Post by AbleMods » Tue Jan 20, 2009 9:18 am

None that I've seen. Maybe drop a PM to Mazhar and see if he can put something in the Wiki - would be awfully nice to have around for future reference.

Like you, I've found all the sub-components of an order are easily created and saved. It's just the order itself that seems to be complex. Almost thought about digging through the PayPal checkout control just because it's the only payment method control that fully saves the order without some sort of "outside gateway" communication required. Might be worth a look-see......
Joe Payne
AbleCommerce Custom Programming and Modules http://www.AbleMods.com/
AbleCommerce Hosting http://www.AbleModsHosting.com/
Precise Fishing and Hunting Time Tables http://www.Solunar.com

User avatar
heinscott
Captain (CAPT)
Captain (CAPT)
Posts: 375
Joined: Thu May 01, 2008 12:37 pm

Re: Creating Orders from Code

Post by heinscott » Tue Jan 20, 2009 1:20 pm

Okay...

I've gotten nearly everthing to work (finally), including a manual PayPal payment, shipping/billing address, order creation, orderitems added...
The only thing I have not been able to figure out is how to add a shipment cost to the order. This should be easy, considering that it is going to be a fixed cost that will come in with the ebay order.
Do I add it as an orderitem with type of shipping? Not sure here...
Any help would be appreciated.

Scott

User avatar
heinscott
Captain (CAPT)
Captain (CAPT)
Posts: 375
Joined: Thu May 01, 2008 12:37 pm

Re: Creating Orders from Code

Post by heinscott » Tue Jan 20, 2009 3:07 pm

...nevermind.
I ended up figuring it out.
Thanks anyway!

Scott

User avatar
AbleMods
Master Yoda
Master Yoda
Posts: 5170
Joined: Wed Sep 26, 2007 5:47 am
Location: Fort Myers, Florida USA

Re: Creating Orders from Code

Post by AbleMods » Tue Jan 20, 2009 6:58 pm

Well done, I knew you wore that labcoat for a reason :P
Joe Payne
AbleCommerce Custom Programming and Modules http://www.AbleMods.com/
AbleCommerce Hosting http://www.AbleModsHosting.com/
Precise Fishing and Hunting Time Tables http://www.Solunar.com

Niraj8428
Ensign (ENS)
Ensign (ENS)
Posts: 19
Joined: Fri Feb 20, 2009 9:13 am

Re: Creating Orders from Code

Post by Niraj8428 » Tue Mar 03, 2009 12:26 am

hey Captain we are in almost same condition want to save Order information, actual we have order information in form of CSV file from other website, can you please share code which you used to save Order info? what you saved first User? then Basket? then Payment ? what all we need to save and in which order? any help will be highly appreciated.

Thanks,
Niraj

User avatar
heinscott
Captain (CAPT)
Captain (CAPT)
Posts: 375
Joined: Thu May 01, 2008 12:37 pm

Re: Creating Orders from Code

Post by heinscott » Tue Mar 03, 2009 1:17 pm

We created orders for ebay orders that were processed on the ebay side. As such, we didn't need to actually submit payment, or calculate shipping. Basically, we were importing with a manual, offline payment method (ebay), and setting a flat fee of $9.99 for shipping. I'm sure you could customize however you need, however. Here is the stripped down version of code we used for the import:

Code: Select all

public void CreateOrder(object sender, CommandEventArgs e)
    {
	//initialize user

        User _User = InitializeUser();
        Basket basket = _User.Basket;
        
	//setup new address

        Address _Address = new Address();
        _Address.Address1 = ?????????;
        _Address.Address2 = ?????????;
        _Address.City = ?????????;
        _Address.Province = ?????????;
        _Address.PostalCode = ?????????;
        _Address.LastName = ?????????;
        _Address.FirstName = ?????????;
        _Address.Email = ?????????;
        _Address.Phone = ?????????;
        _Address.CountryCode = "US";
        _Address.UserId = _User.UserId;
        _Address.Save();
        
	//assign address to user

        _User.PrimaryAddressId = _Address.AddressId;
        _User.Save();
        
        
	//run for all products you wish to add to cart (p in product in question)

        BasketItem bi = BasketItemDataSource.CreateForProduct(p.ProductId, (short)qty);
        bi.Price = price;
        basket.Items.Add(bi);
        
	basket.Save();
        basket.Recalculate();

	//add a shipment to the order

        basket.Shipments.Add(new BasketShipment());
        basket.Shipments[0].AddressId = _User.PrimaryAddressId;
        basket.Shipments[0].ShipMethodId = ?????????; //choose the id of shipping method you wish to use
        basket.Recalculate();
        
	//add a payment (I only tried this with a manual offline payment)
	Payment payment = new Payment();
        payment.PaymentMethodId = 9;
        payment.Amount = basket.Items.TotalPrice();

	//initiate a checkout event

        CheckoutRequest checkoutRequest = new CheckoutRequest(null);
        CheckoutResponse checkoutResponse = basket.Checkout(checkoutRequest);
        
	//if successful
	
	if (checkoutResponse.Success)
        {
            Order _Order = OrderDataSource.Load(checkoutResponse.OrderId);
            OrderItem oi = new OrderItem();
            oi.OrderItemType = OrderItemType.Shipping;
            oi.Price = ?????????;
            oi.OrderId = _Order.OrderId;
            oi.OrderShipmentId = _Order.Shipments[0].OrderShipmentId;
            oi.Name = "Flat Rate Shipping";
            oi.Quantity = 1;
            _Order.Items.Add(oi);
            _Order.Save();

            payment.OrderId = _Order.OrderId;
            payment.ReferenceNumber = ?????????;
            payment.CurrencyCode = "USD";
            payment.PaymentStatus = PaymentStatus.Completed;
            payment.Amount = _Order.Items.TotalPrice();
            payment.PaymentStatusReason = ?????????;
            _Order.Payments.Add(payment);
            _Order.Payments.Save();

            _Order.Save();
        }
    }
Hope this helps,

Scott

Niraj8428
Ensign (ENS)
Ensign (ENS)
Posts: 19
Joined: Fri Feb 20, 2009 9:13 am

Re: Creating Orders from Code

Post by Niraj8428 » Wed Mar 04, 2009 9:41 am

Thanks for this code, however we are struggling since last 3 days to save Payment information for our orders from CSV file. we have saved Users, Orders, Baskets, Basket Items etc. but are not able to save Payment information getting "Object reference not ... " error. don'g know why rest all are saved but facing problem with payment info.

here is the code we are using for saving Payment Info:
Payment payment = new Payment();

payment.PaymentMethodId = 1;
payment.Amount = basket.Items.TotalPrice();
payment.PaymentStatusId = 1;
payment.SubscriptionId = 18;
payment.OrderId = order.OrderId;
payment.CurrencyCode = "USD";
payment.Amount = order.Items.TotalPrice();
payment.PaymentStatusReason = "test"
payment.ReCrypt = true;
payment.PaymentDate = DateTime.Now;
//payment.CompletedDate = System.DateTime.Now;
payment.PaymentStatus = PaymentStatus.Authorized;
//payment.Save();
if (order.Payments != null)
order.Payments.Add(payment);
order.Payments.Save();
order.Save();

Moreover one more query, we are saving information from CSV still we need to create Basket and Basket Items? as I believe those are for temporary purpose right? we need to save Basket Item and Order Item both? confused.

and our Basket and Basket items are getting saved successfully but "Basket.Recalculate()" and "Basket.Checkout()" methods are not working, getting "object reference not.." error, any idea?

Thanks,
Niraj

User avatar
heinscott
Captain (CAPT)
Captain (CAPT)
Posts: 375
Joined: Thu May 01, 2008 12:37 pm

Re: Creating Orders from Code

Post by heinscott » Wed Mar 04, 2009 9:47 am

It would be helpful if you gave the whole error message for "Object Reference..."
As for the creating order items... Only for the Shipping Cost. All the others are created automatically from basket items.

Scott

Niraj8428
Ensign (ENS)
Ensign (ENS)
Posts: 19
Joined: Fri Feb 20, 2009 9:13 am

Re: Creating Orders from Code

Post by Niraj8428 » Wed Mar 04, 2009 9:58 am

"Object reference not set to an instance of an object"

Niraj8428
Ensign (ENS)
Ensign (ENS)
Posts: 19
Joined: Fri Feb 20, 2009 9:13 am

Re: Creating Orders from Code

Post by Niraj8428 » Wed Mar 04, 2009 10:03 am

"..As for the creating order items... Only for the Shipping Cost. All the others are created automatically from basket items.."

Does it mean we will only have to create basket and basket items only ? and order items will be created automatically? if so then how? for that we will have to call any method manually? has it anything to do with Basket.Recalculate() as we are facing horrible problem while saving Payment info. don't know why rest all info are getting saved but getting "object reference not set to an instance of an object error.." while saving payment object (save method) .

Niraj.

User avatar
mazhar
Master Yoda
Master Yoda
Posts: 5084
Joined: Wed Jul 09, 2008 8:21 am
Contact:

Re: Creating Orders from Code

Post by mazhar » Wed Mar 04, 2009 10:07 am

Niraj8428 wrote:"..As for the creating order items... Only for the Shipping Cost. All the others are created automatically from basket items.."

Does it mean we will only have to create basket and basket items only ? and order items will be created automatically? if so then how? for that we will have to call any method manually? has it anything to do with Basket.Recalculate() as we are facing horrible problem while saving Payment info. don't know why rest all info are getting saved but getting "object reference not set to an instance of an object error.." while saving payment object (save method) .

Niraj.
What exactly you want to do? Are you trying to import orders or trying to implement a custom cart using Able framework?

Niraj8428
Ensign (ENS)
Ensign (ENS)
Posts: 19
Joined: Fri Feb 20, 2009 9:13 am

Re: Creating Orders from Code

Post by Niraj8428 » Wed Mar 04, 2009 10:34 am

see we are fetching order information from CSV file and trying to save in our shopping cart web site database which we have purchased from AC and now using AC dlls, commercebuilder.dll now able to save other information in db but not able to save Payment information, hope it makes sense actually this is first time we are working with AC dlls (may be for you AC framework) for our client and have not much knowledge of concept of AC and how it works.

User avatar
mazhar
Master Yoda
Master Yoda
Posts: 5084
Joined: Wed Jul 09, 2008 8:21 am
Contact:

Re: Creating Orders from Code

Post by mazhar » Wed Mar 04, 2009 11:07 am

Then this is import operations and you need not to use Basket.Checkout and Basket.Recalculate etc.

As I have already posted a sample for CSV processing and I think you tried that as well. So all you need is to iterate over CSV and process the data. For example obviously when importing the orders CSV you don't have user of that order in Able database. So first you need is to create a new user using the user name. Then you can save its First Name and Last Name in the child object of user. I mean using User.PrimaryAddress. Then you need to create a new object of order object. Their is one important thing. you need to set the OrderId manually by using the following statement

Code: Select all


Order order = new Order();
order.OrderId = StoreDataSource.GetNextOrderNumber(true);
and finally assign it the UserId of newly created user and save the order.

jake.pretot
Lieutenant, Jr. Grade (LT JG)
Lieutenant, Jr. Grade (LT JG)
Posts: 22
Joined: Fri Feb 20, 2009 1:31 am

Re: Creating Orders from Code

Post by jake.pretot » Thu Mar 05, 2009 8:47 am

Hi Mazhar-

I'm working on the project with Niraj. One thing that I want to make clear is that the orders we are importing are orders, but the payment has not been processed yet, only authorized by the call center. We have gotten to the point where the order record(s) was created in the ac_orders table, but there is nothing in the order items table. The basket items are still in the basket items table.

What we seem to be missing is how to process payment and create the order/order items, etc.. Essentially what we are doing is trying to emulate the same steps that a user goes through if they actually went to the shopping site:
create user if doesn't exist
create address if doesn't exist
create basket
create basket items
then, process the order request (payment/submit order)

In my mind, if everything is in the basket, there should be some method that we can call to provide payment info (credit card info) and the system should do the rest (move items out of basket into the orders table, order items table, subscriptions, etc.).

I don't want to override the system, but want to use the natural order/flow that already exists in AC. I don't want to shortcut the process. Does that make sense? We can send you the code offline via email if you would like to review what we have so far.

Thanks.

-Jake

User avatar
mazhar
Master Yoda
Master Yoda
Posts: 5084
Joined: Wed Jul 09, 2008 8:21 am
Contact:

Re: Creating Orders from Code

Post by mazhar » Thu Mar 05, 2009 9:12 am

Well first regarding payments, if you want to process payments in Able after importing. Currently you can capture the authorize payments from AbleCommerce admin manually.

So if you importing some orders with authorized payment then you need to consider the payment transactions as well. For example for authorized payments you need to create a transaction for the payment having authorize information. I mean CommerceBuilder.Payments.Transaction object.

Secondly if you want to import the order items then you need not to create the Basket and Basket Items. Just import that information in Order Items.

jake.pretot
Lieutenant, Jr. Grade (LT JG)
Lieutenant, Jr. Grade (LT JG)
Posts: 22
Joined: Fri Feb 20, 2009 1:31 am

Re: Creating Orders from Code

Post by jake.pretot » Thu Mar 05, 2009 11:13 am

Mazhar-

What I'm afraid of is that if we insert directly into the orders and order items tables, that we will overlook some other behind the scenes processing that inserts into other tables. For example, if we have a subscription product, making sure that information gets inserted into the right places. If we have built up the basket and basket items, is there no way to call a method for processing the order? I would think all that we would have to do is execute processing for Pay With Card click and the system would take care of everything else. See image.

User avatar
mazhar
Master Yoda
Master Yoda
Posts: 5084
Joined: Wed Jul 09, 2008 8:21 am
Contact:

Re: Creating Orders from Code

Post by mazhar » Thu Mar 05, 2009 11:23 am

In this case check the admin area of order manager where admin can place orders him self. You can use that code as a reference to create and checkout the baskets through your code.

jake.pretot
Lieutenant, Jr. Grade (LT JG)
Lieutenant, Jr. Grade (LT JG)
Posts: 22
Joined: Fri Feb 20, 2009 1:31 am

Re: Creating Orders from Code

Post by jake.pretot » Thu Mar 05, 2009 11:32 am

Are you talking about the ucProcessPayment.ascx? I found this code there...

protected void SaveButton_Click(object sender, EventArgs e)
{
if (Page.IsValid && CustomValidation())
{
PaymentMethod method = GetSelectedMethod();
if (method != null)
{
Payment payment = new Payment();
payment.OrderId = _OrderId;
payment.PaymentMethodId = method.PaymentMethodId;
AccountDataDictionary paymentInstrumentBuilder = new AccountDataDictionary();
switch (method.PaymentInstrument)
{
case PaymentInstrument.AmericanExpress:
case PaymentInstrument.Discover:
case PaymentInstrument.JCB:
case PaymentInstrument.MasterCard:
case PaymentInstrument.Visa:
case PaymentInstrument.DinersClub:
case PaymentInstrument.Maestro:
case PaymentInstrument.SwitchSolo:
case PaymentInstrument.VisaDebit:
paymentInstrumentBuilder["AccountNumber"] = CardNumber.Text;
paymentInstrumentBuilder["ExpirationMonth"] = ExpirationMonth.SelectedItem.Value;
paymentInstrumentBuilder["ExpirationYear"] = ExpirationYear.SelectedItem.Value;
paymentInstrumentBuilder["SecurityCode"] = SecurityCode.Text;
if (IssueNumber.Text.Length > 0) paymentInstrumentBuilder["IssueNumber"] = IssueNumber.Text;
if ((StartDateMonth.SelectedIndex > 0) && (StartDateYear.SelectedIndex > 0))
{
paymentInstrumentBuilder["StartDateMonth"] = StartDateMonth.SelectedItem.Value;
paymentInstrumentBuilder["StartDateYear"] = StartDateYear.SelectedItem.Value;
}
payment.ReferenceNumber = StringHelper.MakeReferenceNumber(CardNumber.Text);
payment.Amount = AlwaysConvert.ToDecimal(CreditCardPaymentAmount.Text);
break;
case PaymentInstrument.Check:
paymentInstrumentBuilder["RoutingNumber"] = RoutingNumber.Text;
paymentInstrumentBuilder["BankName"] = BankName.Text;
paymentInstrumentBuilder["AccountHolder"] = AccountHolder.Text;
paymentInstrumentBuilder["AccountNumber"] = BankAccountNumber.Text;
payment.ReferenceNumber = StringHelper.MakeReferenceNumber(BankAccountNumber.Text);
payment.Amount = AlwaysConvert.ToDecimal(CheckPaymentAmount.Text);
break;
}
if (payment.Amount > 0)
{
//PRESERVE PAYMENT INSTRUMENT DATA
_Order.Payments.Add(payment);
_Order.Payments.Save();
//ADD IN PAYMENT INSTRUMENT DATA FOR PROCESSING
payment.AccountData = paymentInstrumentBuilder.ToString();
payment.Authorize(false);
//REDIRECT TO PAYMENT PAGE
Response.Redirect("Default.aspx?OrderId=" + _OrderId.ToString());
}
}
}
}
</script>

User avatar
mazhar
Master Yoda
Master Yoda
Posts: 5084
Joined: Wed Jul 09, 2008 8:21 am
Contact:

Re: Creating Orders from Code

Post by mazhar » Thu Mar 05, 2009 11:35 am

Yes. First place an order manually from merchant side. It will help you understand how admin placed the order and then check the code that is used for the functionality.

jake.pretot
Lieutenant, Jr. Grade (LT JG)
Lieutenant, Jr. Grade (LT JG)
Posts: 22
Joined: Fri Feb 20, 2009 1:31 am

Re: Creating Orders from Code

Post by jake.pretot » Thu Mar 05, 2009 12:10 pm

Mazhar-

That is exactly what we were looking for! Thanks for pointing us in the right direction!

-Jake

User avatar
mazhar
Master Yoda
Master Yoda
Posts: 5084
Joined: Wed Jul 09, 2008 8:21 am
Contact:

Re: Creating Orders from Code

Post by mazhar » Fri Mar 06, 2009 5:25 am

sounds good :)

Niraj8428
Ensign (ENS)
Ensign (ENS)
Posts: 19
Joined: Fri Feb 20, 2009 9:13 am

Re: Creating Orders from Code

Post by Niraj8428 » Fri Mar 06, 2009 6:58 am

Thanks for your Help Mazhar but after looking in to those pages I found we have used almost same code and that is why we are able to save User, Basket, Basket Items, Order etc. but don't know why we are getting "Object reference not set to an instance of an object." error when we try to save Payment information. it seems still there is something which we are missing, does it has anything to do with database tables? because our database tables are blank, we are using blank fresh database except products table. does it expect any master table values or anything like that?

I looked in to pages you suggested ("PlaceOrder1.aspx.cs" and "PlaceOrder2.aspx.cs") and found that for payment it is used:
"
_Basket.Recalculate();
Payment payment = new Payment();
payment.Amount = _Basket.Items.TotalPrice();
CheckoutRequest checkoutRequest = new CheckoutRequest(null);
CheckoutResponse checkoutResponse = _Basket.Checkout(checkoutRequest);
if (checkoutResponse.Success)
{
Session.Remove("PlaceOrderUserId");
Response.Redirect("ViewOrder.aspx?OrderId=" + checkoutResponse.OrderId);
}
"
but Recalculate(); gives us error and "CheckoutRequest checkoutRequest = new CheckoutRequest(null);
CheckoutResponse checkoutResponse = _Basket.Checkout(checkoutRequest);" is also giving us error.

any idea if we are missing anything?

Niraj.

Post Reply