<?php
// // accept all post data and make array
$data = json_decode(file_get_contents('php://input'), true);
// // get the data from the array
$deal_name = "test";
// $deal_source = isset($data['deal_source']) ? $data['deal_source'] : "";
$contact_first_name = isset($data['yrnamr']) ? $data['yrname'] : "";
// $contact_last_name = isset($data['contact_last_name']) ? $data['contact_last_name'] : "";
$contact_email = isset($data['yremail']) ? $data['yremail'] : "";
$contact_phone = isset($data['telephone']) ? $data['telephone'] : "";
$contact_message = isset($data['yrmessage']) ? $data['yrmessage'] : "";
$data_string = json_encode(array(
"custom_fields" => array(),
"email" => $contact_email,
"first_name" => $contact_first_name,
"last_name" => "WA",
"is_public" => true,
"phone" => $contact_phone
));
$api_key = "d7c85d208c924e489f36ae69e1550570";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://app.teamwave.com/api/crm/deals?api_key='.$api_key,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>'{
"custom_fields": {
"27806": {
"$key": 27806,
"field_type": "select",
"key": "source",
"name": "Source",
"options": null,
"position": 1,
"value": "test"
}
},
"currency": 1876589,
"pipeline": 29270,
"stage": 155081,
"title": "Deal Name Dynamic Test 4"
}',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
$response = json_decode($response, true);
$deal_id = $response['id'];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://app.teamwave.com/api/crm/deals/'.$deal_id.'/link-contact?api_key='.$api_key,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>$data_string,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;`
I use this code to integrate my contactform7 fields with teamwave crm.The code creates a deal and links it with a contact in the CRM. but the data is not being sent on form submission.
I suspect something is wrong where the contact form 7 fields are dynamically fetched. I am not sure what is wrong...............
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
The following code is very straightforward. However, when I execute it, I always get {"error":"Unsupported Media Type"} from Watson-Conversation service. Please help to show me where the issue comes from.
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_POST => true,
CURLOPT_URL => "https://watson-api-explorer.mybluemix.net/conversation/api/v1/workspaces/70b056e6-14a0-424f-9631-696272ce666e/message?version=2016-09-20",
CURLOPT_USERPWD => "{MYUSERNAME}:{MYPASSWORD}",
CURLOPT_POSTFIELDS => array('message' => '{ "input": { "text": "Hola" }, "alternate_intents": false }'),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => true
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err)
{
echo "cURL Error #:" . $err;
}
else
{
echo $response;
}
Thank you very much.
I have sorted it out already by adding following option into the call:
CURLOPT_HTTPHEADER => array('Content-Type: application/json')
Below is my code to add headers and footers to generate pdf, I don't know here I'm doing it wrong.Please help!
$html = $this->renderView('CoreBundle:PdfGenerator:generate.html.twig', array(
'userId' => $userId,
));
$snappy = $this->get('knp_snappy.pdf');
$snappy->setOption('header-html', $this->container->get('templating.helper.assets')->getUrl('bundles/core/pdfHtml/header.html'));
$snappy->setOption('footer-html', $this->container->get('templating.helper.assets')->getUrl('bundles/core/pdfHtml/footer.html'));
//echo $request->getHost().$this->container->get('templating.helper.assets')->getUrl('bundles/core/pdfHtml/header.html'); die();
echo $html; die();
return new Response(
$snappy->getOutputFromHtml($html),
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="file.pdf"'
)
);
http://www.michaelperrin.fr/2016/02/17/generating-pdf-files-with-symfony/
Follow this, I got my stuff working
$header = $this->renderView('FamilyHealthDischargeSummaryBundle:ExportPdf:header.html.twig');
$body = $this->renderView('FamilyHealthDischargeSummaryBundle:ExportPdf:body.html.twig', $data);
$snappy = $this->get('knp_snappy.pdf');
$snappy->setOption('header-html', $header);
return new Response(
$snappy->getOutputFromHtml($body), 200,
[
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename=' . $file2 . '.pdf',
]
);
}
I'm trying to upload image via Wordpress REST api v2. So far all I managed was to create empty entries in wordpress media library. Meaning they have image names, but no actual image.
POST Request:
http://localhost/wordpress/wp-json/wp/v2/media
Authorization: Basic d29yZHByZXNzOndvcmRwcmVzcw==
Content-Type: application/json
Content-Disposition: attachment;filename=map2.jpg
{
"source_url" : "file:///C:/Users/x/Desktop/map2.jpg"
}
Response:
{
"id": 127,
"date": "2016-05-25T08:43:30",
"date_gmt": "2016-05-25T08:43:30",
"guid": {
"rendered": "http://localhost/wordpress/wp-content/uploads/2016/05/map2-3.jpg",
"raw": "http://localhost/wordpress/wp-content/uploads/2016/05/map2-3.jpg"
},
"modified": "2016-05-25T08:43:30",
"modified_gmt": "2016-05-25T08:43:30",
"password": "",
"slug": "map2-3",
"status": "inherit",
"type": "attachment",
"link": "http://localhost/wordpress/map2-3/",
"title": {
"raw": "map2-3",
"rendered": "map2-3"
},
"author": 1,
"comment_status": "open",
"ping_status": "closed",
"alt_text": "",
"caption": "",
"description": "",
"media_type": "image",
"mime_type": "image/jpeg",
"media_details": {},
"post": null,
"source_url": "http://localhost/wordpress/wp-content/uploads/2016/05/map2-3.jpg",
"_links": {
"self": [
{
"href": "http://localhost/wordpress/wp-json/wp/v2/media/127"
}
],
"collection": [
{
"href": "http://localhost/wordpress/wp-json/wp/v2/media"
}
],
"about": [
{
"href": "http://localhost/wordpress/wp-json/wp/v2/types/attachment"
}
],
"author": [
{
"embeddable": true,
"href": "http://localhost/wordpress/wp-json/wp/v2/users/1"
}
],
"replies": [
{
"embeddable": true,
"href": "http://localhost/wordpress/wp-json/wp/v2/comments?post=127"
}
]
}
}
I get no errors, everything's seem to be working, except response->post and response->media_details is either null or empty. Ofcourse image itself is not uploaded.
Based on this GitHub WP-API Adding Media ticket, I should send 2 requests. First POST request should return data with post object. I would send this post object via PUT method, and image should be uploaded...since I have no post object, this is not possible.
Any ideas what am I doing wrong?
Sideloading images is not supported by the wordpress api so you will have to do some changes.
First, your content-type should be image/jpeg and not application/json, remember that content-type is supposed to reflect the data that you are passing and the POST media request expects an image.
Another change you have to make to accommodate the content-type is the way that you are passing the data. Instead of sending it with the source_url parameter, try passing it as a binary file.
One last thing I would mention is that the wp/v2 calls return 3XX status on a few occasions. It would be useful to follow those redirects and redo those requests to those new urls.
I had some issues passing JPEG images but PNG images have worked well. Here is a curl example that I use to upload png media:
curl --request POST \
--url http://www.yoursite.com/wp-json/wp/v2/media \
--header "cache-control: no-cache" \
--header "content-disposition: attachment; filename=tmp" \
--header "authorization: Basic d29yZHByZXNzOndvcmRwcmVzcw==" \
--header "content-type: image/png" \
--data-binary "#/home/web/tmp.png" \
--location
My working answer using PHP cUrl
<?php
$curl = curl_init();
$data = file_get_contents('C:\test.png');
curl_setopt_array($curl, array(
CURLOPT_URL => "http://woo.dev/wp-json/wp/v2/media",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HTTPHEADER => array(
"authorization: Basic XxxxxxxXxxxxXx=",
"cache-control: no-cache",
"content-disposition: attachment; filename=test.png",
"content-type: image/png",
),
CURLOPT_POSTFIELDS => $data,
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
At january 2020 using wordpress 5.3.2 with nginx the solution that work for me is:
function uploadFile($token, $archivo) {
$file = file_get_contents( $archivo );
$mime = mime_content_type( $archivo );
$url = BASEAPI. 'wp-json/wp/v2/media';
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $file );
curl_setopt($ch, CURLOPT_BINARYTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt( $ch, CURLOPT_HTTPHEADER, [
'Content-Type: '.$mime,
'Content-Disposition: attachment; filename="'.basename($archivo).'"',
'Authorization: Bearer ' .$token,
] );
$result = curl_exec( $ch );
curl_close( $ch );
print_r( json_decode( $result ) );
}
The token is the Authorization JWT token and $archivo is the path to file.
For anyone looking for a JS solution, here's how I made it work using Axios. I will skip authorization implementations, as there are a few options around (oAuth, JWT, Basic).
const fs = require('fs');
const axios = require('axios');
axios({
url: 'http(s)://{your-wp-domain}/wp-json/wp/v2/media',
method: 'POST',
headers: {
'Content-Disposition':'attachment; filename="file.jpg"',
Authorization: {your-authorization-method},
'Content-Type':'image/jpeg'
},
data: fs.readFileSync('path/to/file.jpg', (err, data) => {
if (err) {
console.log(err);
}
});
})
.then(res => {
console.log(res.data);
})
.catch(err => {
console.log(err);
});
Here you can use this code snippet. This works for me using Wordpress API REST
<?php
//Add this to your function.php
function upload_image( $imageID, $login ) {
$request_url = 'https://DOMAINNAME.com/wp-json/wp/v2/media'; //change the domainname
$image_file_path = get_attached_file($imageID); //change this to your file meda path if your not throwing media file to other server
$image = file_get_contents( $image_file_path );
$mime = mime_content_type( $image_file_path );
$api_media_response = wp_remote_post( $request_url, array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( $login ), //login format USERNAME:PASSWORD
'Content-Disposition' => 'attachment; filename='.basename($image_file_path).'',
'Content-Type' => $mime
),
'body' => $image
) );
//this function return wp_remote_post
// more info => https://developer.wordpress.org/reference/functions/wp_remote_post/
}
After trying to get the image upload running with wp_remote_post (donĀ“t wanna use curl for several reasons) i came up with the following working solution:
// Upload image to wordpress media library
$file = #fopen( 'image.jpg', 'r' );
$file_size = filesize( 'image.jpg' );
$file_data = fread( $file, $file_size );
$args = array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( 'USERNAME:PASSWORD' ),
'accept' => 'application/json', // The API returns JSON
'content-type' => 'application/binary', // Set content type to binary
'Content-Disposition' => 'attachment; filename=nameoffileonserver.jpg'
),
'body' => $file_data
);
$api_response = wp_remote_post( 'http://myserver.com/wp-json/wp/v2/media', $args);
if you want to upload a image to WordPress rest API using nuxtjs or vuejs you can use the below code:
in template:
<input style="display: none;" type="file" #change="onFileSelected"
<button #click="onUpload" />
in data:
data() {
return {
selectedFile: null,
previewImage: null
};}
in methods:
onFileSelected(event) {
this.selectedFile = event.target.files[0];
}
onUpload() {
const fd = new FormData();
fd.append("file", this.selectedFile, this.selectedFile.name);
fd.append("title", "pedram");
fd.append("caption", "this is caption");
/* file reader for prview image */
const reader = new FileReader();
reader.readAsDataURL(this.selectedFile);
reader.onload = e =>{
this.previewImage = e.target.result;
};
/* set request header */
const headers = {
'Content-Disposition':`attachment; filename=${this.selectedFile.name}`,
Authorization: "Bearer" + this.$cookiz.get("AdminToken"),
'content-type': 'image'
};
this.$axios.post('/wp-json/wp/v2/media', fd, { headers })
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
});
},
if you want to preview the image you can use file reader and store it in a data variable then use the data instead of image src like bellow code:
<img #click="$refs.fileInput.click()" v-if="previewImage" :src="previewImage" alt="" class="w-100" />
It took me one day to solve the issue I hope the above codes helps