Example shows quick and simple setup of a webhooks service.
This example shows a single inline service that logs new messages.
1048
function startInlineServices() {
  // Provide a webhook definition
  var hook = {
    name: 'Inline Sample',
    events: ['message.sent'],
    path: '/inline_sample_message_sent',
  };

  // Register this webhook with Layer's Services
  webhooksServices.register({
    secret: SECRET,
    url: HOST + ':' + PORT,
    hooks: [hook]
  });

  // Listen for events from Layer's Services, and call our callbackAsync with each event
  webhooksServices.listen({
    expressApp: app,
    secret: SECRET,
    hooks: [hook]
  }, redis);

  // Setup your callback to handle the webhook events
  queue.process(hook.name, 50, function(job, done) {
    console.log(new Date().toLocaleString() + ': Inline Sample: Message Received from ' + (job.data.message.sender.user_id || job.data.message.sender.name));
    done();
  });
}
919222
def send_msg_to_webhook(self, json_payload, log_msg):
        
        if SILENCE_OVERRIDE:  # pragma: no cover
            return

        payload = {
            'text': log_msg,
            'attachments':[json_payload]
        }
        header = {
            'Content-Type':'application/json'
        }

        try:
            request = requests.post(
                self.webhook_url,
                headers=header,
                json=payload
            )
            request.raise_for_status()
        except Exception as error_msg:  #pragma: no cover
            warning_msg = (
                'EXCEPTION: UNABLE TO COMMIT LOG MESSAGE' +
                '\n\texception={0}'.format(repr(error_msg)) +
                '\n\tmessage={0}'.format(log_msg)
            )
            warnings.warn(
                warning_msg,
                exceptions.WebhookFailedEmitWarning
            )
436510
def subscribe_to_address_webhook(callback_url, subscription_address, event='tx-confirmation', confirmations=0, confidence=0.00, coin_symbol='btc', api_key=None):
    '''
    
    '''
    assert is_valid_coin_symbol(coin_symbol)
    assert is_valid_address_for_coinsymbol(subscription_address, coin_symbol)
    assert api_key, 'api_key required'

    url = make_url(coin_symbol, 'hooks')

    params = {'token': api_key}
    data = {
        'event': event,
        'url': callback_url,
        'address': subscription_address,
    }

    if event == 'tx-confirmation' and confirmations:
        data['confirmations'] = confirmations
    elif event == 'tx-confidence' and confidence:
        data['confidence'] = confidence

    r = requests.post(url, json=data, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
    response_dict = get_valid_json(r)
    return response_dict['id']
481341
function setupHooks (InstanceModel, config) {
  const ourHookedFnNames = ['save', 'remove', 'index']
  const schema = InstanceModel.schema
  const hooks = _.values(schema.hooks)

  _.forEach(hooks, ho => {
    let addHookFn = 'addDynamicHooks'
    if (!config.promisify) {
      addHookFn = 'addFlexibleHooks'
    }
    InstanceModel.prototype[addHookFn](ho.name)
    const mwopts = { passParams: true }
    _.forEach(ho.fns, (fn, index) => {
      if (ourHookedFnNames.indexOf(ho.name) >= 0) {
        const mwFn = fn
        if (ho.hook === 'post') {
          ho.fns[index] = function (next) {
            mwFn.apply(this)
            next()
          }
        }

        mwopts.passParams = false
      }
    })
    InstanceModel.prototype[ho.hook](ho.name, ho.fns, mwopts)
  })
}
132645
function fetchWebhook() {
        if($this->webhookID === null) {
            throw new \BadMethodCallException('Unable to fetch webhook from a message that was not posted by a webhook');
        }
        
        return (new \React\Promise\Promise(function (callable $resolve, callable $reject) {
            $this->client->apimanager()->endpoints->webhook->getWebhook($this->webhookID)->done(function ($data) use ($resolve) {
                $webhook = new \CharlotteDunois\Yasmin\Models\Webhook($this->client, $data);
                $resolve($webhook);
            }, $reject);
        }));
    }
646480
function send(message, callback) {
  const suppliedCallback = callback || function () {};
  if (!message) {
    return suppliedCallback(new Error('No message'));
  }
  const requestParams = {
    url: this.webhook,
    body: extend(this.options, { text: message }),
    json: true
  };
  return request.post(requestParams, function (err, res, body) {
    if (err || body !== 'ok') {
      return suppliedCallback(err || new Error(body));
    }
    return suppliedCallback(null, body);
  });
}
862373
function runHook (instance, type) {
  var hook = type ? 'response' : 'request'
  hook += 'Hook'
  if (instance[hook] && isFunction(instance[hook])) {
    instance[hook]()
  }
}
410125
def send_webhook(config, payload):
    
    try:
        response = requests.post(
            config['webhook_url'],
            data=json.dumps(payload, cls=ModelJSONEncoder),
            headers={config['api_key_header_name']: config['api_key']},
        )
    except Exception as e:
        logger.warning('Unable to send webhook: ({1}) {2}'.format(
            e.__class__.__name__,
            e.message,
        ))
    else:
        logger.debug('Webhook response: ({0}) {1}'.format(
            response.status_code,
            response.text,
        ))
183792
def add_webhook(self, policy, name, metadata=None):
        
        return self.manager.add_webhook(self, policy, name, metadata=metadata)
977160
protected void logWebServiceMessage(String logMessage, WebServiceMessage message, boolean incoming) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        
        try {
            message.writeTo(os);
            logMessage(logMessage, os.toString(), incoming);
        } catch (IOException e) {
            log.warn("Unable to log WebService message", e);
        }
    }
1106126
public WebhookResources webhookResources() {
        if (webhooks.get() == null) {
            webhooks.compareAndSet(null, new WebhookResourcesImpl(this));
        }
        return webhooks.get();
    }
976273
function createServer(webhook)
{
  var self = this

  var onError = this.emit.bind(this, 'error')

  var port     = webhook.port     || 0
  var hostname = webhook.hostname || HOSTNAME

  var server = http.createServer(function(req, res)
  {
    if(req.method === 'GET')
    {
      res.end()

      return self.push(parse(req.url).query)
    }

    req.pipe(concat(function(body)
    {
      res.end()

      self.push(body.toString())
    }))
  })
  .listen(port, hostname, function()
  {
    var address = this.address()

    if(hostname === HOSTNAME) hostname = getHostname()

    if(!hostname)
    {
      self.emit('error', new Error("There's no public available interfaces"))

      return this.close()
    }

    self.emit('open', 'http://'+hostname+':'+address.port)
  })
  .on('error'      , onError)
  .on('clientError', onError)

  return server
}
134062
function (message) {
    var that = this;
    console.assert(this !== undefined, '[SDK] this !== undefined');

    if (that.__chancelList.length === 0) {
      console.warn(logCord$1, 'You maybe add one chancel');
    }

    lodash.each(that.__chancelList, function (chancel) {
      chancel.server.sendMessage(message);
    });
    that._traceLogEventsCount(TypeMsg.OnNoticeToServer);
    that.mc.trigger(TypeMsg.OnNoticeToServer, message);
    return that
  }
894153
def webhook_handler(request):
    
    body = request.stream.read().decode('utf8')
    print('webhook handler saw:', body)
    api.notify_webhook_received(payload=body)

    # nb. protected references are not part of the API.
    # this is just to demonstrate that the asyncid is stored
    print('key store contains:', api._db.keys())
633501
def webhooks(request):
    

    if request.method != "POST":
        return HttpResponse("Invalid Request.", status=400)

    json = simplejson.loads(request.POST["json"])

    if json["event"] == "recurring_payment_failed":
        zebra_webhook_recurring_payment_failed.send(sender=None, customer=_try_to_get_customer_from_customer_id(json["customer"]), full_json=json)

    elif json["event"] == "invoice_ready":
        zebra_webhook_invoice_ready.send(sender=None, customer=_try_to_get_customer_from_customer_id(json["customer"]), full_json=json)

    elif json["event"] == "recurring_payment_succeeded":
        zebra_webhook_recurring_payment_succeeded.send(sender=None, customer=_try_to_get_customer_from_customer_id(json["customer"]), full_json=json)

    elif json["event"] == "subscription_trial_ending":
        zebra_webhook_subscription_trial_ending.send(sender=None, customer=_try_to_get_customer_from_customer_id(json["customer"]), full_json=json)

    elif json["event"] == "subscription_final_payment_attempt_failed":
        zebra_webhook_subscription_final_payment_attempt_failed.send(sender=None, customer=_try_to_get_customer_from_customer_id(json["customer"]), full_json=json)

    elif json["event"] == "ping":
        zebra_webhook_subscription_ping_sent.send(sender=None)

    else:
        return HttpResponse(status=400)

    return HttpResponse(status=200)
277845
def post(self, data):
        
        if not self.url:
            raise Error('URL for incoming webhook is undefined')

        return requests.post(self.url, data=json.dumps(data),
                             timeout=self.timeout, proxies=self.proxies)
807855
def process_webhooks(webhooks)
      webhooks.each do |element|
        webhook = Webhook.new(element, @bot)
        @webhooks[webhook.id] = webhook
      end
    end