Send JSON data from Python to Telegram using webhook - python

i have a python application that send data to request.log using webhook.php
webhook.php working code :
<?php
$request = file_get_contents('php://input');
$req_dump = print_r( $request, true );
$fp = file_put_contents( 'request.log', $req_dump );
// Updated Answer
if($json = json_decode(file_get_contents("php://input"), true)){
$data = $json;
}
print_r($data);
?>
content in request.log is on json format.
I get results in request.log without issue, but i need to send same details to telegram, here's the not working code :
<?php
$request = file_get_contents('php://input');
$req_dump = print_r( $request, true );
$fp = file_put_contents( 'request.log', $req_dump );
// Updated Answer
if($json = json_decode(file_get_contents("php://input"), true)){
$data = $json;
}
print_r($data);
if($json = json_decode(file_get_contents("php://input"), true)){
$token = "166.....:AAFlfaCuGdkG3MD1hO.......";
$chatid = "-51....";
$message = $data;
function sendMessage($chatid, $message, $token)
{
$url = "https://api.telegram.org/bot" . $token . "/sendMessage?chat_id=" . $chatid;
$url = $url . "&text=" . urlencode($message);
$ch = curl_init();
$optArray = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true
);
curl_setopt_array($ch, $optArray);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
sendMessage($chatid, $message, $token);
}
?>
Can't figure out how to get those data sent to telegram, if it's impossible to send to request.log and to telegram in same time, is there a way to get updated content from request.log and send them to telegram.
Thank you

Related

Sending HTTP request using PHP and trying to receive in python

I am sending an HTTP request using CURL API in PHP and trying to receive the variable custid in python: How do I receive the custid? Below is the PHP code and also the python code. The url in this example is $temp_url = "https://test.com//api/v1/users/all?custid=123";
PHP Send:
function __pull($temp_url)
{
$curl = curl_init();
$username = "##########";
$password = "##########";
$temp_url = "https://test.com//api/v1/users/all?custid=123";
curl_setopt_array($curl, array(
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_URL => "$temp_url",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_USERPWD => "$username:$password",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache"
),));
$this->response = curl_exec($curl);
$this->err = curl_error($curl);
curl_close($curl);
$this->response = json_decode($this->response, true); //because of true, it's in an array
//var_dump($this->response);
//print_r($this->err);
if (empty($this->response)) return FALSE; else return TRUE;
}
Here is the Python Code at the designated URL:
#app.route('/api/v1/users/all', methods=['GET'])
#auth.login_required
def get_users():
# what is the code in python to retrieve the variable custid from this url
# https://test.com//api/v1/users/all?custid=123
print(request['custid'])
return TRUE
To get custid in above example, you should request object like below:
def get_users():
custid = request.args.get('custid')
print(custid)
return 'OK'
Basically, the get() method of the args object returns the value of the custid query parameter as a string (or returns None)

upload a classified listing using rest api in wordpress theme

So i am making a classified website with wordpress and classima theme, i am testing out upload the image with the help of postman. Below is the theme code responsible for api upload to the website and i couldn't figure out which variable to use in my postman body to upload to website using api. I am able to set new listing title, price and everything but for image i can not figure out how to do it. Please see my attached screenshot of postman for what i have tried
$files = $request->get_file_params();
$uploaded_images = [];
if (!empty($files['gallery']['name'])) {
$gallery = $files['gallery'];
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
foreach ($gallery['name'] as $key => $value) {
if ($gallery['name'][$key]) {
$image = array(
'name' => $gallery['name'][$key],
'type' => $gallery['type'][$key],
'tmp_name' => $gallery['tmp_name'][$key],
'error' => $gallery['error'][$key],
'size' => $gallery['size'][$key]
);
Filters::beforeUpload();
$status = wp_handle_upload($image, ['test_form' => false]);
Filters::afterUpload();
if ($status && !isset($status['error'])) {
$filename = $status['file'];
$filetype = wp_check_filetype(basename($filename));
$wp_upload_dir = wp_upload_dir();
$attachment = [
'guid' => $wp_upload_dir['url'] . '/' . basename($filename),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
];
$attach_id = wp_insert_attachment($attachment, $filename, $listing_id);
if (!is_wp_error($attach_id)) {
$uploaded_images[$image['name']] = $attach_id;
wp_update_attachment_metadata($attach_id, wp_generate_attachment_metadata($attach_id, $filename));
}
}
}
}
}
$listing = rtcl()->factory->get_listing($listing_id);

Convert Python code to PHP/Laravel (Gate.io signature)

I am in the process of incorporating the gate,io rest api and am currently trying to convert the signature function from python to php(laravel).
Apparently there is a bug hiding in the conversion.
Can someone take a look and tell me if this is all correct or if something is missing here?
For improvement suggestions I would be grateful
Python code:
def gen_sign(method, url, query_string=None, payload_string=None):
key = '' # api_key
secret = '' # api_secret
t = time.time()
m = hashlib.sha512()
m.update((payload_string or "").encode('utf-8'))
hashed_payload = m.hexdigest()
s = '%s\n%s\n%s\n%s\n%s' % (method, url, query_string or "", hashed_payload, t)
sign = hmac.new(secret.encode('utf-8'), s.encode('utf-8'), hashlib.sha512).hexdigest()
return {'KEY': key, 'Timestamp': str(t), 'SIGN': sign}
Source: Gate.io API Signature string generation
Php Code:
public function createSignature($method, $url, $query=null, $payload=null, $algo = 'sha256'){
$key = 'xxx';
$secret= 'xxx';
$time = microtime(true);
$hashed_payload = hash_hmac($algo,$query ?? '');
$string = "{$methode}\n{$url}\n{$query ?? ''}\n{$hashed_payload}\n{$time}"
$sign = hash_hmac($algo,$string,$secret)
return ['KEY' => $key, 'Timestamp' => "{$time}", 'SIGN' => $sign]
}
i got the answer, i hope it will helps:
public function buildSignHeaders($method, $resourcePath, $queryParams = [], $payload = null)
{
$fullPath = parse_url(config('gate-io.host'), PHP_URL_PATH) . $resourcePath;
$fmt = "%s\n%s\n%s\n%s\n%s";
$timestamp = time();
$hashedPayload = hash("sha512", ($payload !== null) ? $payload : "");
$signatureString = sprintf(
$fmt,
$method,
$fullPath,
GuzzleHttp\Psr7\build_query($queryParams, false),
$hashedPayload,
$timestamp
);
$signature = hash_hmac("sha512", $signatureString, config('gate-io.apiSecretKey'));
return [
"KEY" => config('gate-io.apiKey'),
"SIGN" => $signature,
"Timestamp" => $timestamp
];
}

Create Signature using SHA256 encrypyion with .p12 file in python

Can any one help to do the same code in Python
<?php
$payload = '{"amount":205.16,"currency":"AED","language":"en","merchant_code":"O8Ryrfvy8aUb","merchant_order":"931","redirect_urls":{"cancel":"http://127.0.0.1:8000/api/pointspay-cancel","fail":"http://127.0.0.1:8000/api/pointspay-failed","success":"http://127.0.0.1:8000/api/pointspay-success"},"timestamp":1604722764987,"type":"direct"}';
echo x509_fingerprint($payload, '/home/tmt/Documents/Protect4less/LoyLogic/pointspay_certificate.p12', 'Protect4Less#123', 'sha256') . "\n\n";
function x509_fingerprint($payload, $cert_path, $cert_pass, $algorithm = 'sha256')
{
$algorithm = in_array($algorithm, array(
'sha1',
'md5',
'sha256'
)) ? $algorithm : 'sha1';
// 1. Capture the private key from certificate
if (!$cert_store = file_get_contents($cert_path)) {
echo "Error: Unable to read the cert file\n";
exit;
}
if (openssl_pkcs12_read($cert_store, $cert_info, $cert_pass)) {
} else {
echo "Error: Unable to read the cert store.\n";
exit;
}
$privateKey = $cert_info['pkey'];
print_r($privateKey);
// 2. create message digest
$messageDigest = openssl_digest($payload, $algorithm, true);
// 3. Sign the message digest using private key
openssl_private_encrypt($messageDigest, $encryptedData, $privateKey);
return base64_encode($encryptedData);
}
?>
This is PHP code and I want to do the same steps in PYTHON, can any 1 help me to do so.
I tried many things in python but was not able to do so.
Following is the Python code I tried, but the final signature doesn't match with the PHP signature
from OpenSSL import crypto
import hashlib
from base64 import b64encode
str1 = b'{"amount":205.16,"currency":"AED","language":"en","merchant_code":"O8Ryrfvy8aUb","merchant_order":"931","redirect_urls":{"cancel":"http://127.0.0.1:8000/api/pointspay-cancel","fail":"http://127.0.0.1:8000/api/pointspay-failed","success":"http://127.0.0.1:8000/api/pointspay-success"},"timestamp":1604722764987,"type":"direct"}'
psw = 'Protect4Less#123'
p12 = crypto.load_pkcs12(open("/home/tmt/Documents/Protect4less/LoyLogic/pointspay_certificate.p12", 'rb').read(), psw)
pkey = p12.get_privatekey()
my_hash2 = hashlib.sha256() #Choose SHA256 and update with same bytes
my_hash2.update(str1)
hash_digest = my_hash2.hexdigest()
print("Result after digesting: " + str(my_hash2.hexdigest()))
# data = str1
my_signature = crypto.sign(pkey, str1, 'sha256')
signature_b64 = b64encode(my_signature)
print(signature_b64)

Interacting with suiteCRM API V7.9 with Python requests

I've been trying for a while now to connect to the suiteCRM API using Python's request module but to no avail, the official tutorial uses PHP: https://docs.suitecrm.com/developer/api/api-4_1/
I can't seem to create the Python equivalent of this request, no matter what I get the same response:
<pre>/**
* SugarWebServiceImplv4_1.php
*
* This class is an implementation class for all the web services. Version 4_1 adds limit/off support to the
* get_relationships function. We also added the sync_get_modified_relationships function call from version
* one to facilitate querying for related meetings/calls contacts/users records.
*
*/
Class [ <user> class SugarWebServiceImplv4_1 extends SugarWebServiceImplv4 ] {
- Constants [0] {
}
- Static properties [1] {
Property [ public static $helperObject ]
}
- Static methods [0] {
}
- Properties [0] {
}
- Methods [36] {
/**
* Class Constructor Object
*
*/
Method [ <user, overwrites SugarWebServiceImplv4, ctor> public method __construct ] {
}
/**
* Retrieve a collection of beans that are related to the specified bean and optionally return relationship data for those related beans.
* So in this API you can get contacts info for an account and also return all those contact's email address or an opportunity info also.
*
* #param String $session -- Session ID returned by a previous call to login.
* #param String $module_name -- The name of the module that the primary record is from. This name should be the name the module was developed under (changing a tab name is studio does not affect the name that should be passed into this method)..
* #param String $module_id -- The ID of the bean in the specified module
* #param String $link_field_name -- The name of the lnk field to return records from. This name should be the name the relationship.
* #param String $related_module_query -- A portion of the where clause of the SQL statement to find the related items. The SQL query will already be filtered to only include the beans that are related to the specified bean.
... that continues on, it looks like some documentation.
This is my code:
def get_info():
headers = {
"Content-Type": "application/json"
}
creds = OrderedDict()
creds = {"user_auth": {'user_name':"***", "password": "***"}}
creds = json.dumps(creds)
data = {
'method':'login',
'input_type': 'JSON',
'response_type':'JSON',
'rest_data': creds
}
data = json.dumps(data)
response = requests.post("http://example.com/suitecrm/service/v4_1/rest.php", headers=headers, data=data)
print(response.text)
return response.text
Does anyone have any experience doing this? Thank you
edit: this is the PHP call from their docs:
<?php
$url = "http://example.com/suitecrm/service/v4_1/rest.php";
function restRequest($method, $arguments){
global $url;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$post = array(
"method" => $method,
"input_type" => "JSON",
"response_type" => "JSON",
"rest_data" => json_encode($arguments),
);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
$result = curl_exec($curl);
curl_close($curl);
return json_decode($result,1);
}
$userAuth = array(
'user_name' => 'suitecrmuser',
'password' => md5('suitecrmpassword'),
);
$appName = 'My SuiteCRM REST Client';
$nameValueList = array();
$args = array(
'user_auth' => $userAuth,
'application_name' => $appName,
'name_value_list' => $nameValueList);
$result = restRequest('login',$args);
$sessId = $result['id'];
$entryArgs = array(
//Session id - retrieved from login call
'session' => $sessId,
//Module to get_entry_list for
'module_name' => 'Accounts',
//Filter query - Added to the SQL where clause,
'query' => "accounts.billing_address_city = 'Ohio'",
//Order by - unused
'order_by' => '',
//Start with the first record
'offset' => 0,
//Return the id and name fields
'select_fields' => array('id','name',),
//Link to the "contacts" relationship and retrieve the
//First and last names.
'link_name_to_fields_array' => array(
array(
'name' => 'contacts',
'value' => array(
'first_name',
'last_name',
),
),
),
//Show 10 max results
'max_results' => 10,
//Do not show deleted
'deleted' => 0,
);
$result = restRequest('get_entry_list',$entryArgs);
print_r($result);
Please check this working example, it should help you get started. Its using python3.
import urllib.request
import json
import hashlib
encode = hashlib.md5("MasterPass".encode('utf-8'))
encodedPassword = encode.hexdigest()
args = {'user_auth': {'user_name': 'admin','password': encodedPassword}}
crmUrl="https://yourname.crm.cr/service/v4_1/rest.php"
data = json.dumps(args)
args = {'method': 'login', 'input_type': 'json',
'response_type' : 'json', 'rest_data' : data}
params = urllib.parse.urlencode(args).encode('utf-8')
response = urllib.request.urlopen(crmUrl, params)
response = response.read().strip()
if not response:
print( "error: " , response)
result = json.loads(response.decode('utf-8'))
print (result)

Categories

Resources