Coded something up in Couch in an interesting way? Have a snippet or shortcode to share? Post it here for the community to benefit.
6 posts Page 1 of 1
Dear Couchers,

Updated October 2021 :)

The <cms:curl /> tag can be used to make form-url or json encoded HTTP requests (including GET, POST, PUT, PATCH, and DELETE) via PHP's cURL implementation. We can use this to make HTTP requests and store the response in a defined Couch variable, which comes in handy when working with third-party APIs.

Parameters:
    - headers = HTTP headers (ex: "Authorization: Bearer <cms:show secret_token />")
    - method = optional HTTP method (ex: 'get', 'post', 'put', 'patch', or 'delete') will default to 'get'
    - data = a form-url or json encoded string depending on APIs needs
    - into = optionally name a Couch variable to store response into
    - is_json = optionally make the variable a Couch array
    - scope optionally scope the variable (using is_json will default this to 'global')

Basic usage:
Code: Select all
<cms:curl url='https://jsonplaceholder.typicode.com/posts/89' headers="Content-type: application/json" method='patch' data='{"title" : "New Title", "body" : "New body here"}' into='response' is_json='1' />

<cms:show response.title /><br />
<cms:show response.body /><br />
<cms:show response.id />

If you need to add multiple headers, simply put a pipe ('|') character between each header.

Code: Select all
<cms:curl . . . headers="Content-type: application/json | Authorization: Bearer <cms:show secret_token />" . . . />

If anyone has suggestions for improvement, please comment!

Thank you @KK for making such an extensible CMS and @trendoman for your tips 8-)

- - - - - - -

Install

Put the attachment in your addons folder and include it in your kfunctions.php file.

curl.zip
Download
(1.06 KiB) Downloaded 392 times

Code: Select all
require_once( K_COUCH_DIR.'addons/curl/curl.php' );

- - - - - - -

Examples:

Form-urlencode function (in these examples, I'm calling this simple Couch function to urlencode data when needed)

Code: Select all
<cms:func 'urlencode' string=''><cms:php>
  global $CTX;
  echo(http_build_query($CTX->get('string')));
</cms:php></cms:func>


Make a new JSON Placeholder post. (https://jsonplaceholder.typicode.com/guide/)

Code: Select all
<cms:capture into='data' is_json='1'>
  {
    "title" : "New Post"
  }
</cms:capture>

<cms:curl url='https://jsonplaceholder.typicode.com/posts' headers="Content-type: application/json" method='post' data="<cms:show data as_json='1' />" into='response' is_json='1' />

<cms:show response.title /><br />
<cms:show response.id />

- - - - -

New Post
101

Make a new Stripe customer (https://stripe.com/docs/api/customers/create)

Code: Select all
in /couch/config.php
define('STRIPE_SECRET_KEY', 'sk_test_4eC39HqLyjWDarjtT1zdp7dc');

- - - - -

<cms:capture into='data' is_json='1'>
  {
    "description" : "My First Test Customer (created for API docs)"
  }
</cms:capture>

<cms:curl url='https://api.stripe.com/v1/customers' headers="Authorization: Bearer <cms:php>echo(STRIPE_SECRET_KEY);</cms:php>" method='post' data="<cms:call 'urlencode' data />" into='response' is_json='1' />

<cms:show response.description /><br />
<cms:show response.id />

- - - - -

My First Test Customer (created for API docs)
cus_8epDebVEl8Bs2V
Good job) I PMed my "fetch-url" code for your personal use.

It is safe to add User Agent and Referrer to always know who/what is knocking.
Code: Select all
curl_setopt($ch, CURLOPT_USERAGENT, "CouchCMS ".$CTX->get('k_cms_version') );
curl_setopt($ch, CURLOPT_REFERER, $CTX->get('k_page_link') );


UPDATE:

My latest version that also supports cookies is uploaded to GitHub:

Cms-Fu Funcs » fetch-url
@ mwlarkin1 and @trendoman,
I have a query!
How can we use this is a DBF?

I want to achieve executing a cURL when a DBF is submitted successfully.

This is what I have (though it is not working):
Code: Select all
<cms:db_persist_form
    ...
/>
<cms:if k_success>
<cms:capture into='data' is_json='1'>
    {
        "APIKey" : "some_value",
        "senderid" : "GENXCO",
   "channel" : "Trans",
   "DCS" : "0",
   "flashsms" : "0",
   "number" : "898304xxxx",
   "text" : "SMS text goes here",
   "route" : "6",
   "peid" : "1201159489186433918"
    }
</cms:capture>
<cms:curl url='http://login.businesslead.co.in/api/mt/SendSMS' headers="Content-type: application/json | charset=utf-8" method='POST' data="<cms:show data as_json='1' />" into='response' is_json='1' />


The actual API URL is:
http://login.businesslead.co.in/api/mt/SendSMS?APIKey=some_value&senderid=GENXCO&channel=Trans&DCS=0&flashsms=0&number=8983044369&text=SMS text goes here&route=6&peid=1201159489186433918


But nothing happens. How can errors be checked? Or is it that my code is faulty?

Any inputs will be helpful!

Regards,
GenXCoders
Image
where innovation meets technology
genxcoders wrote: ..
But nothing happens. How can errors be checked?

a. Open some console with curl and make sure, that full command with headers, url and cookies (if necessary) works well with --verbose flag. When you are absolutely sure that console command works perfect with expected response from server, only then use the funcs on page.

b. To debug the func's code, copy the func to the page and start adding var_dump($var); return; to verify the vars.

c. I recently used the 'fetch-url' myself and had it rewritten a bit (update is posted, issues resolved), now it allows to see the status of connection via <cms:show_json curl.status /> code. Not necessary to use my func, if you prefer the other, just copy the relevant line $status = curl_getinfo($ch); and add a var_dump($status); in case the server's response does not match the expected response previously achieved via console curl'ing.

Hello im trying to urlencode this but its not working what am i doing wrong any help would be greatly appreciated.



Code: Select all

<cms:func 'urlencode' string=''><cms:php>
          global $CTX;
          echo(http_build_query($CTX->get('string')));
        </cms:php></cms:func>
       
        <cms:capture into='data'>
 
            "grant_type": "client_credentials"
            "client_id": "**********************************"
            "client_secret": "******************************"
            "scope": "https://graph.microsoft.com/.default"
          
        </cms:capture>
       
   
     
       
   <cms:curl
        url='https://login.microsoftonline.com/c28d522e-2f26-4b40-8504-28668abfc36a/oauth2/v2.0/token'
        method='POST'
        headers='Content-Type: application/x-www-form-urlencoded | Connection: keep-alive | Accept: */* | Host: login.microsoftonline.com | redirect_uri: https://transgo.tech/trc.php'
        data="<cms:call 'urlencode' data />"
        into='token'
        is_json='1'
        />   
      
               
      
<cms:show token as_json='1'/>   
rudydjmedina wrote: Hello im trying to urlencode this but its not working what am i doing wrong any help would be greatly appreciated.


PHP function http_build_query does not work with strings, only can take an array. So, either add 'as_json' parameter and set the data as array or try PHP urlencode which works with strings ;)
6 posts Page 1 of 1