Stef Hej
Stef Hej

Reputation: 1377

Ruby on Rails How to build a Payment model to deal with Paypal REST SDK

I'd like to create a Payment model along the official Paypal Example on Github. But I'm stuck in the creating of the model with the desired fields.

Payment.new({
    :intent => "sale",
    :payer =>  {
        :payment_method =>  "paypal" },
    :redirect_urls => {
        :return_url => "http://localhost:3000/payment/execute",
        :cancel_url => "http://localhost:3000/" },
    :transactions =>  [{
        :item_list => {
          :items => [{
            :name => "item",
            :sku => "item",
            :price => "5",
            :currency => "USD",
            :quantity => 1 }]},
        :amount =>  {
          :total =>  "5",
          :currency =>  "USD" },
    :description => "This is the payment transaction description." }]})

Starting with rails g model Payment intent:string ... I don't know how to create the nested fields like

:redirect_urls => {
    :return_url => "http://localhost:3000/payment/execute",
    :cancel_url => "http://localhost:3000/" }

and more deeper

:transactions =>  [{
    :item_list => {
      :items => [{
        :name => "item",
        :sku => "item",
        :price => "5",
        :currency => "USD",
        :quantity => 1 }]},

Thanks for any help!

Upvotes: 0

Views: 282

Answers (1)

Jeremie
Jeremie

Reputation: 2401

You can use OpenStruct to do this for you. It will be something like this :

paypal_hash = {
    :intent => "sale",
    :payer =>  {
        :payment_method =>  "paypal" },
    :redirect_urls => {
        :return_url => "http://localhost:3000/payment/execute",
        :cancel_url => "http://localhost:3000/" },
    :transactions =>  [{
        :item_list => {
          :items => [{
            :name => "item",
            :sku => "item",
            :price => "5",
            :currency => "USD",
            :quantity => 1 }]},
        :amount =>  {
          :total =>  "5",
          :currency =>  "USD" },
    :description => "This is the payment transaction description." }]}

paypal_obj = OpenStruct.new(paypal_hash)
paypal_obj.intent
# => "sales"

Upvotes: 1

Related Questions