<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Set Custom Field &#8211; Chatbot Dojo</title>
	<atom:link href="https://v3.chatbotdojo.com/topic-category/set-custom-field/feed/" rel="self" type="application/rss+xml" />
	<link>https://v3.chatbotdojo.com</link>
	<description></description>
	<lastBuildDate>Thu, 14 Jan 2021 15:04:23 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.8.2</generator>

<image>
	<url>https://v3.chatbotdojo.com/wp-content/uploads/2020/07/favicon-56x56.png</url>
	<title>Set Custom Field &#8211; Chatbot Dojo</title>
	<link>https://v3.chatbotdojo.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to set a custom field with /fb/subscriber/setCustomField</title>
		<link>https://v3.chatbotdojo.com/topic/how-to-set-a-custom-field-with-fb-subscriber-setcustomfield/</link>
		
		<dc:creator><![CDATA[ninjawarrior]]></dc:creator>
		<pubDate>Tue, 12 Jan 2021 12:28:59 +0000</pubDate>
				<guid isPermaLink="false">https://v3.chatbotdojo.com/?post_type=sfwd-topic&#038;p=25471</guid>

					<description><![CDATA[The curl command as displayed on the ManyChat API Swagger is: You need to replace the 0&#8217;s in the command with the appropriate data: ManyChat API key, subscriber ID, field_id, field_value (&#8216;string&#8217;, 123, true, &#8216;2018-07-18&#8217;, &#8216;2018-07-02T00:00:00+00:00&#8217;). I&#8217;ll show you how to use this and what it does below. Why would you need this? Setting a &#8230;<p class="read-more"> <a class="" href="https://v3.chatbotdojo.com/topic/how-to-set-a-custom-field-with-fb-subscriber-setcustomfield/"> <span class="screen-reader-text">How to set a custom field with /fb/subscriber/setCustomField</span> Read More &#187;</a></p>]]></description>
										<content:encoded><![CDATA[
<p>The curl command as displayed on the ManyChat API Swagger is:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">curl -X POST "https://api.manychat.com/fb/subscriber/setCustomField" -H "accept: application/json" -H "Authorization: Bearer 0" -H "Content-Type: application/json" -d "{ \"subscriber_id\": 0, \"field_id\": 0, \"field_value\": \"'string', 123, true, '2018-07-18', '2018-07-02T00:00:00+00:00'\"}"</pre>



<p>You need to replace the 0&#8217;s in the command with the appropriate data: ManyChat API key, subscriber ID, field_id, field_value (&#8216;string&#8217;, 123, true, &#8216;2018-07-18&#8217;, &#8216;2018-07-02T00:00:00+00:00&#8217;). I&#8217;ll show you how to use this and what it does below.</p>



<h2>Why would you need this?</h2>



<p>Setting a custom field has a lot of use cases. Loyalty card points, progression values, user settings etcetera. In our platforms we use it to set Application settings/preferences that we use to create JSON output for our apps&#8217;functionality. Another use case is a shopping cart, you will store the cart contents in a custom field, an item price and more of these values. A custom field is used in every chatbot.</p>



<p>This is the default response on a successful request, is, as always:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{
  "status": "success"
}</pre>



<h2>So how can we show you how to use it?</h2>



<p>We are going to split this up in 2 parts again:<br>1. We create a webpage with a list of all custom fields and their current values, with an option to change it by adding a value in the form field. We don&#8217;t make a difference in string, number, boolean, date or datetime in this section, but you can if you want to in your system; <br>2. We create a PHP file to process the data.</p>



<p>But First, as always, let&#8217;s add a new function to our class file in classes/manychat.class.php.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="1002" data-enlighter-title="" data-enlighter-group="">    /**
     * 
     * @param type $subscriber_id
     * @param type $field_id
     * @param type $field_value
     * @param type $mc_api
     * @return boolean
     */
    function subscriberSetCustomField($subscriber_id, $field_id, $field_value, $mc_api)
    {

        $postfields_arr = [
            'subscriber_id' => $subscriber_id,
            'field_id'      => $field_id,
            'field_value'   => $field_value
        ];

        $postfields = json_encode($postfields_arr);

        $ch            = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://api.manychat.com/fb/subscriber/setCustomField");
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields . PHP_EOL);
        $headers       = [
            'Authorization: Bearer ' . preg_replace("/^(\w+\s+)/", "", $mc_api),
            'Content-Type: application/json',
            'Accept: application/json'
        ];
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $server_output = curl_exec($ch);
        curl_close($ch);

        $json_obj  = json_decode($server_output);
        $good_call = $json_obj->status;

        if ($good_call == "success") {
            return true;
        } else {
            return false;
        }
    }</pre>



<p>After we created the new function, we will create 2 new PHP files:</p>



<ol><li>subscriber_setcustomfield_form.php</li><li>subscriber_setcustomfield.php</li></ol>



<p>The First file is to get the collection for the specific user, each custom field with its own form text input field</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;!DOCTYPE html>
&lt;html>
    &lt;head>
        &lt;title>Set Custom Field HTML Sample Page&lt;/title>
        &lt;meta charset="UTF-8">
        &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
        &lt;!--Bootstrap CSS--> 
        &lt;link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    &lt;/head>
    &lt;body style="padding:50px;max-width:600px;">

        &lt;?php
        /*
         * Load the ManyChat Config File
         */
        require_once './config.inc.php';

        /*
         * Create Page and Form
         */

        $subscriber_id   = "1929189923777499";
        $subscriber_info = $mc->getSubscriberInfo($subscriber_id, $mc_api);
        $subscriber_cufs = $subscriber_info->custom_fields;

        ?>

        &lt;p style="margin:50px 0;">Let's get all Custom Fields and assign a value to it manually. When you press the button, your custom field value for the subscriber will be updated.&lt;/p>

        &lt;form method="post" action="subscriber_setcustomfield.php" id="setCustomField">
            &lt;div class="form-group">
                &lt;label for="mc_uid">ManyChat User ID&lt;/label>                
                &lt;input type="text" class="form-control" value="&lt;?= $subscriber_id ?: "Enter a valid userId in your Code First" ?>" id="mc_uid" name="mc_uid" />
            &lt;/div>

            &lt;?php
            foreach ($subscriber_cufs AS $cuf) {
                ?>
                &lt;div class="form-group">
                    &lt;label for="mc_uid">&lt;strong>&lt;?= $cuf->name ?>&lt;/strong>&lt;/label>                
                    &lt;input type="text" class="form-control" value="" id="" name="&lt;?= $cuf->id ?>" />
                    &lt;em>Current value: &lt;?= $cuf->value ?>&lt;/em>
                &lt;/div> 
            &lt;?php } ?>

            &lt;button type="submit" class="btn btn-primary">Set Custom Field Value&lt;/button>
        &lt;/form>

        &lt;!-- Optional JavaScript -->
        &lt;!-- jQuery first, Bootstrap JS -->
        &lt;script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous">&lt;/script>
        &lt;script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous">&lt;/script>
    &lt;/body>
&lt;/html>
</pre>



<p>If you run this page in your browser, you&#8217;ll see something similar to this:</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="539" height="898" src="https://v3.chatbotdojo.com/wp-content/uploads/2021/01/image-4.png" alt="" class="wp-image-25475" srcset="https://v3.chatbotdojo.com/wp-content/uploads/2021/01/image-4.png 539w, https://v3.chatbotdojo.com/wp-content/uploads/2021/01/image-4-180x300.png 180w" sizes="(max-width: 539px) 100vw, 539px" /></figure>



<p>It&#8217;s a large list with all custom fields set to your current user ID. In the &#8220;real&#8221; world, you&#8217;d of course get this user ID from your own system instead of hard-coding it in the source code.</p>



<p>To change a custom field, just enter the new value in the form field and submit it by using the button. On the next page, you will get a confirmation of the changes custom user field.</p>



<p>The PHP script we use for processing the data, is as follows:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;?php

/*
 * Load the ManyChat Config File
 */
require_once './config.inc.php';

/*
 * Set a Custom Field Value to a Subscriber 
 */

$clean_data    = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
$subscriber_id = $clean_data['mc_uid'] ?: exit("No subscriber found");
$i             = 0;

foreach ($clean_data AS $customfield_id => $customfieldvalue) {
    if (!empty($customfieldvalue) &amp;&amp; $customfield_id !== "mc_uid") {
        echo "$customfield_id = $customfieldvalue &lt;br />";
        $subscriber_setcustomfield = $mc->subscriberSetCustomField($subscriber_id, $customfield_id, $customfieldvalue, $mc_api);
        if ($subscriber_setcustomfield) {
            $i++;
        }
    }
}

if ($i == 1) {
    echo "$i custom field has been updated";
} elseif ($i > 1) {
    echo "$i custom fields have been updated";
} else {
    echo "No fields have been changed";
}
</pre>



<p><code>$subscriber_setcustomfield</code> will return TRUE for a correct response, which we will use to increase $i for each successful change.</p>



<p>Let&#8217;s give it a go. Here&#8217;s what we edit:</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="552" height="296" src="https://v3.chatbotdojo.com/wp-content/uploads/2021/01/image-5.png" alt="" class="wp-image-25476" srcset="https://v3.chatbotdojo.com/wp-content/uploads/2021/01/image-5.png 552w, https://v3.chatbotdojo.com/wp-content/uploads/2021/01/image-5-300x161.png 300w, https://v3.chatbotdojo.com/wp-content/uploads/2021/01/image-5-400x214.png 400w" sizes="(max-width: 552px) 100vw, 552px" /></figure>



<p>Once we clicked the button, we will get the following result:</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="264" height="68" src="https://v3.chatbotdojo.com/wp-content/uploads/2021/01/image-6.png" alt="" class="wp-image-25477"/></figure>



<p>If you have tried to actually integrate this into your system now, you may have noticed a little caveat. Want to guess what?</p>



<p>I&#8217;ll tell you: what if you want to assign a value to a custom user field that has NOT been set earlier? It is not in this current list, since we only retrieve current custom fields that are already set and can be edited.</p>



<p>It is a great practice for you to learn the API system. Here&#8217;s how you can do it, go ahead and try!</p>



<ul><li>get a list of all custom fields in your bot</li><li>get your user Id</li><li>match all existing user fields and show the values</li><li>create a list of new fields that can still be assigned, you could cross reference them, or use arrays to intersect</li></ul>



<p>There are plenty of ways to do this though. Go crazy! <img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p>If you have questions, please let me know.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
