Skip to main content

Ezpservices Integration In Ruby on Rails(Cafe Press)

Ezprints  Integration In rails

1)Posting Order to Ezprints and get the shipping values
require 'net/https'
require 'rexml/document'
def shipping_options_ezp_services
      @order = Order.where(:id => 5).first
      @total_orders = Order.all
      xml = "<?xml version='1.0' encoding='UTF-8'?>
      <orders partnerid='45678' version='1'>
      <ordersession>
      <order>
      <orderid>#{@order.id}</orderid>
      <shippingaddress>
      <firstname>#{@order.first_name}</firstname>
      <address1>#{@order.address1}</address1>
      <city>#{@order.city}</city>
      <state>#{@order.state}</state>
      <zip>#{@order.zip}</zip>
      <countrycode>#{@order.country}</countrycode>
      <phone>#{@order.phone_no}</phone>
      </shippingaddress>"
     @total_orders.each do |t|
        xml << "<orderline productid='#{t.product_id}' imageid='#{t.image_id}'>
                 <description>#{t.description}</description>
                  <quantity>#{t.quantity}</quantity>
                </orderline>
             </order>
          </ordersession>
       </orders>"
      end
  
    begin
        url = URI.parse('http://services.ezprints.com/ShippingCalculator/CalculateShipping.axd')
        request = Net::HTTP::Post.new(url.path)
        request.content_type = 'text/xml'
        request.body = xml
        response = Net::HTTP.start(url.host, url.port) {|http| http.request(request)}
        # Start of After Posting the order to ezpshipping ShippingCalculator output will be getting like these
        # <?xml version="1.0"?>
        # <shippingOptions>
        #   <order orderid="1234">
        #      <option type="FC" price="9.95" shippingMethod="USFC" description="Economy to United States"/>
        #      <option type="PM" price="9.95" shippingMethod="USPM" description="Express to United States"/>
        #      <option type="SD" price="15.95" shippingMethod="USSD"
        #         description="Second Business Day to United States"/>
        #      <option type="ON" price="23.95" shippingMethod="OVNT"
        #         description="Next Business Day to United States"/>
        #   </order>
        # </shippingOptions>
        #End of response after posting order to ezpshipping calculator
        @options = Array.new
        document = REXML::Document.new(response.body)
        doc = REXML::XPath.each(document, "*//option type") { |element|
        type = element.attributes["type"]
        price =  element.attributes["price"]
        shippingmethod =  element.attributes["shippingMethod"]
        description =  element.attributes["description"]
         @options << {
          :id => type,:service => shippingmethod + "(" + description +")",:price => price }
          }
        p @options.inspect
      rescue Exception
      end
  end

2)Send Order To Ezprints and placing order


##Post orders to ezpprints
def send_order_ezp
  begin
   xml = "<?xml version='1.0' encoding='UTF-8'?>
                 <orders partnerid = 'xxxxx' version = '1'>
                  <images>
                      <uri id='3'title='Logo'>http://www.ezprints.com/images/logo.jpg</uri>
                      <uri id='5' title='My Photo'>http://www.ezprints.com/images/0/0_5.jpg</uri>
                      <uri id='6' title='A  Photo'>http://www.ezprints.com/images/0/123.jpg</uri>
                  </images>
                  <ordersession>
                      <sessionid>1234</sessionid>
                      <vendor logoimageid = '3'>
                          <name>MyCompanyName</name>
                          <address1>123 Any St.</address1>
                          <address2>Apartment 3</address2>
                          <city>Anytown</city>
                          <state>PA</state>
                          <zip>12345</zip>
                          <countrycode>USA</countrycode>
                          <phone>303-555-1212</phone>
                          <email>jane@host.com</email>
                          <url>www.ezprints.com</url>
                      </vendor>
                      <customer>
                          <customerid>1234</customerid>
                          <title>Ms</title>
                          <firstname>Jane</firstname>
                          <lastname>Doe</lastname>
                          <address1>123 Any St.</address1>
                          <address2>Apartment 3</address2>
                          <city>Anytown</city>
                          <state>PA</state>
                          <zip>12345</zip>
                          <countrycode>USA</countrycode>
                          <phone>303-555-1212</phone>
                          <email>jane@host.com</email>
                      </customer>
                      <order>
                          <orderid>1234</orderid>
                          <shippingaddress>
                              <title>Ms</title>
                              <firstname>Jane</firstname>
                              <lastname>Doe</lastname>
                              <address1>456 Another St.</address1>
                              <address2>Unit D</address2>
                              <city>Anothertown</city>
                              <state>ON</state>
                              <zip>B6B-4G3</zip>
                              <countrycode>USA</countrycode>
                              <phone>301-555-1212</phone>
                              <email>jo@hots.com</email>
                          </shippingaddress>
                          <shippingmethod>FC</shippingmethod>
                          <orderline productid = '10050' imageid = '5'>
                              <description>5x7 Glossy Print</description>
                              <productprice>1.95</productprice>
                              <quantity>1</quantity>
                              <position>fit</position>
                          </orderline>
                          <producttotal>1.95</producttotal>
                          <shippingprice>5.95</shippingprice>
                          <tax>0.00</tax>
                          <ordertotal>1.95</ordertotal>
                      </order>
                      <producttotal>1.95</producttotal>
                      <shippingtotal>5.95</shippingtotal>
                      <taxtotal>0.00</taxtotal>
                      <total>7.90</total>
                  </ordersession>
              </orders>"
              url = URI.parse("http://order.ezprints.com")
              request = Net::HTTP::Post.new("/PostXmlOrder.axd?PartnerNumber=xxxx&PartnerReference=#{@order}")
              request.content_type = 'text/xml'
              request.body = xml
              logger.info  xml.inspect
              response = Net::HTTP.start(url.host, url.port) {|http| http.request(request)}
              response_data = CobraVsMongoose.xml_to_hash(response.body)
               #After sending ezpprints to order details it will place ezpprints site and response we will recevive as the below format
                #  <orderfailed AffiliateID="499">
                #    <ordernumber>718362</ordernumber>
                #    <referencenumber>00123-200708031121-62724</referencenumber>
                #    <message>4002 Error: Type mismatch</message>
                # </orderfailed>
                # <orderfailed AffiliateID="499">
                #    <ordernumber />
                #    <referencenumber>00244-200708031403-63077</referencenumber>
                #    <message>6047 Invalid State Code in Customer Node. </message>
                # </orderfailed>
               #end After sending ezpprints to order details it will place ezpprints site and response we will recevive as the below format
              if !response_data["XmlOrder"].nil?
                 reference = response_data["XmlOrder"]["@Reference"]
                 message = reference
              elsif !response_data["XmlOrderFailed"].nil?
                  message = response_data["XmlOrderFailed"]["@Reason"]
              end
          rescue
              redirect_to "/"
           end
     end



#After Sending Order To get the status of ezpprints get notifications.

  def Ezprints_notification_status

   xmlstring = request.raw_post

    begin
      x = CobraVsMongoose.xml_to_hash(xmlstring)
      xd = x.stringify_keys
      oen = xd["OrderEventNotification"]
      not_id = oen["@Id"]
      orders = oen["Order"]
      if orders.class == "Array"
      orders.each do |o|
      EzpOrder_parse(o,not_id)
      end
      else
      order = oen["Order"]
      EzpOrder_parse(order,not_id)
      end
    rescue
  end
   render :text => "<?xml version=\"1.0\" encoding=\"UTF-8\"?><OrderEventNotificationReceived Result=\"Success\"/>"
 end

##parsing the ezp orders and creating the ezp notifications

  def EzpOrder_parse(o,nid)
      oid = o["@Id"]
      oref = o["@EZPReferenceNumber"]
      oin = nil
      itemd = nil
      nt = nil
      ship_method = ""
      begin
      if !o["Accepted"].nil?
      nt = "Accepted"
      oin = o["Accepted"]
      elsif !o["AssetsCollected"].nil?
      nt = "AssetsCollected"
      oin = o["AssetsCollected"]
      elsif !o["InProduction"].nil?
      nt = "InProduction"
      oin = o["InProduction"]
      elsif !o["Canceled"].nil?
      nt = "Canceled"
      oin = o["Canceled"]
      elsif !o["Shipment"].nil?
      nt = "Shipment"
      oin = o["Shipment"]
      elsif !o["CompleteShipment"].nil?
      nt = "CompleteShipment"
      oin = o["CompleteShipment"]
      elsif !o["Complete"].nil?
      nt = "Complete"
      oin = o["Complete"]
      end
      ndt = oin["@DateTime"]
      date = ndt.gsub(%r{\"}, '').gsub("T"," ").split(".")
      if (nt == "Shipment") or (nt == "CompleteShipment")
       unless oin["@Carrier"].nil?
       car = oin["@Carrier"].gsub(%r{\"}, '').to_s
      end
      unless oin["@Service"].nil?
       ser = oin["@Service"].gsub(%r{\"}, '').to_s
      end
      unless oin["@DeliveryMethod"].nil?
      del = oin["@DeliveryMethod"].gsub(%r{\"}, '').to_s
      end
      unless oin["@TrackingNumber"].nil?
      track = oin["@TrackingNumber"].gsub(%r{\"}, '').to_s 
      end
      if car.nil? and ser.nil? and del.nil? and track.nil?
      ship_method = ""
      else
      ship_method = car +"|"+ser +"|"+del +"|"+track
      end
      end
      if oin["Item"].nil?
      itemd = ""
      else
      itemd = oin["Item"].inspect
      end
      if itemd.empty?
      if o["Item"].nil?
      itemd = ""
      else
      itemd = o["Item"].inspect
      end
      end
      not_id = nid[/\w+/].to_i
      ref_no = oref.gsub(%r{\"}, '')
      nt_type = nt[/\w+/].to_s
     rescue
    end 
end

Link for Docs

Comments

Popular posts from this blog

Get the Current url in ruby on rails

request.refererrequest.fullpathrequest.fullpath.split("?")[0]request.referer or request.env['HTTP_REFERER'] your controller to get the referer url. 

--------------------
request.original_url
request.url
request.host_with_port
<link rel="canonical" href="<%= request.url %>" />
<%=request.path%>
How can I get the current absolute URL in my Ruby on Rails view?
The request.request_uri only returns the relative URL.
request.env['REQUEST_URI']

 For Rails 3.2 or Rails 4 you should use request.original_url to get the current URL. More detail.

For Rails 3: You want "#{request.protocol}#{request.host_with_port}#{request.fullpath}", since request.url is now deprecated.

For Rails 2: You want request.url instead of request.request_uri. This combines the protocol (usually http://) with the host, and request_uri to give you the full address

Gem::LoadError (Specified 'mysql2' for database adapter, but the gem is not loaded. Add `gem 'mysql2'` to your Gemfile (and ensure its version is at the minimum required by ActiveRecord).?

Gem::LoadError (Specified 'mysql2' for database adapter, but the gem is not loaded. Add `gem 'mysql2'` to your Gemfile (and ensure its version is at the minimum required by ActiveRecord).) In rails?


1)change the gemfile in mysql version
 gem 'mysql2'

2)Change to mysql2 version
 gem 'mysql2','0.3.20'

Active Scaffold : Add radio buttons to your form ruby on rails ?

Active Scaffold : Add radio buttons to your form ruby on rails ?

The way to add radio buttons to your active scaffold create/update from is as shown below

#Controller

class UsersController < ApplicationController
active_scaffold :user do |config|
config.label = “Users”
config.columns = [:name, :gender]
config.columns[:gender].form_ui = :radio
config.columns[:gender].options[:options] = [['Male', '1'], ['Female','2']]
end
end