Develop facebook messenger using NGROK always responsed NULL - php

I had completed setting for ngrok and webhook on facebook.
this is very simple webhook by PHP
$access_token = "my_access_token";
$verify_token = "my_verify_token";
$hub_verify_token = "";
if (isset($_REQUEST['hub_challenge'])) {
$challenge = $_REQUEST['hub_challenge'];
$hub_verify_token = $_REQUEST['hub_verify_token'];
}
if ($hub_verify_token === $verify_token) {
echo $challenge;
exit();
}
$input = json_decode(file_get_contents('php://input'), true);
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
$message = $input['entry'][0]['messaging'][0]['message']['text'];
$message_to_reply = 'I could see your message';
$myjsondata = '{
"recipient":{
"id":"' . $sender . '"
},
"message":{
"text":"' . $message_to_reply . '"
}
}';
send("me/messages", $mydata, $input, $access_token);
function send($type, $data, $input, $access_token) {
$url = 'https://graph.facebook.com/v2.11/' . $type . '?access_token=' . $access_token;
$ch = curl_init($url);
$jsonDataEncoded = $data;
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
if (!empty($input['entry'][0]['messaging'][0]['message'])) {
$result = curl_exec($ch);
// **this $result is always NULL**
}
}
Result, i could receive json info from user typing in my localhost envirment. But when excuting curl, this $result is always NULL and having no error ,so weird.
What's wrong with this ?
PS: If i change webhook to cloud host, Operation is normal but hard to debug :(

Related

Coinbase Pro - IP does not match IP whitelist issue but IP is whitelisted already

I'm using coinbase pro API to fetch some data and to make some trades but API is returning
{"message":"IP does not match IP whitelist"}
I'm using Rest API with correct API keys. I'm sure API keys are authenticated correctly and while creating API keys, I've entered correct IP address of my server. I rechecked IP 5 times but it's correct. Below is my sample code
<?php
function signature($request_path='', $body='', $timestamp=false, $secret = '', $method='GET') {
$body = is_array($body) ? json_encode($body) : $body;
$timestamp = $timestamp ? $timestamp : time();
$what = $timestamp.$method.$request_path.$body;
return base64_encode(hash_hmac("sha256", $what, base64_decode($secret), true));
}
function make_request($url, $method, $headers, $body = ''){
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// Set the url
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, true);
if ($method == "POST") {
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
}
// "accept" => "application/json"
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Execute
$result_json = curl_exec($ch);
curl_close($ch);
return $result_json;
}
try {
$apiurl = "https://api.pro.coinbase.com";
$secret = "SUPER_SECRET";
$api_key = "API_KEY";
$passphrase = "PASSPHRASE";
$method = "GET";
$requestPath = "/accounts";
$body = "";
$url = $apiurl . $requestPath;
$data["name"] = "";
$body = json_encode($data);
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$list = explode(" ", $user_agent);
$user_agent = $list[0];
$timestamp = (string) time();
$string = $timestamp . $method . $requestPath;
$sig = signature($requestPath, '', $timestamp, $secret);
$headers = [
"CB-ACCESS-KEY: ".$api_key,
"CB-ACCESS-SIGN: ".$sig,
"CB-ACCESS-TIMESTAMP: ".$timestamp,
"CB-ACCESS-PASSPHRASE: ".$passphrase,
"User-Agent:". $user_agent,
"Content-Type: application/json",
];
$result_json = make_request($url, $method, $headers);
var_dump($result_json);
die;
}
catch(Exception $e){
var_dump($e->getMessage());
die;
}
I've searched a lot for this problem and been struggling with it since 2 days. If anyone can help or point me in right direction? That would be highly appreciated.
Thanks & Regards.

How do i get the correct redirect url for my shopify app?

I am learning how to make Shopify apps right but I am in trouble because even after following every single line of code correctly I can't seem to figure out what I have done wrong.
Error - It says theshopifystore.myshopify.com refused to connect
everything else is fine i can even store all the info about a store on MySQL but i think the redirect url should be something else can anyone figure out what it is?
Here is the code of all the files that I have made in that process
first - index.php
<?php
include_once("inc/mysql_connect.php");
include_once("header.php");?>
Second - install.php
<?php
// Set variables for our request
$shop = $_GET['shop'];
$api_key = "22xxxxxx151d751c89";
$scopes = "read_orders,write_orders,read_products,write_products";
$redirect_uri = "https://videomap.host/token.php";
// Build install/approval URL to redirect to
$install_url = "https://" . $shop . "/admin/oauth/authorize?client_id=" . $api_key . "&scope=" . $scopes . "&redirect_uri=" . urlencode($redirect_uri);
// Redirect
header("Location: " . $install_url);
die();?>
Third - token.php
<?php
// Get our helper functions
require_once("inc/functions.php");
require_once("inc/mysql_connect.php");
// Set variables for our request
$api_key = "x7151d751c89xxxxxxxxxxx";
$shared_secret = "shxxxxxxxxa72837xxxxxx4f";
$params = $_GET; // Retrieve all request parameters
$hmac = $_GET['hmac']; // Retrieve HMAC request parameter
$params = array_diff_key($params, array('hmac' => '')); // Remove hmac from params
ksort($params); // Sort params lexographically
$computed_hmac = hash_hmac('sha256', http_build_query($params), $shared_secret);
// Use hmac data to check that the response is from Shopify or not
if (hash_equals($hmac, $computed_hmac)) {
// Set variables for our request
$query = array(
"client_id" => $api_key, // Your API key
"client_secret" => $shared_secret, // Your app credentials (secret key)
"code" => $params['code'] // Grab the access key from the URL
);
// Generate access token URL
$access_token_url = "https://" . $params['shop'] . "/admin/oauth/access_token";
// Configure curl client and execute request
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $access_token_url);
curl_setopt($ch, CURLOPT_POST, count($query));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($query));
$result = curl_exec($ch);
curl_close($ch);
// Store the access token
$result = json_decode($result, true);
$access_token = $result['access_token'];
// Show the access token (don't do this in production!)
$sql = "INSERT INTO shop (shop_url, access_token, install_date)
VALUES ('".$params['shop']."', '".$access_token."', NOW())";
if (mysqli_query($conn, $sql)) {
header('Location: https://'.$params['shop'].'/admin/apps');
die();
} else {
echo "Error inserting new record: " . mysqli_error($conn);
}
} else {
// Someone is trying to be shady!
die('This request is NOT from Shopify!');
}?>
Fourth - header.php
<?php $shopify = $_GET;
$sql = "SELECT * FROM shops WHERE shop_url='" . $shopify['shop'] . "' LIMIT 1";
$check = mysqli_query($conn, $sql);
if(mysqli_num_rows($check) < 1){
header("Location: install.php?shop=" . $shopify['shop']);
exit();
}else{
$shop_row = mysqli_fetch_assoc($check);
$shop_url = $shopify['shop'];
$token = $shop_row['access_token'];
}
?>
Fifth - inc/functions.php
<?php
function shopify_call($token, $shop, $api_endpoint, $query = array(), $method = 'GET', $request_headers = array()) {
// Build URL
$url = "https://" . $shop . $api_endpoint;
if (!is_null($query) && in_array($method, array('GET', 'DELETE'))) $url = $url . "?" . http_build_query($query);
// Configure cURL
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($curl, CURLOPT_MAXREDIRS, 3);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
// curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 3);
// curl_setopt($curl, CURLOPT_SSLVERSION, 3);
curl_setopt($curl, CURLOPT_USERAGENT, 'My New Shopify App v.1');
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
// Setup headers
$request_headers[] = "";
if (!is_null($token)) $request_headers[] = "X-Shopify-Access-Token: " . $token;
curl_setopt($curl, CURLOPT_HTTPHEADER, $request_headers);
if ($method != 'GET' && in_array($method, array('POST', 'PUT'))) {
if (is_array($query)) $query = http_build_query($query);
curl_setopt ($curl, CURLOPT_POSTFIELDS, $query);
}
// Send request to Shopify and capture any errors
$response = curl_exec($curl);
$error_number = curl_errno($curl);
$error_message = curl_error($curl);
// Close cURL to be nice
curl_close($curl);
// Return an error is cURL has a problem
if ($error_number) {
return $error_message;
} else {
// No error, return Shopify's response by parsing out the body and the headers
$response = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
// Convert headers into an array
$headers = array();
$header_data = explode("\n",$response[0]);
$headers['status'] = $header_data[0]; // Does not contain a key, have to explicitly set
array_shift($header_data); // Remove status, we've already set it above
foreach($header_data as $part) {
$h = explode(":", $part);
$headers[trim($h[0])] = trim($h[1]);
}
// Return headers and Shopify's response
return array('headers' => $headers, 'response' => $response[1]);
}
}
Sixth - inc/mysql_connect.php
<?php
$host = "localhost";
$username = "xxxxxxx_shopify";
$password ="xxxxxxx1#";
$database = "xxxxxxxopify";
$conn = mysqli_connect($host, $username, $password, $database);
if(!$conn){
die("Connection Error" . mysqli_connect_error());
}
?>

docusign download documents after user sign

I am using docusign-rest-recipes github link to download DOC after user signs.
I am facing following error when I try this code:
"PARTNER_AUTHENTICATION_FAILED .The specified Integrator Key was not found or is disabled. An Integrator key was not specified.".
I have assigned all values correctly, But still I can't get out of this error. Any help is appriciated
<?php
// Input your info here:
$email = "***"; // your account email
$password = "***"; // your account password
$integratorKey = "***"; // your account integrator key, found on (Preferences -> API page)
// copy the envelopeId from an existing envelope in your account that you want
// to download documents from
$envelopeId = "***";
// construct the authentication header:
$header = "<DocuSignCredentials><Username>" . $email . "</Username><Password>" . $password . "</Password><IntegratorKey>" . $integratorKey . "</IntegratorKey></DocuSignCredentials>";
/////////////////////////////////////////////////////////////////////////////////////////////////
// STEP 1 - Login (retrieves baseUrl and accountId)
/////////////////////////////////////////////////////////////////////////////////////////////////
$url = "https://demo.docusign.net/restapi/v2/login_information";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("X-DocuSign-Authentication: $header"));
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 200 ) {
echo "error calling webservice, status is:" . $status;
exit(-1);
}
$response = json_decode($json_response, true);
$accountId = $response["loginAccounts"][0]["accountId"];
$baseUrl = $response["loginAccounts"][0]["baseUrl"];
curl_close($curl);
//--- display results
echo "accountId = " . $accountId . "\nbaseUrl = " . $baseUrl . "\n";
/////////////////////////////////////////////////////////////////////////////////////////////////
// STEP 2 - Get document information
/////////////////////////////////////////////////////////////////////////////////////////////////
$curl = curl_init($baseUrl . "/envelopes/" . $envelopeId . "/documents" );
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"X-DocuSign-Authentication: $header" )
);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 200 ) {
echo "error calling webservice, status is:" . $status;
exit(-1);
}
$response = json_decode($json_response, true);
curl_close($curl);
//--- display results
echo "Envelope has following document(s) information...\n";
print_r($response); echo "\n";
/////////////////////////////////////////////////////////////////////////////////////////////////
// STEP 3 - Download the envelope's documents
/////////////////////////////////////////////////////////////////////////////////////////////////
foreach( $response["envelopeDocuments"] as $document ) {
$docUri = $document["uri"];
$curl = curl_init($baseUrl . $docUri );
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"X-DocuSign-Authentication: $header" )
);
$data = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 200 ) {
echo "error calling webservice, status is:" . $status;
exit(-1);
}
file_put_contents($envelopeId . "-" . $document["name"], $data);
curl_close($curl);
//*** Documents should now be downloaded in the same folder as you ran this program
}
//--- display results
echo "Envelope document(s) have been downloaded, check your local directory.\n";
I have regenerated my $integratorKey again and given 777 permissions to folder where image has to be saved. That $integratorKey was issue, Creating a new one resolved the issue.
Note: You can also get status of DOC by envelope ID, So If status is completed then you can download the DOC.

FB messenger Bot not getting postback payloads

I am developing a facebook chatbot. I am facing a issue which I cannot solve. I am developing this in laravel. Here I cannot get the postback payload. here is my code
public function index(Request $request) {
if ($request->hub_verify_token === $this->verifyToken) {
echo $request->hub_challenge;
exit;
}
$input = json_decode(file_get_contents("php://input"), true);
$senderId = $input['entry'][0]['messaging'][0]['sender']['id'];
$messageText = $input['entry'][0]['messaging'][0]['message']['text'];
$pageId = $input['entry'][0]['id'];
$accessToken = "access_token_that_got_from_fb";
//set Message
if($messageText != "") {
$answer = "Howdy! User";
}
if($messageText == "hello") {
$answer = 'Testing hello from bot';
}
foreach ($input['entry'][0]['messaging'] as $message) {
// When bot receive message from user
if (!empty($message['postback'])) {
$answer = 'got it tada';
}
}
//send message to facebook bot
$response = [
'recipient' => [ 'id' => $senderId ],
'message' => [ 'text' => $answer ] //json_encode($request->getContent())
];
$ch = curl_init('https://graph.facebook.com/v2.11/me/messages?access_token='.$accessToken);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($response));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
$result = curl_exec($ch);
curl_close($ch);
}
and my route is
Route::any('chatbot', 'ChatbotController#index');
here the message is working . but the postback payload request is not going to server. on the other hand using the same code in normal php file I am able to get postback paylod.
$hubVerifyToken = 'chatbot';
$accessToken = "access_token";
// check token at setup
if ($_REQUEST['hub_verify_token'] === $hubVerifyToken) {
echo $_REQUEST['hub_challenge'];
exit;
}
// handle bot's anwser
$input = json_decode(file_get_contents('php://input'), true);
$senderId = $input['entry'][0]['messaging'][0]['sender']['id'];
$messageText = $input['entry'][0]['messaging'][0]['message']['text'];
$postback = isset($input['entry'][0]['messaging'][0]['postback']['payload']) ? $input['entry'][0]['messaging'][0]['postback']['payload'] : '' ;
//set Message
if($messageText == "hi") {
$answer = "Hello";
}
if($messageText == "hello") {
$answer = "Hello there, welcome to Chatleads";
}
if($postback) {
$answer = "postback TADA";
}
//send message to facebook bot
$response = [
'recipient' => [ 'id' => $senderId ],
'message' => [ 'text' => $answer ]
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://graph.facebook.com/v2.11/me/messages?access_token=$accessToken");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($response));
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
How to solve this issue? can anyone show me a path?
Solved it by checking at laravel.log file.
$this->messageText = isset($this->input['entry'][0]['messaging'][0]['message']['text']) ? $this->input['entry'][0]['messaging'][0]['message']['text'] : '' ;
messageText should be like this. that's why its causing an error.

How to authenticate Oauth v1 and PHP

I am using this code to verify the account of users with twitter.
$signature = ??????
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://api.digits.com/1.1/sdk/account.json');
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-length: 0',
'Content-type: application/json',
'Authorization: ' . 'OAuth oauth_nonce="39914766530163254991478493084", oauth_timestamp="1478493084", oauth_version="1.0", oauth_signature_method="HMAC-SHA1", oauth_consumer_key="' . $consumerKey . '", oauth_token="' . $oauthToken . '", oauth_signature="'.$signature.'"',
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($curl);
$info = curl_getinfo($curl);
if ($info['http_code'] == 200) {
$r = json_decode($result);
// var_dump($r->phone_number);
// die();
if (strval($r->phone_number) == strval($phone)) {
// phone is equal, validate the user
curl_close($curl);
return true;
} else {
// phone is not equal
curl_close($curl);
return false;
}
} else {
// unable to auth the user
curl_close($curl);
return false;
}
but I do not know what should I use instead of $signature. how can I generate $signature.
regards
Try this code:
$url = 'https://api.digits.com/1.1/sdk/account.json';
$consumerKey = 'test';
$consumerSecret = 'test';
$oAuth = new OAuth( $consumerKey, $consumerSecret );
echo $oAuth->generateSignature( 'GET', $url ); //EYCZrp4cBizLgXcSX5ex4pYKI8g= (or something like it)
php-oauth need to be installed on your server http://us3.php.net/manual/en/oauth.installation.php.

Categories