Group list addition in php api of docusign - docusignapi

I am not able to add grouplist in rest api by php code
<?php
// Input your info here:
$email = "********* "; // your account email
$password = "*****"; // your account password
$integratorKey = "********"; // your account integrator key, found on (Preferences -> API page)
$accountID = "********** ";
$debug = $_POST["debug"];
$debug = $_POST["debug"];
// construct the authentication header:
$header = "<DocuSignCredentials><Username>" . $email . "</Username><Password>" . $password . "</Password><IntegratorKey>" . $integratorKey . "</IntegratorKey></DocuSignCredentials>";
/////////////////////////////////////////////////////////////////////////////////////////////////
// STEP 1 - Login (to retrieve 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_SSL_VERIFYPEER, 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 logon 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
if ($debug){
echo "<BR>accountId = " . $accountId . "<BR>baseUrl = " . $baseUrl . "<BR>";
}
/////////////////////////////////////////////////////////////////////////////////////////////////
// STEP 2 - status retrieval using filters
/////////////////////////////////////////////////////////////////////////////////////////////////
echo "<BR>Sending new user update...<BR>";
$curl = curl_init($baseUrl . "/users");
if ($debug){
echo "URL is: " . $baseUrl . "/users" . "<BR>";
echo "Title: " . $_POST["title"]."<BR>";
echo "First Name: " . $_POST["firstName"]."<BR>";
echo "Middle Name: " .$_POST["middleName"]."<BR>";
echo "Last Name: " . $_POST["lastName"]."<BR>";
echo "User Name: " .$_POST["userName"]."<BR>";
echo "Password :" . $_POST["password"]."<BR>";
echo "Email: " .$_POST["email"]."<BR>";
echo "Check box:".$_POST['check_list']."<BR>";
}
$data = array("newUsers" => array
(
array
(
"lastName" => $_POST["lastName"],
"firstName" => $_POST["firstName"],
"password" => $_POST["password"],
"userName" => $_POST["userName"],
"email" => $_POST["email"],
"middleName" => $_POST["middleName"],
"title" => $_POST["title"],
"userSettings" => array
(
array
(
"name" => "canSendEnvelope",
"value" => "true"
)
),
"forgottenPasswordInfo" => array
(
"forgottenPasswordQuestion1" => $_POST["forgottenPasswordQuestion1"],
"forgottenPasswordAnswer1" => $_POST["forgottenPasswordAnswer1"]
),
"groupList" => array
(
"groupId" => $_POST["check_list"],
"groupName" => $_POST["check_list"],
"permissionProfileId" => $_POST["check_list"],
"groupType" => $_POST["check_list"]
)
)
)
);
$data_string = json_encode($data);
if ($debug) {
echo "<BR><BR>";
echo $data_string;
echo "<BR><BR>";
}
// build web request
$request_header = array(
'Accept: application/json',
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
"X-DocuSign-Authentication: $header" );
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HTTPHEADER, $request_header);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
//execute web request
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 201 ) {
echo "error calling webservice, status is:" . $status . "<BR>error text is --> ";
print_r($json_response); echo "<BR>";
exit(-1);
}
$response = json_decode($json_response, true);
//--- display results
if ($debug){
echo "Received " . $response . " end<BR>";
}
echo "New user created."
?>

Since groupList is an array property you need to specify each group node separately. The JSON that your PHP code produces should look like this:
"groupList": [
{
"groupId": "sample string 1",
"groupName": "sample string 2",
"permissionProfileId": "sample string 3",
"groupType": "sample string 4"
}
],

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

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

why php mailer not send attachement?

I m using php mailer to send mail with attachment but i don't know why attachment not send
else msg in body send properly and no error show plz give best solution for this
$to = 'ok123#gmail.com';
$msg = "This a body of a mail";
require_once("functions/class.phpmailer.php");
$mailer = new PHPMailer();
$mailer->From = "noreply#gmail.com";
$mailer->Subject = "attachment file";
$mailer->AddAddress($to);
$mailer->ContentType = 'text/html';
$mailer->CharSet = "UTF-8";
$mailer->Body = $msg;
$mailer->IsHTML(true);
$mailer->AddAttachment("images/20130319182911.zip","20130319182911.zip");
$mailer->Send();
echo "Message Sent OK<p></p>\n";
This is my favorite mail attachment class. Use it if you like it.
class AttachmentEmail {
private $from = 'yours#email.com';
private $from_name = 'Your Name';
private $reply_to = 'yours#email.com';
private $to = '';
private $subject = '';
private $message = '';
private $attachment = '';
private $attachment_filename = '';
public function __construct($to, $subject, $message, $attachment = '', $attachment_filename = '') {
$this -> to = $to;
$this -> subject = $subject;
$this -> message = $message;
$this -> attachment = $attachment;
$this -> attachment_filename = $attachment_filename;
}
public function mail() {
if (!empty($this -> attachment)) {
$filename = empty($this -> attachment_filename) ? basename($this -> attachment) : $this -> attachment_filename ;
$path = dirname($this -> attachment);
$mailto = $this -> to;
$from_mail = $this -> from;
$from_name = $this -> from_name;
$replyto = $this -> reply_to;
$subject = $this -> subject;
$message = $this -> message;
$file = $path.'/'.$filename;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$name = basename($file);
$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "Reply-To: ".$replyto."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use diff. tyoes here
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$header .= $content."\r\n\r\n";
$header .= "--".$uid."--";
if (mail($mailto, $subject, "", $header)) {
return true;
} else {
return false;
}
} else {
$header = "From: ".($this -> from_name)." <".($this -> from).">\r\n";
$header .= "Reply-To: ".($this -> reply_to)."\r\n";
if (mail($this -> to, $this -> subject, $this -> message, $header)) {
return true;
} else {
return false;
}
}
}
}
And use it like
$sendit = new AttachmentEmail('test#example.com', 'Testing attachment!', 'Hi', '/home/test/test.jpg');
$sendit -> mail();
Gmail removes .zip attachment when it detects particular files inside, like EXEs. Add zip attachment as 20130319182911.piz and it should arrive.
It's not a phpmailer problem, but a Gmail policy.

Resources