如何在Rails中通过Paypal智能按钮集成实现Paypal付款

时间:2020-07-21 19:02:53

标签: ruby-on-rails paypal paypal-rest-sdk

我已经通过使用SmartButtons并在server-side中创建订单在Rails应用程序中实现了PayPal结帐API。

我使用了payouts-ruby-sdk gem,我的代码如下:-

index.html.erb
<!-- Set up a container element for the button -->
<div id="paypal-button-container"></div>

<!-- Include the PayPal JavaScript SDK -->
<script src="https://www.paypal.com/sdk/js?client-id=xyz&currency=USD"></script>

<script>
    // Render the PayPal button into #paypal-button-container
    paypal.Buttons({

        // Call your server to set up the transaction
        createOrder: function(data, actions) {
            return fetch('/orders', {
                method: 'post'
            }).then(function(res) {
                return res.json();
            }).then(function(orderData) {
                return orderData.orderID;
            });
        },

        // Call your server to finalize the transaction
        onApprove: function(data, actions) {
            return fetch('/orders/' + data.orderID + '/capture', {
                method: 'post'
            }).then(function(res) {
                return res.json();
            }).then(function(orderData) {
                // Three cases to handle:
                //   (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart()
                //   (2) Other non-recoverable errors -> Show a failure message
                //   (3) Successful transaction -> Show a success / thank you message

                // Your server defines the structure of 'orderData', which may differ
                var errorDetail = Array.isArray(orderData.details) && orderData.details[0];

                if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {
                    // Recoverable state, see: "Handle Funding Failures"
                    // https://developer.paypal.com/docs/checkout/integration-features/funding-failure/
                    return actions.restart();
                }

                if (errorDetail) {
                    var msg = 'Sorry, your transaction could not be processed.';
                    if (errorDetail.description) msg += '\n\n' + errorDetail.description;
                    if (orderData.debug_id) msg += ' (' + orderData.debug_id + ')';
                    // Show a failure message
                    return alert(msg);
                }

                // Show a success message to the buyer
                alert('Transaction completed');
            });
        }


    }).render('#paypal-button-container');
</script>

orders_controller.rb

class OrdersController < ApplicationController
   skip_before_action :verify_authenticity_token

  def index
  end

  def create
    # Creating Access Token for Sandbox
        client_id =  'xyz'
      client_secret = 'abc'
        # Creating an environment
        environment = PayPal::SandboxEnvironment.new(client_id, client_secret)
        client = PayPal::PayPalHttpClient.new(environment)

        request = PayPalCheckoutSdk::Orders::OrdersCreateRequest::new
        request.request_body({
                                intent: "CAPTURE",
                                purchase_units: [
                                    {
                                        amount: {
                                            currency_code: "USD",
                                            value: "10.00"
                                        }
                                    }
                                ]
                              })

        begin
        # Call API with your client and get a response for your call
        # debugger
        response = client.execute(request)
        puts response.result.id
        render json: {success: true, orderID: response.result.id}
        rescue PayPalHttp::HttpError => ioe
            # Something went wrong server-side
            puts ioe.status_code
            puts ioe.headers["debug_id"]
        end
  end

  def execute_payment
    client_id =  'xyz'
    client_secret = 'abc'
        # Creating an environment
        environment = PayPal::SandboxEnvironment.new(client_id, client_secret)
        client = PayPal::PayPalHttpClient.new(environment)

      request = PayPalCheckoutSdk::Orders::OrdersCaptureRequest::new(session[:orderID])

        begin
            # Call API with your client and get a response for your call
            response = client.execute(request) 
            
            # If call returns body in response, you can get the deserialized version from the result attribute of the response
            order = response.result
            puts order
        rescue PayPalHttp::HttpError => ioe
            # Something went wrong server-side
            puts ioe.status_code
            puts ioe.headers["debug_id"]
        end
  end
end

现在,我想实现Paypal的Payouts API,我知道paypal-ruby-sdk可以使用,但是我很困惑该代码的位置以及如何将其与前端集成。有任何想法吗?在此先感谢:)

1 个答案:

答案 0 :(得分:0)

上面的代码是Checkout代码,既适用于前端(JavaScript),也适用于后端(Ruby)。

Payouts与Checkout无关,无论是前端Checkout还是后端Checkout。

付款严格是一种后端API操作,您可以在其中将钱从您的帐户转账到另一个帐户。

付款未连接到任何前端UI。如果需要,您可以构建自己的UI来触发付款。大概您知道您想从您的帐户向谁汇款,以及应该由什么程序触发该操作。