2014-01-30 2 views
0

Magento SOAP API v1과 Savon gem을 사용하여 Rails 4에 앱을 빌드하고 있습니다. 지금은 보류 상태의 모든 주문을 받으려고합니다. 다음이Magento SOAP API v1에서 필터를 Rails 4 및 Savon과 함께 사용하는 방법은 무엇입니까?

class MagentoAPI 
    def self.call method, options={} 
    response = @@soap_client.request :call do 
     if options.empty? 
     soap.body = { :session => @@soap_session, :method => method } 
     elsif options[:string] 
     soap.body = { :session => @@soap_session, :method => method, :arguments => [options[:string]] } 
     else 
     puts options 
     soap.body = { :session => @@soap_session, :method => method, :arguments => options } 
     end 
    end 
    if response.success? 
     # listing found products 
     final = [] 
     call_return = response[:call_response][:call_return] 
     return [] if call_return[:item].nil? 
     raw = call_return[:item] 
     if raw.is_a? Hash # this is a list of one item 
     final << raw[:item].inject({}){|x,y| x.merge(y[:key]=>y[:value])} 
     else 
     if raw[0][:item].nil? # this is a product info 
      return raw.inject({}){|x,y| x.merge(y[:key]=>y[:value])} 
     else # this is a list of many items 
      raw.each{|result| final << result[:item].inject({}){|x,y| x.merge(y[:key]=>y[:value])}} 
     end 
     end 
     final 
    end 
    end 
end 

: 그리고 이건 그냥 그래서 내가 제대로 요청을 포맷하고 있지 않다 생각하고 Savon::HTTP::Error을 반환

class Order 
    def self.get_all_active 
    activeOrders = MagentoAPI.call 'order.list', :filter => {:status => 'pending'} 
    end 
end 

내가 this 코드를 사용하고있는 API에 후크합니다. 아무도 이것에 대한 경험이나 통찰력을 가지고 있지 않습니까?

+0

여전히 해결할 문제입니까? 그렇다면 최소한의 코드로 문제를 제거 할 수 있습니까? 너무 복잡합니다. Savon 및 SOAP 호출에 대해 도움을 드릴 수 있지만 관련 문제가 발생하기 전에 먼저 코드의 논리를 이해할 여유가 없습니다. 아무도 여기까지 아무 것도 쓰지 않은 이유라고 생각합니다. –

+0

답장을 보내 주신 @SteffenRoller에게 감사드립니다. 나는 이것을 끝내기 위해 PHP를 사용하여 끝내었고 잘 동작한다. Magento가 깊이 중첩 된 배열을 기대하는 방식에 문제가 있다고 생각합니다. Savon은 Magento가 처리 할 수있는 방식으로 해시를 해당 배열로 변환하지 않았습니다. Magento의 말에 더 많은 문제가 있다고 생각합니다. Savon을 사용하여 API에 대한 모든 인수가 필요하지 않은 요청은 정상적으로 처리되었지만보다 구체적인 것을 요구하면 일반 SOAPFault 오류가 발생합니다. – jweaver60

답변

2

희망 사항이 너무 늦지 않으 리라 생각되지만 (기본 가정이라고 가정)이 기본 문건으로 보석을 만들었습니다. 이번 주말이나 다음 주에 마무리하길 원하지만 코드를 살펴보고 Magento 용 필터를 만드는 방법을 살펴볼 수 있습니다. 설치하려면, 단지 실행 : 당신은 마 젠토의 SOAP API의 간단한 필터 중 하나를 사용하려면

gem install magento_api_wrapper 

은, 요약하면, 당신은 키와 값으로 해시를 전달할 수 있습니다

api = MagentoApiWrapper::Sales.new(magento_url: "yourmagentostore.com/index.php", magento_username: "soap_api_username", magento_api_key: "userkey123") 

api.order_list(simple_filters: [{key: "status", value: "processing"}, {key: created_at, value: "12/10/2013 12:00" }]) 

하고를 복잡한 필터를 사용, 키, 연산자 및 값으로 해시를 전달합니다

api.order_list(complex_filters: [{key: "status", operator: "eq", value: ["processing", "completed"]}, {key: created_at, operator: "from", value: "12/10/2013" }]) 

이것은 모든 젠토 주문에 해시의 배열을 반환합니다.

특히, 요청 코드 체크 아웃 : 그냥 보석을 사용하기 쉬울 것입니다 있지만, 여기에 내가 젠토의의 서식을 끝내면 SavonClient,에 전달하기 전에 요청을 포맷하고있어 방법 https://github.com/harrisjb/magento_api_wrapper/blob/master/lib/magento_api_wrapper/requests/sales_order_list.rb

을 SOAP의 API :

def call 
     client.call(@request.call_name, message: message_with_attributes, response_parser: :nokogiri) 
    end 

    #message_with_attributes are required for some specific formatting when updating Magento via the SOAP API 
    def message_with_attributes 
     @request.body.merge!(:attributes! => @request.attributes) unless @request.attributes.empty? 
     puts "REQUEST: #{@request.inspect}" 
     return @request.body 
    end 

    #configuration of the client is mostly mandatory, however some of these options (like timeout) will be made configurable in the future 
    #TODO: make timeout configurable 
    def client 
     Savon::Client.new do |savon| 
     savon.ssl_verify_mode   :none 
     savon.wsdl      base_url 
     savon.namespaces    namespaces 
     savon.env_namespace   'SOAP-ENV' 
     savon.raise_errors    false 
     #savon.namespace_identifier  #none 
     savon.convert_request_keys_to :lower_camelcase 
     savon.strip_namespaces   true 
     savon.pretty_print_xml   true 
     savon.log      log_env 
     savon.open_timeout    10 #seconds 
     savon.read_timeout    45 #seconds 
     end 
    end 

    #TODO: make configurable 
    def log_env 
     true 
    end 

    #correctly format MagentoApiWrapper::Request call_names for SOAP v2 
    def response_tag_format_lambda 
     lambda { |key| key.snakecase.downcase } 
    end 

    def namespaces 
     { 
     'xmlns:SOAP-ENV' => 'http://schemas.xmlsoap.org/soap/envelope/', 
     'xmlns:ns1' => 'urn:Magento', 
     'xmlns:xsd' => 'http://www.w3.org/2001/XMLSchema', 
     'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance', 
     'xmlns:SOAP-ENC' => 'http://schemas.xmlsoap.org/soap/encoding/', 
     'SOAP-ENV:encodingStyle' => 'http://schemas.xmlsoap.org/soap/encoding/' 
     } 
    end 

    #Use MagentoApiWrapper::Api magento_url as endpoint 
    def base_url 
     "#{@magento_url}/api/v2_soap?wsdl=1" 
    end 
    end 
:

def body 
     merge_filters!(sales_order_list_hash) 
    end 

    def attributes 
     { session_id: { "xsi:type" => "xsd:string" }, 
     filters: { "xsi:type" => "ns1:filters" }, 
     } 
    end 

    def sales_order_list_hash 
     { 
     session_id: self.session_id 
     } 
    end 

    def merge_filters!(sales_order_list_hash) 
     if !filters_array.empty? 
     sales_order_list_filters = { 
      filters: filters_array, 
     } 
     sales_order_list_hash.merge!(sales_order_list_filters) 
     else 
     sales_order_list_hash 
     end 
    end 

    def filters_array 
     custom_filters = {} 
     custom_filters.compare_by_identity 
     if !simple_filters.nil? 
     add_simple_filters(custom_filters) 
     end 

     if !complex_filters.nil? 
     add_complex_filters(custom_filters) 
     end 
     custom_filters 
    end 

    def add_simple_filters(custom_filters) 
     simple_filters.each do |sfilter| 
     custom_filters[:attributes!] = { 
      "filter" => { 
      "SOAP-ENC:arrayType" => "ns1:associativeEntity[2]", 
      "xsi:type" => "ns1:associativeArray" 
      } 
     } 
     custom_filters["filter"] = { 
      item: { 
      key: sfilter[:key], 
      value: sfilter[:value], #formatted_timestamp(created_at) 
      :attributes! => { 
       key: { "xsi:type" => "xsd:string" }, 
       value: { "xsi:type" => "xsd:string" } 
      }, 
      }, 
      :attributes! => { 
      item: { "xsi:type" => "ns1:associativeEntity" }, 
      }, 
     } 
     end 
     custom_filters 
    end 

    def add_complex_filters(custom_filters) 
     complex_filters.each do |cfilter| 
     custom_filters[:attributes!] = { 
      "complex_filter" => { 
      "SOAP-ENC:arrayType" => "ns1:complexFilter[2]", 
      "xsi:type" => "ns1:complexFilterArray" 
      } 
     } 
     custom_filters["complex_filter"] = { 
      item: { 
      key: cfilter[:key], 
      value: { 
       key: cfilter[:operator], 
       value: cfilter[:value] 
      }, 
      :attributes! => { 
       key: { "xsi:type" => "xsd:string" }, 
       value: { "xsi:type" => "xsd:associativeEntity" } 
      }, 
      }, 
      :attributes! => { 
      item: { "xsi:type" => "ns1:complexFilter" }, 
      }, 
     } 
     end 
     custom_filters 
    end 

    def formatted_timestamp(timestamp) 
     begin 
     Time.parse(timestamp).strftime("%Y-%m-%d %H:%M:%S") 
     rescue MagentoApiWrapper::BadRequest => e 
     raise "Did you pass date in format YYYY-MM-DD? Error: #{e}" 
     end 
    end 

    def status_array 
     data[:status_array] 
    end 

    def created_at_from 
     data[:created_at_from] 
    end 

    def created_at_to 
     data[:created_at_to] 
    end 

    def last_modified 
     data[:last_modified] 
    end 

    def session_id 
     data[:session_id] 
    end 

    def simple_filters 
     data[:simple_filters] 
    end 

    def complex_filters 
     data[:complex_filters] 
    end 

는 또한 여기에 대부분의 특정 API에 대한 구성의 일부를 수행하는 SavonClient있어

내가 말했듯이, 진행중인 작업이지만, 앞으로 몇 주 내에 Magento API에 대해 꽤 잘 설명해야합니다. 희망이 당신을 도와줍니다! 행운을 빕니다!

+0

이러한 링크가 질문에 대답 할 수 있지만 여기에 답변의 핵심 부분을 포함하고 참조 용 링크를 제공하는 것이 좋습니다. 링크 된 페이지가 변경되면 링크 전용 답변이 유효하지 않게 될 수 있습니다. – Joel

+1

Joel은 링크의 소스 코드를 포함하도록 답변을 편집하여 명확성을 보장하고 답변은 사이트 기록에 따라 계속 유지됩니다. – harrisjb

+0

참조 하시겠습니까? 그리고 그것은 당신이 나에게서 +1을 얻는 방법입니다! – Joel