PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label webhooks. Show all posts
Showing posts with label webhooks. Show all posts

Tuesday, November 22, 2022

[FIXED] How to confirm billing of a monthly subscription in PayPal API via webhook?

 November 22, 2022     javascript, node.js, paypal, paypal-rest-sdk, webhooks     No comments   

Issue

I am trying to implement a PayPal subscription flow where user click on a PayPal subscription button that I have created via the dashboard.

In the back-end, I listen to the PAYMENT.SALE.COMPLETED webhook that is triggered when a subscription billing is successful. Unfortunately the webhook doesn't send me much infos so that I can retrieve the user and item in my DB linked to the just billed subscription.
This would allow me to securely show private content to that user.

Here is the webhook content sent by payPal (sorry for the length):

const response = {
        id: 'WH-4W487015EX264720U-32N35125TV248784B',
        event_version: '1.0',
        create_time: '2021-04-26T08:24:41.436Z',
        resource_type: 'sale',
        event_type: 'PAYMENT.SALE.COMPLETED',
        summary: 'Payment completed for EUR 6.9 EUR',
        resource: {
            billing_agreement_id: 'I-T2HP99MJTS1T',
            amount: {
                total: '6.90',
                currency: 'EUR',
                details: {
                    subtotal: '6.90'
                }
            },
            payment_mode: 'INSTANT_TRANSFER',
            update_time: '2021-04-26T08:23:59Z',
            create_time: '2021-04-26T08:23:59Z',
            protection_eligibility_type: 'ITEM_NOT_RECEIVED_ELIGIBLE,UNAUTHORIZED_PAYMENT_ELIGIBLE',
            transaction_fee: {
                currency: 'EUR',
                value: '0.48'
            },
            protection_eligibility: 'ELIGIBLE',
            links: [
                {
                    method: 'GET',
                    rel: 'self',
                    href: 'https://api.sandbox.paypal.com/v1/payments/sale/6R7481343K8159132'
                },
                {
                    method: 'POST',
                    rel: 'refund',
                    href: 'https://api.sandbox.paypal.com/v1/payments/sale/6R7481343K8159132/refund'
                }
            ],
            id: '6R7481343K8159132',
            state: 'completed',
            invoice_number: ''
        },
        links: [
            {
                href: 'https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-4W487015EX264720U-32N35125TV248784B',
                rel: 'self',
                method: 'GET'
            },
            {
                href: 'https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-4W487015EX264720U-32N35125TV248784B/resend',
                rel: 'resend',
                method: 'POST'
            }
        ],
    }

I have tried to GET the /v1/payments/sale/:id but it didn't bring me much informations.

I have also checked other stack overflow threads on the subject but it wasn't of any help. I also don't want to use success callbacks provided in the front-end SDK because they are not as secure as a webhook (connection can close before triggering the callback see this gitlab issue)

How can I be aware that a user was billed for his subscription ?


Solution

We finally found a workaround to make our back-end retrieve the buyer and the item.

Front-end

On the subscription button code, we noticed after a lot of trial/errors that the createSubscription method accept promises and that we could use it to send the subscriptionId the the back-end before the payment continues:

paypal.Buttons({
    style: {...},
    createSubscription: function (data, actions) {
        return actions.subscription.create({
            /* Creates the subscription */
            plan_id: 'P-26J60279VA924454WMCBPBSA',
        }).then(subscriptionId => { // subscriptionId == I-9DH5L3A3JAEB
            return new Promise((res, rej) => {
                // here we send the subscriptionId to the back-end
                // and create a pending subscription
                const body = {subscriptionId, userId, itemId};
                apiCall('POST', '/subscription', body,() => {
                    // allow to return subscriptionId to paypal
                    resolve(subscriptionId); 
                })
            });
        });
    },
    onApprove: function (data, actions) {
       // this function was of NO USE
       // it is not safe to call your backend here
       // as connexion can close and paypal doesn't
       // wait after this function to capture payment
       // thus leading to orphaned subscriptions 
       // (paid but not linked to your backend)
    },
}).render('#paypal-button');

Back-end (webhook handler)

The back-end wait for the confirmation webhook where webhookResponse.resource.billing_agreement_id is the subscription id and allow to validate the previously created subscription. I don't exactly understand why billing_agreement_id is not named subscrition_id...

Let me know if it's not clear enougth. I let that as an answer until there is a better way to do it :)



Answered By - TOPKAT
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, November 11, 2022

[FIXED] How do you send email data with Stripe connect onboarding in test mode?

 November 11, 2022     payment, payment-gateway, stripe-payments, webhooks     No comments   

Issue

I'm currently setting up Stripe connect on my website and I want to test a webhook that needs the email data to be sent to it. But, in test mode, Stripe says "email is not needed in test mode" and blocks the input. Is there a solution or workaround for this so I can test sending email data?

enter image description here

Thanks,


Solution

In test mode it's not possible to set the email for an Express account during the onboarding flow. But when creating the account with the API, you could set the email parameter (this field is only used to make the account easier to identify for you).

Also note that Stripe don't send any emails in test mode.



Answered By - soma
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, September 26, 2022

[FIXED] How to allow clients to hook into preconfigured hooks in application

 September 26, 2022     backend, continuous-deployment, events, version-control, webhooks     No comments   

Issue

I have a pretty standard application with a frontend, a backend and some options in the frontend for modifying data. My backend fires events when data is modified (eg. record created, record updated, user logged in, etc.).

Now what I want to do is for my customers to be able to code their own functions and "hook" them into these events.

So far the approaches I have thought of are:

  1. Allowing users in the frontend to write some code in a codeeditor like codemirror, but this whole storing code and executing it with some eval() seems kind of risky and unstable.
  2. My second approach is illustrated below (to the best of my ability at least). The point is that the CRUD API calls a different "hook" web service that has these (recordUpdated, recordCreated, userLoggedIn,...) hook methods exposed. Then the client library needs to extend some predefined interfaces for the different hooks I expose. This still seems doable, but my issue is I can't figure out how my customers would deploy their library into the running "hook" service.

So it's kind of like webhooks, except I already know the exact hooks to be created which I figured could allow for an easier setup than customers having to create their own web services from scratch, but instead just create a library that is then deployed into an existing API (or something like that...). Preferably the infrastructure details should be hidden from the customers so they can focus solely on making business logic inside their custom hooks.

It's kind of hard to explain, but hopefully someone will get and can tell me if I'm on the right track or if there is a more standard way of doing hooks like these?

Currently the entire backend is written in C# but that is not a requirement.

enter image description here


Solution

I'll just draft out the main framework, then wait for your feedback to fill in anything unclear.

Disclaimer: I don't really have expertise with security and sandboxing. I just know it's an important thing, but really, it's beyond me. You go figure it out 😂

Suppose we're now in a safe sandbox where all malicious behaviors are magically taken care, let's write some Node.js code for that "hook engine".

How users deploy their plugin code.

Let's assume we use file-base deployment. The interface you need to implement is a PluginRegistry.

class PluginRegistry {
  constructor() {
    /**
    The plugin registry holds records of plugin info:

    type IPluginInfo = {
      userId: string,
      hash: string,
      filePath: string,
      module: null | object,
    }
    */

    this.records = new Map()
  }

  register(userId, info) {
    this.records.set(userId, info)
  }

  query(userId) {
    return this.records.get(userId)
  }
}

// plugin registry should be a singleton in your app.
const pluginRegistrySingleton = new PluginRegistry()

// app opens a http endpoint
// that accepts plugin registration
// this is how you receive user provided code
server.listen(port, (req, res) => {
  if (isPluginRegistration(req)) {
    let { userId, fileBytes, hash } = processRequest(req)
    let filePath = pluginDir + '/' + hash + '.js'

    let pluginInfo = {
      userId,
      // you should use some kind of hash
      // to uniquely identify plugin
      hash,
      filePath,
      // "module" field is left empty
      // it will be lazy-loaded when
      // plugin code is actually needed
      module: null,
    }

    let existingPluginInfo = pluginRegistrySingleton.query(userId)
    if (existingPluginInfo.hash === hash) {
      // already exist, skip
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.end('ok');
    } else {
      // plugin code written down somewhere
      fs.writeFile(filePath, fileBytes, (err) => {
        pluginRegistrySingleton.register(userId, pluginInfo)
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('ok');
      })
    }

  }
})

From the perspective of hook engine, it simply opens a HTTP endpoint to accept plugin registration, agnostic to the source.

Whether it's from CI/CD pipeline, or plain web interface upload, it doesn't matter. If you have CI/CD setup for your user, it is just a dedicated build machine that runs bash scripts isn't it? So just fire a curl call to this endpoint to upload whatever you need. Same applies to web interface.

How we would execute plugin code

User plugin code is just normal Node.js module code. You might instruct them to expose certain API and conform to your protocol.

class HookEngine {
  constructor(pluginRegistry) {
    // dependency injection
    this.pluginRegistry = pluginRegistry
  }

  // hook
  oncreate(payload) {
    // hook call payload should identify the user
    const pluginInfo = this.pluginRegistry.query(payload.user.id)

    // lazy-load the plugin module when needed
    if (pluginInfo && !pluginInfo.module) {
      pluginInfo.module = require(pluginInfo.filePath)
    }

    // user plugin module is just normal Node.js module
    // you load it with `require`, and you call what ever function you need.
    pluginInfo.module.oncreate(payload)
  }
}


Answered By - hackape
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, September 6, 2022

[FIXED] How can I get notifications from Mailchimp's webhook API when I import contacts?

 September 06, 2022     mailchimp, mailchimp-api-v3.0, webhooks     No comments   

Issue

I wanted to synchronize my contacts from mailchimp to my app. I did this by periodically asking Mailchimp if any contacts were updated or created .

Now, I want to do it using the Mailchimp's webhooks.

I have created a webhook in mailchimp and tested it and it works well when I do some changes as Admin using the Mailchimp UI, but when I add or update any contacts using import contacts functionality, I don't receive any notifications.

Mailchimp's webhook API says that they send notifications only when a change is made

  • by a subscriber
  • by an account admin
  • via the API

so, since I'm not getting the notifications I used to get using the previous method, is changing to webhooks a bad option?

Is there any way that I could get the notifications I used to get from my old method, using Mailchimp's webhooks?


Solution

Webhooks may have been omitted from imports to try and protect users from inadvertently DDoSiNg the hook destinations on large imports.

In regards to keeping these two data sets in parity, because webhooks don't have a trigger for import events, I might first suggest exploring another update method for adding subscriber data to the list in MailChimp.

Perhaps looking to the Batch operation options in MailChimp's API:

  • http://developer.mailchimp.com/documentation/mailchimp/reference/batches/
  • http://developer.mailchimp.com/documentation/mailchimp/guides/how-to-use-batch-operations/?utm_source=mc-api&utm_medium=docs&utm_campaign=apidocs&_ga=1.112643975.2008383502.1487629834

As this should allow large updates while keeping the external app abreast of any updates via the triggered webhooks.



Answered By - Stu
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, September 1, 2022

[FIXED] How to configure webhook in nginx?

 September 01, 2022     amazon-ec2, nginx, nginx-location, nginx-reverse-proxy, webhooks     No comments   

Issue

I am trying to configure the nginx.conf file to receive webhook requests from an external website. The request gets failed with status code 405 (not allowed) when I try to call the webhook using postman. The path of the webhook is /hooks

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
#    include /etc/nginx/conf.d/*.conf;
    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
#        server_name  _;
#        root         /usr/share/nginx/html;
        server_name _;
         root /etc/nginx/code/build;
         location / {
              try_files $uri /index.html;
        }
        error_log  /var/log/nginx/jackfruit.error_log  debug;
        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;
        #include /etc/nginx/sites-enabled/*;
        #location / {
        #}
        location /api {
             proxy_pass http://localhost:8000;
       }
        location /hooks/ {
             proxy_pass http://localhost:8000/hooks;
       }
        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }

    }

Solution

Try removing the trailing slash from the location block as such:

location /hooks {
         proxy_pass http://localhost:8000/hooks;
   }

The reason why I suspect this may be an issue:

If a location is defined by a prefix string that ends with the slash character, and requests are processed by one of proxy_pass, fastcgi_pass, uwsgi_pass, scgi_pass, or memcached_pass, then in response to a request with URI equal to this string, but without the trailing slash, a permanent redirect with the code 301 will be returned to the requested URI with the slash appended.



Answered By - snapdeus
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, July 3, 2022

[FIXED] How does a WebHook work in payment system?

 July 03, 2022     http, paypal, php, stripe-payments, webhooks     No comments   

Issue

I'm currently implementing a payments platform for my website which is very similar to Stripe, but I still can't understand the process or how should I use WebHooks since I need to specify one on my account in the payments platform.

So let's say a person pays on my website for a product that costs $5, I take them to the payment form where they will introduce credit card details. Now when they click "Pay Now" everything gets verified via javascript/jquery and sent to my server and I'm able to charge the user successfully and see it reflected on my Sandbox from my account on the payment platform. Where or when should WebHooks be used or called, or why do I need them?

Thanks in advance


Solution

Webhooks are a way to communicate with your application. With many APIs, you send them a request and the API response is included in the response to your request. But what if the request you make is asynchronous, or if for some reason the API you're using wants to be able to communicate with your application by calling it directly as opposed to waiting for you to make the request.

With webhooks, you'd open an endpoint on your application that the other API / service can send requests to so that you can process their requests. You can almost think of it as push notifications for web applications.

With payments the standard use case for webhooks is to handle subscription renewals. So a customer would sign up today and you'd now in response to your createSubscription call whether or not the subscription was created successfully, but how do you know whether or not the subscription renewed successfully? You could either just poll the payments API over and over again, or the payments API can send you a webhook event saying the subscription renewed and in your webhook handler logic you can handle what to do internally (like send a receipt, update some db fields, etc)



Answered By - Matthew Arkin
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, June 30, 2022

[FIXED] How to know which store consumed shopify webhook?

 June 30, 2022     shopify, shopify-app, webhooks     No comments   

Issue

I have created a Shopify app which will allow different store owners to download it and to configure different Web-hooks of their choice like "Order Create", "Order Update" etc...

Each and every Web-hooks are getting configured properly and working fine.

But my issue is "how to know that call to web-hook method is made due to action performed by which of the store"

In sort I wanted to know action performed on which store has triggered web-hook method to be executed.


Solution

It's part of the headers and handshake sent by Shopify to your app.

Regardless of the type of webhook you get a header X-Shopify-Shop-Domain that contains the permanent-shop.myshopify.com address of the shop. see



Answered By - bknights
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing