如何将PHP SoapClient请求示例转换为RoR?

时间:2018-05-15 11:17:42

标签: php ruby-on-rails http soap-client

我想通过其API使用一些网络服务。在文档中,我发现了一个用PHP SoapClient编写的示例请求。但我使用的是RoR而且我没有PHP经验。有人能告诉我应该如何在RoR中编写相同的内容,或者至少将其翻译成普通的HTTP术语?

<?php
  $soap = new SoapClient(“https://secure.przelewy24.pl/external/wsdl/service.php?wsdl”);
  $test = $soap->TestAccess(“9999”, “anuniquekeyretrievedfromprzelewy24”);
  if ($test)
    echo ‘Access granted’;
  else
    echo ‘Access denied’;
?> 

编辑:特别是我想知道我应该用TestAccess方法做什么,因为普通HTTP中没有方法。我应该使用URL加入此名称吗?

2 个答案:

答案 0 :(得分:1)

为了让您的生活更轻松,请查看允许您简化SOAP访问的gem,例如savon

然后代码可以翻译为

# create a client for the service
client = Savon.client(wsdl: 'https://secure.przelewy24.pl/external/wsdl/service.php?wsdl')

这将自动解析SOAP API中提供的client可能的方法(在WSDL中定义)。要列出可能的操作,请键入

client.operations

在您的情况下,这将列出

[:test_access, :trn_refund, :trn_by_session_id, :trn_full_by_session_id, :trn_list_by_date, :trn_list_by_batch, :trn_full_by_batch, :payment_methods, :currency_exchange, :refund_by_id, :trn_register, :trn_internal_register, :check_nip, :company_register, :company_update, :batch_list, :trn_dispatch, :charge_back, :trn_check_funds, :check_merchant_funds, :transfer_merchant_funds, :verify_transaction, :register_transaction, :deny_transaction, :batch_details]

然后调用该方法,执行以下操作

response = client.call(:test_access, message: { test_access_in: 9999 })
response = client.call(:test_access, message: { 
   test_access_in: 9999 }
   test_access_out: "anuniquekeyretrievedfromprzelewy24" 
)
response.body
 => {:test_access_response=>{:return=>false}}

这会得到一个结果,但我不知道这意味着什么。

答案 1 :(得分:0)

我已经将我们在生产中使用的整个控制器方法作为示例包含在内,但实际上您希望将xml / wsdl请求作为HTTP请求的主体传递,然后将响应解析为xml或我们使用的在rexml之下,可以更方便地遍历返回的文档。

def get_chrome_styles
  require 'net/http'
  require 'net/https'
  require 'rexml/document'
  require 'rexml/formatters/pretty'

  xml = '<?xml version="1.0" encoding="UTF-8"?>
      <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:description7b.services.chrome.com">
        <soapenv:Header/>
        <soapenv:Body>
           <urn:StylesRequest modelId="' + params[:model_id] + '">
              <urn:accountInfo number="[redacted]" secret="[redacted]" country="US" language="en" behalfOf="trace"/>
              <!--Optional:-->
           </urn:StylesRequest>
        </soapenv:Body>
      </soapenv:Envelope>'


  base_url = 'http://services.chromedata.com/Description/7b?wsdl'
  uri = URI.parse( base_url )
  http = Net::HTTP.new(uri.host, uri.port)

  request = Net::HTTP::Post.new("/Description/7b?wsdl")
  request.add_field('Content-Type', 'text/xml; charset=utf-8')
  request.body = xml
  response = http.request( request )

  doc  = REXML::Document.new(response.body)

  options = []
  doc.get_elements('//style').each do |division|
    puts division
    options << { :id => division.attributes['id'], :val => division.text }
  end

  respond_to do |format|
    format.json { render :json => options.to_json }
  end
end