Telegram Bot PHP keyboard doesn't works - bots

I have a problem to creating a custom keyboard for my telegram bot.
Simply, it doesn't works and I don't know the reason...
This is my code:
<?
$botToken = "*****";
$website = "https://api.telegram.org/bot".$botToken;
$update = file_get_contents('php://input');
$update = json_decode($update, TRUE);
$chatId = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];
$telegramusername = $update["message"]["from"]["username"];
$message_id = $update["message"]["message_id"];
$message_name = $update["message"]["chat"]["first_name"];
switch($message)
{
case "ciao":
funzioneCiao($chatId);
break;
case "youtube":
TastieraInline($chatId);
break;
default:
TastieraMenuPrincipale($chatId);
break;
}
function inviaMessaggio($chatId, $messaggio)
{
$url = "$GLOBALS[website]/sendMessage?chat_id=$chatId&parse_mode=HTML&text=".urlencode($messaggio);
file_get_contents($url);
}
function funzioneCiao($chatId)
{
$messaggio = "ciao";
inviaMessaggio($chatId, $messaggio);
}
function TastieraMenuPrincipale($chatId)
{
$messaggio = "ciaaaao";
$tastiera = '&reply_markup={"keyboard":[["Menu Principale"],["Developer"]]}';
$url = "$GLOBALS[website]"."/sendMessage?chat_id=".$chatId."&parse_mode=HTML&text=".$messaggio.$tastiera;
file_get_contents($url);
}
function TastieraInline($chatId)
{
$message = "Iscriviti subito";
$tastiera = '&reply_markup={"inline_keyboard":[[{"text":"SEGUIMI!","url":"http://www.youtube.com"}]]}';
$url = $GLOBALS[website].'/sendMessage?chat_id='.$chatId.'&parse_mod=HTML&text='.$message.$tastiera;
file_get_contents($url);
}
?>
Functions: "funzioneCiao($chatId);" and "inviaMessaggio($chatId, $messaggio)" works but,
"TastieraMenuPrincipale($chatId)" and "TastieraInLine($ChatId)" doesn't works.
I'm a beginner in PHP so I have a lot difficult...
Thank you.

I just tested the code, it works perfectly...

Why didn't you use CURL instead of file_get_contents(); ?!
just write this function into your code then call it after getting new updates :
function makeHTTPRequest($method, $types = []){
$url = 'https://api.telegram.org/bot'.$botToken.'/'.$method;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($types));
$res = curl_exec($ch);
if (curl_error($ch)){
var_dump(curl_error($ch));
} else {
return json_decode($res);
}
}
make sure CURL is activated on your hosting server!

Related

Hi anyone? Go here a little bit

I'm having problem in my telegram bot with this code
<?php
if ($_SERVER['HTTPS'] != "on") {
$url = "https://". $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
header("Location: $url");
exit;
}
$botToken = "XXXX...";
$website = "https://api.telegram.org/bot".$botToken;
$content = file_get_contents("php://input");
$update = json_decode($content, true);
$chatId = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];
// get message_id
$messageId = $update["message"]["message_id"];
switch($message) {
case("action"):
sendMessage($chatId, "What should I do?");
break;
case("add"):
// add the 2nd parameter
editMessageText($chatId, $messageId, "should I add?");
break;
default:
sendMessage($chatId, "default");
}
function sendMessage($chatId, $message) {
$url = $GLOBALS[website]."/sendMessage? chat_id=".$chatId."&text=".urlencode($message)."&reply_markup".$reply1;
file_get_contents($url);
}
function editMessageText($chatId, $messageId, $message) {
$url = $GLOBALS[website]."/editMessageText?chat_id=".$chatId."&message_id=".$messageId."&text=".urlencode($message);
file_get_contents($url);
}
function file_get_contents_curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
?>
I tried to use this as a example and its not work if I use this its keep loading and after a minute the bot will spam me with the same amount of button i press with him
I already used above code but its not editing it incase its sending me the same message
You need to add break inside default
default:
sendMessage($chatId, "default");
break;
}
I capture this one I think it is also getting some error, you did not assign any value to variable $reply1, and also missing = mark after the &reply_markup
function sendMessage($chatId, $message) {
$url = $GLOBALS[website]."/sendMessage?chat_id=".$chatId."&text=".urlencode($message)."&reply_markup".$reply1;
file_get_contents($url);
}
if you need to run for the testing use this
function sendMessage($chatId, $message) {
$url = $GLOBALS[website]."/sendMessage?chat_id=".$chatId."&text=".urlencode($message);
file_get_contents($url);
}
If you need any help

Amazon sp-API aws signature issue

AMAZON SP-API AWS SIGNATURE The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details
public function getOrdersFromApi(){
// Configuration values
$host = 'sellingpartnerapi-eu.amazon.com';
$accessKey = 'XXXXX';
$secretKey = 'XXXXXX';
$region = 'eu-west-1';
$service = 'execute-api';
/**
* You should modify the script
* for
* 1. full request url
* 2. uri for AWS signature
* 3. request method GET / POST / PUT
* 4. actual data of the request
* and call the above functions
*/
$requestUrl = 'https://sellingpartnerapi-eu.amazon.com/orders/v0/orders?MarketplaceIds=A21TJRUUN4KGV&CreatedAfter=2021-01-15T05:26:31.308992';
$uri = '?MarketplaceIds=A21TJRUUN4KGV&CreatedAfter=2021-01-15T05:26:31.308992';
$httpRequestMethod = 'GET';
$data = json_encode(array());
$headers = $this->calcualteAwsSignatureAndReturnHeaders($host, $uri, $requestUrl,
$accessKey, $secretKey, $region, $service,
$httpRequestMethod, $data, TRUE);
$result = $this->callToAPI($requestUrl, $httpRequestMethod, $headers, $data, TRUE);
print_r($result);
}
public function calcualteAwsSignatureAndReturnHeaders($host, $uri, $requestUrl,
$accessKey, $secretKey, $region, $service,
$httpRequestMethod, $data, $debug = TRUE){
$terminationString = 'aws4_request';
$algorithm = 'AWS4-HMAC-SHA256';
$phpAlgorithm = 'sha256';
$canonicalURI = $uri;
$canonicalQueryString = '';
$signedHeaders = 'content-type;host;x-amz-date'; $signedHeaders = "content-type;host;user-agent;x-amz-access-token;x-amz-date;x-amz-security-token";
$currentDateTime = new DateTime('UTC');
$reqDate = $currentDateTime->format('Ymd');
$reqDateTime = $currentDateTime->format('Ymd\THis\Z');
// Create signing key
$kSecret = $secretKey;
$kDate = hash_hmac($phpAlgorithm, $reqDate, 'AWS4' . $kSecret, true);
$kRegion = hash_hmac($phpAlgorithm, $region, $kDate, true);
$kService = hash_hmac($phpAlgorithm, $service, $kRegion, true);
$kSigning = hash_hmac($phpAlgorithm, $terminationString, $kService, true);
// Create canonical headers
$canonicalHeaders = array();
$canonicalHeaders[] = 'content-type:application/json';
$canonicalHeaders[] = 'host:' . $host;
$canonicalHeaders[] = 'x-amz-date:' . $reqDateTime;
$canonicalHeadersStr = implode("\n", $canonicalHeaders);
// Create request payload
$requestHasedPayload = hash($phpAlgorithm, $data);
// Create canonical request
$canonicalRequest = array();
$canonicalRequest[] = $httpRequestMethod;
$canonicalRequest[] = $canonicalURI;
$canonicalRequest[] = $canonicalQueryString;
$canonicalRequest[] = $canonicalHeadersStr . "\n";
$canonicalRequest[] = $signedHeaders;
$canonicalRequest[] = $requestHasedPayload;
$requestCanonicalRequest = implode("\n", $canonicalRequest);
$requestHasedCanonicalRequest = hash($phpAlgorithm, utf8_encode($requestCanonicalRequest));
if($debug){
echo "<h5>Canonical to string</h5>";
echo "<pre>";
echo $requestCanonicalRequest;
echo "</pre>";
}
// Create scope
$credentialScope = array();
$credentialScope[] = $reqDate;
$credentialScope[] = $region;
$credentialScope[] = $service;
$credentialScope[] = $terminationString;
$credentialScopeStr = implode('/', $credentialScope);
// Create string to signing
$stringToSign = array();
$stringToSign[] = $algorithm;
$stringToSign[] = $reqDateTime;
$stringToSign[] = $credentialScopeStr;
$stringToSign[] = $requestHasedCanonicalRequest;
$stringToSignStr = implode("\n", $stringToSign);
if($debug){
echo "<h5>String to Sign</h5>";
echo "<pre>";
echo $stringToSignStr;
echo "</pre>";
}
// Create signature
$signature = hash_hmac($phpAlgorithm, $stringToSignStr, $kSigning);
// Create authorization header
$authorizationHeader = array();
$authorizationHeader[] = 'Credential=' . $accessKey . '/' . $credentialScopeStr;
$authorizationHeader[] = 'SignedHeaders=' . $signedHeaders;
$authorizationHeader[] = 'Signature=' . ($signature);
$authorizationHeaderStr = $algorithm . ' ' . implode(', ', $authorizationHeader);
// Request headers
$headers = array();
$headers[] = 'authorization:'.$authorizationHeaderStr;
$headers[] = 'content-length:'.strlen($data);
$headers[] = 'content-type: application/json';
$headers[] = 'user-agent:sellergeni/1.0 (Php=7.2)';
$headers[] = 'x-amz-access-token:Atza|IwEBII0yZlQvoo95puL9xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$headers[] = 'host: ' . $host;
$headers[] = 'x-amz-date: ' . $reqDateTime;
return $headers;
}
public function callToAPI($requestUrl, $httpRequestMethod, $headers, $data, $debug=TRUE)
{
// Execute the call
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $requestUrl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_POST => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => $httpRequestMethod,
CURLOPT_POSTFIELDS => $data,
CURLOPT_VERBOSE => 0,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_HEADER => false,
CURLINFO_HEADER_OUT=>true,
CURLOPT_HTTPHEADER => $headers,
));
$response = curl_exec($curl);
$err = curl_error($curl);
$responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if($debug){
$headers = curl_getinfo($curl, CURLINFO_HEADER_OUT);
echo "<h5>Request</h5>";
echo "<pre>";
echo $headers;
echo "</pre>";
}
curl_close($curl);
if ($err) {
if($debug){
echo "<h5>Error:" . $responseCode . "</h5>";
echo "<pre>";
echo $err;
echo "</pre>";
}
} else {
if($debug){
echo "<h5>Response:" . $responseCode . "</h5>";
echo "<pre>";
echo $response;
echo "</pre>";
}
}
return array(
"responseCode" => $responseCode,
"response" => $response,
"error" => $err
);
}
Response of this code like this
Canonical to string
GET
?MarketplaceIds=A21TJRUUN4KGV&CreatedAfter=2021-01-15T05:26:31.308992
content-type:application/json
host:sellingpartnerapi-eu.amazon.com
x-amz-date:20210204T060039Z
content-type;host;user-agent;x-amz-access-token;x-amz-date;x-amz-security-token
4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945
String to Sign
AWS4-HMAC-SHA256
20210204T060039Z
20210204/eu-west-1/execute-api/aws4_request
f11a59afb96cf62bbdd17e44405da8c5567178531f839826e89e9b1fcb77a24a
Request
GET /orders/v0/orders?MarketplaceIds=A21TJRUUN4KGV&CreatedAfter=2021-01-15T05:26:31.308992 HTTP/1.1
Host: sellingpartnerapi-eu.amazon.com
Accept: */*
authorization:AWS4-HMAC-SHA256 Credential=xxxxxxxxxxxxxx/20210204/eu-west-1/execute-api/aws4_request, SignedHeaders=content-type;host;user-agent;x-amz-access-token;x-amz-date;x-amz-security-token, Signature=3ddc540c9a1e38ea0466e4d4570a5ea8a1bc7274cfbc2fffd50609c7f379c495
content-length:2
content-type: application/json
user-agent:sellergeni/1.0 (Php=7.2)
x-amz-access-token:Atza|xxxxxxxxxxxxxxxxxxxxxxxxx
x-amz-date: 20210204T060039Z
Response:403
{
"errors": [
{
"message": "The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
The Canonical String for this request should have been
'GET
/orders/v0/orders
CreatedAfter=2021-01-15T05%3A26%3A31.308992&MarketplaceIds=A21TJRUUN4KGV
content-type:application/json
host:sellingpartnerapi-eu.amazon.com
user-agent:sellergeni/1.0 (Php=7.2)
x-amz-access-token:Atza|IwEBII0yZlQvoo95puL9xxxxxxxxxxxxxxxxxx
x-amz-date:20210204T060039Z
x-amz-security-token:
content-type;host;user-agent;x-amz-access-token;x-amz-date;x-amz-security-token
4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945'
The String-to-Sign should have been
'AWS4-HMAC-SHA256
20210204T060039Z
20210204/eu-west-1/execute-api/aws4_request
e995c02098c1a2d5d775380f1fc49804b32af9534b5e330145ca125fe098f0af'
",
"code": "InvalidSignature"
}
]
}
Run:
sign pathparam/resource
Replace:
/messaging/v1/orders/{orderId}
with:
/messaging/v1/orders/xxx-xxxxxxx-xxxxxxx

Get post count from instagram api

I am trying to get the post count of an instagram account, I have managed to do followers and following but cant get to get the post count right.
<?php
$username = 'instagram';
$response = #file_get_contents( "https://www.instagram.com/$username/?__a=1" );
if ( $response !== false ) {
$data = json_decode( $response, true );
if ( $data !== null ) {
$full_name = $data['graphql']['user']['full_name'];
$follower = $data['graphql']['user']['edge_followed_by']['count'];
$follows = $data['graphql']['user']['edge_follow']['count'];
echo "<p>{$full_name}</p> <p>{$follower} followers {$follows} following.</p>";
}
} else {
echo 'Username not found.';
}
?>
If anyone ever needs the answer, I managed to pull it through...
<?php
$username = 'instagram';
$response = #file_get_contents( "https://www.instagram.com/$username/?__a=1" );
if ( $response !== false ) {
$data = json_decode( $response, true );
if ( $data !== null ) {
$full_name = $data['graphql']['user']['full_name'];
$follower = $data['graphql']['user']['edge_followed_by']['count'];
$follows = $data['graphql']['user']['edge_follow']['count'];
$posts = $data['graphql']['user']['edge_owner_to_timeline_media']['count'];
echo "<h2><a href='https://www.instagram.com/{$username}'>{$full_name}</a></h2>
<p><span>{$posts} posts</span> <span>{$follower} followers</span> <span>{$follows} following</span></p>";
}
} else {
echo 'Username not found.';
}
?>
You can get many options by just going to
https://www.instagram.com/$username/?__a=1
and changing the $username to the account you need to see

Setting a target temperature throwing an error in Nest thermostat

Setting target temperature throwing an error like below. I am using php curl to set the temperature. Any help is appreciated.
object(stdClass)#72 (2) {
["cmd"]=>
string(12) "REINIT_STATE"
["pod"]=>
string(5) "rts04"
}
Code:
echo "Setting target temperature...\n";
$success = $nest->setTargetTemperature(150,$device_serial_number);
var_dump($success);
//***********************//
public function setTargetTemperature($temperature, $serial_number) {
$serial_number = $this->getDefaultSerial($serial_number);
$temperature = $this->temperatureInCelsius($temperature, $serial_number);
echo $temperature;
$data = json_encode(array('target_change_pending' => TRUE, 'target_temperature' => $temperature));
return $this->doPOST("/v2/put/shared." . $serial_number, $data);
}
//************//
private function doPOST($url, $data_fields) {
return $this->doRequest('POST', $url, $data_fields);
}
private function doRequest($method, $url, $data_fields, $with_retry=TRUE) {
$ch = curl_init();
if ($url[0] == '/') {
$url = $this->transport_url . $url;
}
$headers = array('X-nl-protocol-version: ' . self::protocol_version);
if (isset($this->userid)) {
$headers[] = 'X-nl-user-id: ' . $this->userid;
$headers[] = 'Authorization: Basic ' . $this->access_token;
}
if (is_array($data_fields)) {
$data = array();
foreach($data_fields as $k => $v) {
$data[] = "$k=" . urlencode($v);
}
$data = implode('&', $data);
} else if (is_string($data_fields)) {
$data = $data_fields;
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, self::user_agent);
curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookie_file);
curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookie_file);
if ($method == 'POST') {
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$headers[] = 'Content-length: ' . strlen($data);
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
if (DEBUG) {
curl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:8888');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
} else {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE); // for security this should always be set to true.
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // for security this should always be set to 2.
curl_setopt($ch, CURLOPT_SSLVERSION, 1); // Nest servers now require TLSv1; won't work with SSLv2 or even SSLv3!
// Update cacert.pem (valid CA certificates list) from the cURL website once a month
$curl_cainfo = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'cacert.pem';
$last_month = time()-30*24*60*60;
if (!file_exists($curl_cainfo) || filemtime($curl_cainfo) < $last_month || filesize($curl_cainfo) < 100000) {
file_put_contents($curl_cainfo, file_get_contents('http://curl.haxx.se/ca/cacert.pem'));
}
if (file_exists($curl_cainfo) && filesize($curl_cainfo) > 100000) {
curl_setopt($ch, CURLOPT_CAINFO, $curl_cainfo);
}
}
$response = curl_exec($ch);
$info = curl_getinfo($ch);
if ($info['http_code'] == 401 || (!$response && curl_errno($ch) != 0)) {
if ($with_retry && $this->use_cache()) {
// Received 401, and was using cached data; let's try to re-login and retry.
#unlink($this->cookie_file);
#unlink($this->cache_file);
if ($info['http_code'] == 401) {
$this->login();
}
return $this->doRequest($method, $url, $data_fields, !$with_retry);
} else {
throw new RuntimeException("Error: HTTP request to $url returned an error: " . curl_error($ch), curl_errno($ch));
}
}
$json = json_decode($response);
if (!is_object($json) && ($method == 'GET' || $url == self::login_url)) {
if (strpos($response, "currently performing maintenance on your Nest account") !== FALSE) {
throw new RuntimeException("Error: Account is under maintenance; API temporarily unavailable.", NESTAPI_ERROR_UNDER_MAINTENANCE);
}
if (empty($response)) {
throw new RuntimeException("Error: Received empty response from request to $url.", NESTAPI_ERROR_EMPTY_RESPONSE);
}
throw new RuntimeException("Error: Response from request to $url is not valid JSON data. Response: " . str_replace(array("\n","\r"), '', $response), NESTAPI_ERROR_NOT_JSON_RESPONSE);
}
if ($info['http_code'] == 400) {
if (!is_object($json)) {
throw new RuntimeException("Error: HTTP 400 from request to $url. Response: " . str_replace(array("\n","\r"), '', $response), NESTAPI_ERROR_API_OTHER_ERROR);
}
throw new RuntimeException("Error: HTTP 400 from request to $url. JSON error: $json->error - $json->error_description", NESTAPI_ERROR_API_JSON_ERROR);
}
// No body returned; return a boolean value that confirms a 200 OK was returned.
if ($info['download_content_length'] == 0) {
return $info['http_code'] == 200;
}
return $json;
}
doPOST function called from setTargetTemperature. doRequest function called from doPOST.
For more reference see here https://github.com/gboudreau/nest-api
the easy things are:
Make sure the thermostat is in heat/cool mode, or cool mode.
Make sure the thermostat is not set to away.
Can you post the code block you are using to make the call?

Paypal Success transation return values empty-- sometimes

There is a problem with my paypal Integration in live site.
For 90% of transactions, I didn't get any problem. Some times only I am facing this below problem.
Problem: After successful transaction, I am not getting Pay pal values like Transaction Id, Message etc. All values shows empty. It comes for 10% of transactions only. please tell me what may be the problem. Can't able to find out the reason
Thanks in Advance..
$paypal_email = '5345345345345f';
$cur_dir='http://'.$_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']);
$return_url = $cur_dir.'/paymentsucess.php';
$cancel_url = $cur_dir.'/payment-not-sucess.php';
$notify_url = $cur_dir.'/payments.php';
extract($_POST);
$item_name = $exam_name;
$item_amount = $amount;
$userid=$userid;
if (!isset($_POST["txn_id"]) && !isset($_POST["txn_type"])){
$querystring = "?business=".urlencode($paypal_email)."&";
$querystring .= "item_name=".urlencode($item_name)."&";
$querystring .= "amount=".urlencode($item_amount)."&";
//loop for posted values and append to querystring
foreach($_POST as $key => $value){
$value = urlencode(stripslashes($value));
$querystring .= "$key=$value&";
}
$querystring .= "return=".urlencode(stripslashes($return_url))."&";
$querystring .= "cancel_return=".urlencode(stripslashes($cancel_url))."&";
$querystring .= "notify_url=".urlencode($notify_url);
header('location:https://www.paypal.com/cgi-bin/webscr'.$querystring);
exit();
}else{
$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$value = preg_replace('/(.*[^%^0^D])(%0A) (.*)/i','${1}%0D%0A${3}',$value);// IPN fix
$req .= "&$key=$value";
}
$data['item_name'] = $_POST['item_name'];
$data['item_number'] = $_POST['item_number'];
$data['payment_status'] = $_POST['payment_status'];
$data['payment_amount'] = $_POST['mc_gross'];
$data['payment_currency'] = $_POST['mc_currency'];
$data['txn_id'] = $_POST['txn_id'];
$data['receiver_email'] = $_POST['receiver_email'];
$data['payer_email'] = $_POST['payer_email'];
$data['custom'] = $_POST['custom'];
$data['userid'] = $_POST['userid'];
// post back to PayPal system to validate
$header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);
if (!$fp) {
// HTTP ERROR
} else {
fputs ($fp, $header . $req);
while (!feof($fp)) {
$res = fgets ($fp, 1024);
if (strcmp ($res, "VERIFIED") == 0) {
// Validate payment (Check unique txnid & correct price)
$valid_txnid = check_txnid($data['txn_id']);
$valid_price = check_price($data['payment_amount'], $data['item_number']);
// PAYMENT VALIDATED & VERIFIED!
if($valid_txnid && $valid_price){
$orderid = updatePayments($data);
if($orderid){
}else{
}
}else{
}
}else if (strcmp ($res, "INVALID") == 0) {
}
}
fclose ($fp);
}
}

Resources