How to authenticate Oauth v1 and PHP - 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.

Related

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());
}
?>

How to get json for soundcloud without type

I get JSON from the Soundcloud API by using code in section【A】.
But I want to get it without using $type, like in code【B】.
In other words, I want to get that information by only giving $target.
What should I do?
$r = soundcloud_responce();
var_dump( $r );
function soundcloud_responce(){
$client_id = 'xxx';
$type = 'tracks';
$q = 'words';
// code【A】
// If I have $type, So this process ok.
$url = "https://api.soundcloud.com/";
$url .= $type;
$url .= "?client_id=$client_id";
$url .= "&q=$q";
// code【B】
// I want to do same process with $target but without $type
$target = "https://soundcloud.com/accountname/trackname";
$target = str_replace('https://soundcloud.com/', '', $target);
$url = "https://api.soundcloud.com/";
$url .= $target;
$url .= "?client_id=$client_id";
// curl
$ch = curl_init();
$headers = [
'Accept: application/json',
'Content-Type: application/json',
];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$res = curl_exec($ch);
$json = json_decode($res);
curl_close($ch);
return $json;
}
(Add 2020-02-21-09:38 #Tokyo)
I tried this code【C】but this also failed.
// code【C】
// I tried with oembed but this also failed.
$target = "https://soundcloud.com/accountname/trackname";
$url = 'http://soundcloud.com/oembed?format=json&url='.$target;
(Add 2020-02-21-10:12 #Tokyo)
I tried this code【D】but this also failed.
// code【D】
// I tried with resolve but this also failed.
$target = "https://soundcloud.com/accountname/trackname";
$url = "https://api.soundcloud.com/resolve?url=$target&client_id=$client_id";
I tried this code【E】this is successful!
Thank you for giving me good advice, #showdev.
// code【E】
// this is successful!
$target = "https://soundcloud.com/accountname/trackname";
$target = urlencode($target);
$url = "https://api.soundcloud.com/resolve.json?url=$target&client_id=$client_id";

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.

Develop facebook messenger using NGROK always responsed NULL

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 :(

How to replace tokens on email campain using REST API in PHP ?

I have an email campaign on Marketo to send emails using PHP. on my email template I have a token like, {{my.emailBody:default=Body}} I would like to replace the the token with my custom email content from my PHP code,
This is my code,
$sample = new SendSampleEmail();
$sample->id = 11111;
$sample->emailAddress = "myemail#example.com";
print_r($sample->postData());
class SendSampleEmail{
private $host = "https://AAA-AAA-121.mktorest.com";
private $clientId = "dxxxxxxxxxxxxxxxxxxxxx1";
private $clientSecret = "Sxxxxxxxxxxxxxxxxxxxxxxxxxxxxe";
public $id; //id of to delete
public $emailAddress;//email address to send to
public $textOnly;//boolean option to send text only version
public $leadId;// id of lead to impersonate
public function postData(){
$url = $this->host . "/rest/asset/v1/email/" . $this->id . "/sendSample.json?access_token=" . $this->getToken();
$requestBody = "&emailAddress=" . $this->emailAddress;
if (isset($this->textOnly)){
$requestBody .= "&textOnly=" . $this->textOnly;
}
if (isset($this->leadId)){
$requestBody .= "&leadId=" . $this->leadId;
}
//print_r($requestBody);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('accept: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody);
curl_getinfo($ch);
$response = curl_exec($ch);
return $response;
}
private function getToken(){
$ch = curl_init($this->host . "/identity/oauth/token?grant_type=client_credentials&client_id=" . $this->clientId . "&client_secret=" . $this->clientSecret);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('accept: application/json',));
$response = json_decode(curl_exec($ch));
curl_close($ch);
$token = $response->access_token;
return $token;
}
}
Using this code I can successfully trigger the emails, but how can I replace the token value {{my.emailBody:default=Body}} ?
I have the same problem which I tried to used Assets Tokens from the REST API: http://developers.marketo.com/rest-api/assets/tokens/
to modify token's values, but it is the only endpoint I cannot make it work. Please let me know if you could make it work.
However, I used the SOAP API to solve for this issue:
You create a Batch Campaign from Marketo inside a Marketo Program that contains the Token you want to modify and the email you want to send using that token.
The SOAP API will schedule the campaign to run (you can set the current time for immediate run), and you can set the value for the tokens:
public function schedule_campaign($program_name,$campaign_name,$token_name,$token_value)
{
$params = new stdClass();
$params->programName = $program_name;
$params->campaignName = $campaign_name;
$dtzObj = new DateTimeZone("America/New_York");
$dtObj = new DateTime('now', $dtzObj);
$params->campaignRunAt = $dtObj->format(DATE_W3C);
$token = new stdClass();
$token->name = "{{my.".$token_name."}}";
$token->value = $token_value;
$params->programTokenList = array("attrib" => $token);
$params = array("paramsScheduleCampaign" => $params);
$soapClient = new SoapClient(MARKETO_SOAP_ENDPOINT ."?WSDL", self::$auth_options);
try
{
$response = $soapClient->__soapCall('scheduleCampaign', $params, self::$auth_options, self::$auth_header);
return true;
}
catch(Exception $ex) {
return false;
}
}
UPDATE:
I've found the way to update/replace tokens using REST API:
public function create_token($folder_id,$name,$content,$folder_type = 'Program')
{
$folder_id = intval($folder_id);
$endpoint = 'rest/asset/v1/folder/'.$folder_id.'/tokens';
$url = $this->url . $endpoint . ".json?access_token=" . self::$token."&folderType=".$folder_type."&name=".$name."&type=". urlencode('rich text')."&value=".urlencode($content);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POST, 1);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response);
}
Token replacement only works with the Request Campaign and Schedule Campaign APIs, you can't replace my tokens with the send sample email API.

Categories