POST REQUEST for creating an Envelope in DocuSign - wordpress

This is all I have for now. I am using jQuery.
Also I get this error: PARTNER_AUTHENTICATION_FAILED
jQuery(document).ready(function($){
// console.log('DocuSign Script Loaded!');
var accountId = '404569';
// on button click
$('#upload_submit').click(function(){
// form inputs
// document, emailSubject, status, recipients
var name = $('#upload_name').val();
var email = $('#upload_email').val();
$.post("https://na2.docusign.net/restapi/v2/accounts/" + accountId + "/envelopes", {
},
function (data) {
console.log(data);
});
});
});

Your example code is not providing authentication credentials.

<?php
// Set Authentication information
$email = '';
$password = '';
$integratorKey = '';
function get_url( $email, $password, $integratorKey ) {
// api service point
$url = "https://demo.docusign.net/restapi/v2/login_information";
// construct the authentication header:
$header = "<DocuSignCredentials><Username>" . $email . "</Username><Password>" . $password . "</Password><IntegratorKey>" . $integratorKey . "</IntegratorKey></DocuSignCredentials>";
// STEP 1 - Login (to retrieve baseUrl and accountId)
$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 ) {
return (['ok' => false, 'errMsg' => "Error calling DocuSign, status is: " . $status]);
}
$response = json_decode( $json_response, true );
// Account ID and Base URL for envelopes API
$accountId = $response["loginAccounts"][0]["accountId"];
$baseUrl = $response["loginAccounts"][0]["baseUrl"];
curl_close( $curl );
return $baseUrl;
}
// Base URL Envelope
$baseUrl = get_url( $email, $password, $integratorKey );

Related

Sending an email from WordPress through REST API with an Axios call

I'm using this snippet to send an email from WordPress through the REST API.
My Vue-based front end is posting form data to WordPress using an Axios put() call:
sendEmail () {
const formData = new FormData()
formData.append('contact_name', this.contactName)
formData.append('contact_email', this.contactEmail)
formData.append('contact_message', this.contactMessage)
this.$axios.$put(`${this.baseUrl}/wp-json/contact/v1/send`, formData)
.then((res) => {
this.success = true
})
.catch((err) => {
this.$toast.error(err.response)
})
}
I suppose the code above is correct, and that the issue lies on the WordPress side:
Functions.php:
function sendContactMail(WP_REST_Request $request) {
$response = array(
'status' => 304,
'message' => 'There was an error sending the form.'
);
$parameters = $request->get_json_params();
if (count($_POST) > 0) {
$parameters = $_POST;
}
$siteName = wp_strip_all_tags(trim(get_option('blogname')));
$contactName = wp_strip_all_tags(trim($parameters['contact_name']));
$contactEmail = wp_strip_all_tags(trim($parameters['contact_email']));
$contactMessage = wp_strip_all_tags(trim($parameters['contact_message']));
if (!empty($contactName) && !empty($contactEmail) && !empty($contactMessage)) {
$subject = "(New message sent from site $siteName) $contactName <$contactEmail>";
$body = "<h3>$subject</h3><br/>";
$body .= "<p><b>Name:</b> $contactName</p>";
$body .= "<p><b>Email:</b> $contactEmail</p>";
$body .= "<p><b>Message:</b> $contactMessage</p>";
if (send_email($contactEmail, $contactName, $body)) {
$response['status'] = 200;
$response['message'] = 'Form sent successfully.';
}
}
return json_decode(json_encode($response));
exit();
}
add_action('rest_api_init', function () {
register_rest_route( 'contact/v1', '/send', array(
'methods' => 'POST',
'callback' => 'sendContactMail'
));
});
However, I have no idea how to troubleshoot the issue, because whichever problem is occuring here doesn't produce any input that I can see (I don't have access to server PHP log unfortunately).
Any idea about what's wrong in my code or how I could troubleshoot it?
Just in case below is the code of the send_email() function as well:
function send_email($form_email, $form_name, $form_message) {
$email_subject = 'Message from '. get_bloginfo('name') . ' - ' . $form_email;
$headers = "From: '" . $form_name . "' <" . $form_email . "> \r\n";
$headers .= "Reply-To: ". strip_tags($form_email) . "\r\n";
$headers .= "Content-Type:text/html;charset=utf-8";
$email_message = '<html><body>';
$email_message .= "<table>";
$email_message .= "<tr><td>NAME: </td><td>" . $form_name . "</td></tr>";
$email_message .= "<tr><td>MESSAGE: </td><td>" . $form_message . "</td></tr>";
$email_message .= "</table>";
$email_message .= "</body></html>";
$email_message = nl2br($email_message);
wp_mail('me#gmail.com', $email_subject, $email_message, $headers);
}
the problem was in your axios put request. your form was not submitted correctly to the server due to missing header:
this.$axios.$put(`${this.baseUrl}/wp-json/contact/v1/send`, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then((res) => {
this.success = true
})
.catch((err) => {
this.$toast.error(err.response)
})
i debugged it via more parameters in your wordpress function request response. i saw that all the form parameters where missing, so i investigated on that end and viola: its working now.

Integrate Salesforce and AdWords Conversion Tracking into wpcf7

i'm tracking AdWords Conversion through a WPCF7. Since on_sent_ok doesen't work anymore, I found a workaround:
// Contact Conversion-Tracker
function mycustom_wp_footer() {
?>
<script type="text/javascript">
document.addEventListener( 'wpcf7mailsent', function( event ) {
location = 'example.com./thank-you/';
}, false );
</script>
<?php
}
Now there is a function in my functions.php where I send requests via the wpcf7 to salesforce:
// Lead 2 Salesforce
add_action( 'wpcf7_before_send_mail', 'editData' );
function editData( $cf7 ) {
$submission = WPCF7_Submission::get_instance();
if ( $submission ) {
$posted_data = $submission->get_posted_data();
$first_name = $posted_data["Vorname"];
$last_name = $posted_data["Nachname"];
$Tel = $posted_data["Tel"];
$mobile = $posted_data["mobile"];
$email = $posted_data["email"];
$message = $posted_data["message"];
$post_items[] = 'oid=00000000000';
$post_items[] = 'first_name=' . $first_name;
$post_items[] = 'last_name=' . $last_name;
$post_items[] = 'email=' . $email;
$post_items[] = 'phone=' . $Tel;
$post_items[] = 'mobile=' . $mobile;
$post_items[] = 'description=' . $message;
$post_items[] = 'lead_source=Contact form';
$post_items[] = 'company=not there';
$post_items[] = 'Anliegen__c=​Contact';
$post_items[] = 'Work together';
$post_string = implode ('&', $post_items);
// Create a new cURL resource
$ch = curl_init();
if (curl_error($ch) != "")
{
// error handling
}
$con_url = 'salesforce.com/servlet/servlet.WebToLead?
encoding=UTF-8';
curl_setopt($ch, CURLOPT_URL, $con_url);
// Set the method to POST
curl_setopt($ch, CURLOPT_POST, 1);
// Pass POST data
curl_setopt( $ch, CURLOPT_POSTFIELDS, $post_string);
curl_exec($ch); // Post to Salesforce
curl_close($ch); // close cURL resource
}}
// End Lead 2 Salesforce
Now these two functins seem to not work together properly. Since I added the first function where the redirect happens, no new leads will be added to my Salesforce.
Thank you in advance.

How avoid form resubmission on page refresh?

I'm doing a simple feedback form on WordPress. And like many people, I encountered the problem of resending the form when refresh the browser page. I know that this problem is solved through the use of the pattern "Post/Redirect/Get". Which says that you need after processing the data $_POST, request the same page using the $_GET method. But I can not use the result of the wp_mail function for redirection.
if(wp_mail($email, $email_subject, $email_message, $headers)) {
add_action('send_headers', 'simplemail_add_header');
}
function simplemail_add_header() {
header("Location: http://google.com");
}
It just does not work.
UPD
Here is my full code:
class SimpleMailer {
private $nonce = 'feedback_nonce';
public function __construct() {
add_action('phpmailer_init', array($this, 'simplemail_smtp_config'));
add_shortcode('simplemail', array($this, 'simplemail_sendmail'));
}
public function simplemail_smtp_config($phpmailer) {
$phpmailer->isSMTP();
$phpmailer->SetFrom("admin#mail.com");
$phpmailer->addAddress("sender#mail.com");
$phpmailer->Host = "ssl://smtp.mail.com";
$phpmailer->SMTPAuth = true;
$phpmailer->Port = 465;
$phpmailer->Username = "admin#mail.com";
$phpmailer->Password = "password";
$phpmailer->SMTPSecure = 'ssl';
}
public function simplemail_sendmail($shortcode_attributes) {
global $wp;
$result = "";
$error = false;
$data = array();
$required_fields = array("feedback_name", "feedback_email", "feedback_message");
$atts = shortcode_atts(array(
"email" => get_bloginfo('admin_email'),
"form_action" => home_url($wp->request),
"form_cls" => '',
"mail_subject" => "Feedback message from",
"pls_name" => 'Your Name',
"pls_email" => 'Your E-mail Address',
"pls_message" => 'Your Message',
"label_submit" => 'Submit',
"error_common" => 'There was some mistake. Try again, a little later.',
"error_empty" => 'Please fill in all the required fields.',
"error_noemail" => 'Please enter a valid e-mail address.',
"success" => 'Thanks for your e-mail! We\'ll get back to you as soon as we can.'
), $shortcode_attributes);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
foreach ($_POST as $field => $value) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$data[$field] = trim(strip_tags($value));
}
foreach ($required_fields as $required_field) {
$value = trim($data[$required_field]);
if(empty($value)) {
$error = true;
$result = $atts['error_empty'];
}
}
if(!empty($data["feedback_blank"])) {
$error = true;
$result = $atts['error_empty'];
}
if(!is_email($data['feedback_email'])) {
$error = true;
$result = $atts['error_noemail'];
}
if(!wp_verify_nonce($data[$this->nonce],'simplemail_nonce')) {
$error = true;
$result = $atts['error_common'];
}
if ($error == false) {
$email_subject = $atts['mail_subject']." [".get_bloginfo('name')."]";
$email_message = $data['feedback_message']."\n\n";
$headers = "From: ".$data['feedback_name']." <".$data['feedback_email'].">\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
if(wp_mail(null, $email_subject, $email_message, $headers)) {
add_action('send_headers', array($this, 'simplemail_add_header', 10, $atts['form_action']));
// wp_redirect( 'http://google.com', 301 );
// exit;
}
$data = array();
$result = $atts['success'];
}
}
return $this->simplemail_draw_form($atts, $data, $result);
}
public function simplemail_draw_form($atts, $data, $result) {
$output = "<form action='".$atts['form_action']."' class='".$atts['form_cls']."' method='post'>".PHP_EOL.
"<input type='text' name='feedback_name' placeholder='".$atts['pls_name']."' value='".#$data['feedback_name']."'>".PHP_EOL.
"<input type='text' name='feedback_blank'>".PHP_EOL.
"<input type='email' name='feedback_email' placeholder='".$atts['pls_email']."' value='".#$data['feedback_email']."'>".PHP_EOL.
"<textarea name='feedback_message' cols='30' rows='10' placeholder='".$atts['pls_message']."'>".#$data['feedback_message']."</textarea>".PHP_EOL;
$output .= wp_nonce_field('simplemail_nonce', $this->nonce, false);
$output .= ($result != "") ? '<div class="feedback-info">'.$result.'</div>' : '<div class="feedback-info"></div>';
$output .= "<button type='submit'>".$atts['label_submit']."</button>".PHP_EOL."</form>";
return $output;
}
public function simplemail_add_header($location) {
header("Location: {$location}");
}
}
$simplemailer = new SimpleMailer();
And I get this error if I uncomment the redirect. And nothing at all, if you try to use simplemail_add_header
Warning: Cannot modify header information - headers already sent by (output started at /var/www/vhosts/12/151953/webspace/httpdocs/skgk.kz/wp-includes/nav-menu-template.php:256) in /var/www/vhosts/12/151953/webspace/httpdocs/skgk.kz/wp-includes/pluggable.php on line 1216
I think you need to add a token in a hidden textbox and within the form to be submitted, the text in this text box will be the token and it need to change on every page load. Save this token in a session variable. Then add a condition at the top of the page to validate the token, if the token is different kill the loading process or display a message or whatever you feel is needed. You may also add token longevity to allow submitting of a page within certain amount of time.
The token creation, token validation and token longevity are normally a function somewhere that is called as needed and form different pages.
Edit:
If all you want is redirect the user to a different page then do:
if(mail succeed) {
header('location: thankyou.html');
}

Woocommerce CRM connect

I'm trying to connect my Woocommerce to a CRM. They gave me this example code.
My question:
In what file do i need to add this code in Woocommerce.
class SimplicateApi {
public $authentication_key;
public $authentication_secret;
public $api_url;
public function __construct($domain, $key, $secret){
$this->authentication_key = $key;
$this->authentication_secret = $secret;
$this->api_url = 'https://'.$domain.'/api/v2';
}
public function makeApiCall($method, $url, $payload = NULL) {
// Generate the list of headers to always send.
$headers = array(
"User-Agent: simplicate-koppeling",// Sending a User-Agent header is a best practice.
"Authentication-Key: ".$this->authentication_key,
"Authentication-Secret: ".$this->authentication_secret,
"Accept: application/json", // Always accept JSON response.
);
$endpoint = $this->api_url . $url;
$curl = curl_init($endpoint);
switch(strtoupper($method)) {
case "GET":
// Nothing to do, GET is the default and needs no
// extra headers.
break;
case "POST":
// Add a Content-Type header (IMPORTANT!)
$headers[] = "Content-Type: application/json";
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
break;
case "PATCH":
// Add a Content-Type header (IMPORTANT!)
$headers[] = "Content-Type: application/json";
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH");
curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
break;
case "DELETE":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
break;
default:
exit;
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if (self::isFailure($httpCode)) {
return array('errorNumber' => $httpCode,
'error' => 'Request returned HTTP error '.$httpCode,
'request_url' => $url);
}
$curl_errno = curl_errno($curl);
$curl_err = curl_error($curl);
if ($curl_errno) {
$msg = $curl_errno.": ".$curl_err;
curl_close($curl);
return array('errorNumber' => $curl_errno,
'error' => $msg);
}
else {
error_log("Response: ".$response);
curl_close($curl);
return json_decode($response, true);
}
}
public static function isFailure($httpStatus){
// Simplistic check for failure HTTP status
return ($httpStatus >= 400);
}
}
$SimplicateApi = new SimplicateApi('yourdomain.simplicate.nl','yourapikey','yourapisecret');
// pepare the payload to create an organization
$org_payload = array(
'name' => $variable_with_organization_name,
'phone' => $variable_with_organization_phone,
'email' => $variable_with_organization_email,
'note' => $variable_with_note,
'relation_type' => array(
'id'=>'' //provide the relationtypeid, f.e. relationtype:796ce0d318a2f5db515efc18bba82b90
),
'visiting_address' => array(
'country_code' => 'NL'
), // can be extented with other address data
'postal_address' => array(
'country_code' => 'NL'
) // can be extented with other address data
);
// add the organization to the CRM
$organization = $SimplicateApi->makeApiCall('POST','/crm/organization',json_encode($org_payload));
And nother question.
How about this part:
// pepare the payload to create an organization
$org_payload = array(
'name' => $variable_with_organization_name,
'phone' => $variable_with_organization_phone,
'email' => $variable_with_organization_email,
'note' => $variable_with_note,
Where do i get these variables from woocommerce?
you need Add custom api route
first technique :
inside woocommerce-ac.php add :
add_action('woocommerce_api_loaded', 'wpc_register_wp_api_endpoints');
function wpc_register_wp_api_endpoints() {
include_once( 'woo-includes/api/v2/class-wc-api-carts.php' );
add_filter('woocommerce_api_classes', 'filter_woocommerce_api_classes', 10, 1);
}
function filter_woocommerce_api_classes($array) {
$cart = array(
'WC_API_Carts',
);
return array_merge($array, $cart);
}
and inside woo-includes/api/v2 add class-wc-api-customs.php; that is done
full details

Wordpress XML-RPC and featured images

I'm currently developing a plugin for a client that takes an xml feed hourly and posts it into wordpress and I'm having trouble sending the featured image to the post.
I can post to wordpress fine but all my attempts to post the featured image have failed.
<?php
class XMLRPClientWordPress
{
var $XMLRPCURL = "";
var $UserName = "";
var $PassWord = "";
// Constructor
public function __construct($xmlrpcurl, $username, $password)
{
$this->XMLRPCURL = $xmlrpcurl;
$this->UserName = $username;
$this->PassWord = $password;
}
function send_request($requestname, $params)
{
$request = xmlrpc_encode_request($requestname, $params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_URL, $this->XMLRPCURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
$results = curl_exec($ch);
curl_close($ch);
return $results;
}
public function create_post( $title, $body )
{
$title = htmlentities( $title, ENT_NOQUOTES, 'UTF-8' );
$content = array(
'post_category' => array( 18 ), // my category id
'post_type' => 'post',
'post_title' => $title,
'post_content' => $body,
'featured_image_url' => 'http://www.geekologie.com/2009/02/18/scary%20clown.jpg',
);
$params = array( 0, $this->UserName, $this->PassWord, $content );
return $this->send_request( 'wp.newPost', $params );
}
}
$objXMLRPClientWordPress = new XMLRPClientWordPress("xxxx/xmlrpc.php" , "xxxxx" , "xxxx");
$objXMLRPClientWordPress->create_post('Hey Chloe','Hope you like the clown');
?>
Is what i currently have, i've been reading the wordpress patch tickets on this issue but can't seem to figure out how to actually use the new features
Thanks
It should be something like this
'wp_post_thumbnail' => $pictureid
You have to get the ID of uploaded picture into variable and then assign it as a value of 'wp_post_thumbnail' parameter for 'metaWeblog.newPost'

Resources