DePayFi / widgets

💸 Payments directly into your wallet. DePay simplifies and improves Web3 Payments with the power of DeFi. Accept any token with on-the-fly conversion and state-of-the-art widgets.
https://depay.com
MIT License
96 stars 36 forks source link

Simplifies track and polling method configuration to just evaluate promises (and not actual returns) #70

Closed 10xSebastian closed 1 year ago

10xSebastian commented 1 year ago

Problem

track: {
  method: async(payment)=>{}
}

was internally relying on not only the promise to resolve but also to return { "status": 200 }.

This is to cumbersome for integrators and also not intuitive, neither was this fact really documented.

Solution

For all configurable methods, track and track.poll, just evaluate if the returned promise resolves, not what it is returning in order to evaluate if the method succeeded, or needs to be retried.

Added Documentation

Alternatively you can pass a method to track that performs the tracking request to your backend if you need to handle the request yourself (e.g. to add additional headers etc.):

DePayWidgets.Payment({

  track: {
    method: async (payment)=>{
      let response = await fetch('/track/payments', {
        method: 'POST',
        body: JSON.stringify(payment),
        headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": document.querySelector('[name=csrf-token]').content }
      })
      if(response.status != 200) {
        throw 'TRACKING FAILED'
      }
    }
  }
})
DePayWidgets.Payment({

  track: {
    method: (payment)=>axios('/track/payments', payment)
  }
})

In case you pass a tracking method it needs to return a promise.

If that promise resolves, the widget assumes the tracking initialization was successful. If the promise rejects it will retry the tracking initialization over and over again.

Make sure to evaluate within your tracking method if the response succeeded or not and throw an error accordingly.

Additional Polling

If you use a method for additional polling, make sure you return a promise. Polling will continue as long as you resolve this promise with anything that resolves to true:

DePayWidgets.Payment({

  track: {
    poll: {
      method: async (payment)=>{
        let response = await fetch('/payments/123/release', {
          method: 'POST',
          body: JSON.stringify(payment),
          headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": document.querySelector('[name=csrf-token]').content }
        })
        if(response.status == 200) {
          let json = await response.json()
          return json // { "forward_to": "https://mywebsite.com/payments/123/confirmation" }
        }
      }
    }
  }
})
DePayWidgets.Payment({

  track: {
    poll: {
      method: async (payment)=>{
        let response = await axios('/payments/123/release', payment)
        return response // { "forward_to": "https://mywebsite.com/payments/123/confirmation" }
      }
    }
  }
})