Alpha Software Mobile Development Tools:   Alpha Anywhere    |   Alpha TransForm subscribe to our YouTube Channel  Follow Us on LinkedIn  Follow Us on Twitter  Follow Us on Facebook

Announcement

Collapse

The Alpha Software Forum Participation Guidelines

The Alpha Software Forum is a free forum created for Alpha Software Developer Community to ask for help, exchange ideas, and share solutions. Alpha Software strives to create an environment where all members of the community can feel safe to participate. In order to ensure the Alpha Software Forum is a place where all feel welcome, forum participants are expected to behave as follows:
  • Be professional in your conduct
  • Be kind to others
  • Be constructive when giving feedback
  • Be open to new ideas and suggestions
  • Stay on topic


Be sure all comments and threads you post are respectful. Posts that contain any of the following content will be considered a violation of your agreement as a member of the Alpha Software Forum Community and will be moderated:
  • Spam.
  • Vulgar language.
  • Quotes from private conversations without permission, including pricing and other sales related discussions.
  • Personal attacks, insults, or subtle put-downs.
  • Harassment, bullying, threatening, mocking, shaming, or deriding anyone.
  • Sexist, racist, homophobic, transphobic, ableist, or otherwise discriminatory jokes and language.
  • Sexually explicit or violent material, links, or language.
  • Pirated, hacked, or copyright-infringing material.
  • Encouraging of others to engage in the above behaviors.


If a thread or post is found to contain any of the content outlined above, a moderator may choose to take one of the following actions:
  • Remove the Post or Thread - the content is removed from the forum.
  • Place the User in Moderation - all posts and new threads must be approved by a moderator before they are posted.
  • Temporarily Ban the User - user is banned from forum for a period of time.
  • Permanently Ban the User - user is permanently banned from the forum.


Moderators may also rename posts and threads if they are too generic or do not property reflect the content.

Moderators may move threads if they have been posted in the incorrect forum.

Threads/Posts questioning specific moderator decisions or actions (such as "why was a user banned?") are not allowed and will be removed.

The owners of Alpha Software Corporation (Forum Owner) reserve the right to remove, edit, move, or close any thread for any reason; or ban any forum member without notice, reason, or explanation.

Community members are encouraged to click the "Report Post" icon in the lower left of a given post if they feel the post is in violation of the rules. This will alert the Moderators to take a look.

Alpha Software Corporation may amend the guidelines from time to time and may also vary the procedures it sets out where appropriate in a particular case. Your agreement to comply with the guidelines will be deemed agreement to any changes to it.



Bonus TIPS for Successful Posting

Try a Search First
It is highly recommended that a Search be done on your topic before posting, as many questions have been answered in prior posts. As with any search engine, the shorter the search term, the more "hits" will be returned, but the more specific the search term is, the greater the relevance of those "hits". Searching for "table" might well return every message on the board while "tablesum" would greatly restrict the number of messages returned.

When you do post
First, make sure you are posting your question in the correct forum. For example, if you post an issue regarding Desktop applications on the Mobile & Browser Applications board , not only will your question not be seen by the appropriate audience, it may also be removed or relocated.

The more detail you provide about your problem or question, the more likely someone is to understand your request and be able to help. A sample database with a minimum of records (and its support files, zipped together) will make it much easier to diagnose issues with your application. Screen shots of error messages are especially helpful.

When explaining how to reproduce your problem, please be as detailed as possible. Describe every step, click-by-click and keypress-by-keypress. Otherwise when others try to duplicate your problem, they may do something slightly different and end up with different results.

A note about attachments
You may only attach one file to each message. Attachment file size is limited to 2MB. If you need to include several files, you may do so by zipping them into a single archive.

If you forgot to attach your files to your post, please do NOT create a new thread. Instead, reply to your original message and attach the file there.

When attaching screen shots, it is best to attach an image file (.BMP, .JPG, .GIF, .PNG, etc.) or a zip file of several images, as opposed to a Word document containing the screen shots. Because Word documents are prone to viruses, many message board users will not open your Word file, therefore limiting their ability to help you.

Similarly, if you are uploading a zipped archive, you should simply create a .ZIP file and not a self-extracting .EXE as many users will not run your EXE file.
See more
See less

JSON issue

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • JSON issue

    working on the square API to get a refresh token, running into an issue with a JSON array but not sure what to do about it. There are two records in mydb and the first one works correctly and does the insert, the second go round fails when it goes to get "contents" from cf_1.GetContent to populate the fields for the next update to the db.
    cf_1.getcontent() is concatenating the values from the for each banana array.

    I tried ce_close() as you can see in the code and setting the value manually but again when it calls the value from the header its a concatenated value from both records, my guess is if I had 25 values for each banana I would see 25 values returned in the header. To me it looks like the TCP keepalive is doing justs that even though I am closing the curl connection ( or am I?)

    I just want to run the curl command for each merchant_id, get the contents back from square and update my DB

    Hopefully this will make sense to somebody here who can guide me in the right direction. I did think about waiting until the whole thing runs and use a json array to then plow through each value and perform all updates but it seems like it would be easier to just re-use the curl cmd and it certainly seems like we do this all the time when sending multiple emails, or sms using curl...

    Here is a copy of the xbasic code with some modified values for security sake

    Code:
    function getnewoauth as c (e as p)
    
        dim getnewoauth as c
        'debug(1)
        dim cn as sql::Connection
        dim result as l = .f.
        dim args as sql::Arguments
        dim rs as sql::ResultSet
        dim sqlstm as c
        dim vResult[0] as p
        dim merchid as c
        dim flag_1 as l
        dim slist1[0] as c = [ "Square-Version: 2022-08-23" , "Content-Type: application/json" ]
    
    
    
    
        result = cn.open("::Name::Connection1")
            sqlstm = "SELECT * FROM squaredata"
            result = cn.Execute(sqlstm)
            rs = cn.ResultSet
            merchid = rs.ToPropertyArray(vResult)
    
    
        debug(1)
    
    for each banana in vResult
    
    f.client_id = "sq0iyow"
    f.client_secret = "sq0csthK0Bc"
    f.grant_type = "refresh_token"
    f.refresh_token = banana.refresh_token
    js = json_generate(f)
    posted_fields = js
        dim ce as extension::Curl
        dim jso as extension::JSON
        dim cf_1 as extension::CurlFile
    ce = extension::Curl.Init()
    ce.setOpt("BUFFERSIZE",102400)
    ce.setOpt("URL","https://connect.squareup.com/oauth2/token")
    ce.setOpt("HTTPHEADER",slist1)
    ce.setOpt("USERAGENT","curl/7.81.0")
    ce.setOpt("MAXREDIRS",50)
    ce.setOpt("CAINFO",a5.Get_Exe_Path()+"\caroot\ca-cert.pem")
    ce.setOpt("CAPATH",a5.Get_Exe_Path()+"\caroot")
    ce.setOpt("PROXY_CAPATH", a5.get_exe_path() + "\caroot")
    ce.setOpt("CUSTOMREQUEST","POST")
    ce.setOpt("FTP_SKIP_PASV_IP",1)
    ce.setOpt("TCP_KEEPALIVE",1)
        dim f as p
        dim js as c
        dim posted_fields as c
    ce.setOpt("POSTFIELDS",posted_fields)
    ce.setOpt("POSTFIELDSIZE_LARGE", len(posted_fields) )        
    ce.SetOpt("FILE",cf_1)
    
    flag_1 = ce.Exec()
    if flag_1 then
    
        dim headers as c
        dim contents as c = "Failed"
        headers = cf_1.GetHeaders()
        contents = cf_1.GetContent()
    
    end if
        jso.setJson(contents)
            dim mytoken as c
                mytoken = jso.getProperty("access_token")
            dim myrefresh as c
                myrefresh = jso.getProperty("refresh_token")    
            dim expdate as c
                expdate = jso.getProperty("expires_at")
            dim merchid as c
                merchid  = jso.getProperty("merchant_id")
                    args.Add("mytoken",mytoken)
                    args.Add("reftoken",myrefresh)
                    args.Add("expdate",expdate)
                    args.Add("merchid",merchid)
            updatedata = "UPDATE alphanwcopro.mysquaredata set access_token = :mytoken, expiration_date = :expdate WHERE merchant_id = :merchid"
                    cn.execute(updatedata,args)
    
        ce.close()    
    next
    ce.close()
    cn.close()
    end function​
    Any ideas would be greatly appreciated!



    NWCOPRO: Nuisance Wildlife Control Software My Application: http://www.nwcopro.com "Without forgetting, we would have no memory at all...now what was I saying?"

  • #2
    For clarity, the issue is the resulting value of cf_1.content, for instance the first record would run in the for each banana variable to return this in the variable "contents"

    Code:
    {
      "access_token": "EAAp7Yg",
      "token_type": "bearer",
      "expires_at": "2022-11-03T02:24:03Z",
      "merchant_id": "DBHE1",
      "refresh_token": "EQANmLy",
      "short_lived": false
    }​

    once we make a second round trip for the next record we get

    Code:
    {
      "access_token": "EAAp7Yg",
      "token_type": "bearer",
      "expires_at": "2022-11-03T02:24:03Z",
      "merchant_id": "DBHE1",
      "refresh_token": "EQANmLy",
      "short_lived": false
    }​​{
      "access_token": "EAAgucp",
      "token_type": "bearer",
      "expires_at": "2022-11-03T02:56:25Z",
      "merchant_id": "FSTK6",
      "refresh_token": "EQAAgbC",
      "short_lived": false
    }​

    so as you can imagine, when I call

    jso.setJson(contents)
    dim mytoken as c
    mytoken = jso.getProperty("access_token")​...etc I get an error that there is a root array issue...and basically I cant set my values because I have an array now

    Hope that helps explain my issue further...
    NWCOPRO: Nuisance Wildlife Control Software My Application: http://www.nwcopro.com "Without forgetting, we would have no memory at all...now what was I saying?"

    Comment


    • #3
      2022-10-04_17-17-25-JSON1.png2022-10-04_17-19-16JSON2.png Pete
      Insanity: doing the same thing over and over again and expecting different results.
      Albert Einstein, (attributed)
      US (German-born) physicist (1879 - 1955)

      Comment


      • #4
        My goal wasn't to correct the json at the end, the goal was to reset contents to a single record in cf_1.getContents because the jso.setJson(contents) line is throwing an error on the next FOR EACH with albeit improperly formatted json.

        thanks though for the heads up on that, I could maybe use that info to just create some valid json to process after the whole thing has run.
        NWCOPRO: Nuisance Wildlife Control Software My Application: http://www.nwcopro.com "Without forgetting, we would have no memory at all...now what was I saying?"

        Comment


        • #5
          We had the same issue with other API's. Seems like the API is holding on to the connection and the previous values. Our solution was to move the API into an Xbasic module or into a UDF and call it from the component. So, we open and close the module or call the function so the API will see it as a fresh request. Closing and deleting the values in the component does not work.
          Pat Bremkamp
          MindKicks Consulting

          Comment


          • #6
            exactly that...I tried to close the connection with ce.close after the insert but it still persists with the values as though it didn't close the connection. I am thinking my only recourse would be to accept back whatever it returns and deal with that...and as you can see would be difficult. Square says that I should refresh the tokens every 7 days (they exp at 30 days btw) so for each connected account I need to run this once a week. I was hoping to build a solution that would run through each record and update them.
            I just can't figure out what constitutes a new "connection" to the API
            NWCOPRO: Nuisance Wildlife Control Software My Application: http://www.nwcopro.com "Without forgetting, we would have no memory at all...now what was I saying?"

            Comment


            • #7
              after the insert I wrote more curl to close the connection by re-dimming the whole scenario with slist1 = connection: close and it sends back the message resource not found which dammit all happily appends to cf_1.getcontents() too, lol so now it looks like this:

              Code:
              {
                "access_token": "EAAAMSY",
                "token_type": "bearer",
                "expires_at": "2022-11-03T14:23:37Z",
                "merchant_id": "DHHE1",
                "refresh_token": "EQAAmLy",
                "short_lived": false
              }{
                "message": "Resource not found.",
                "type": "NOT_FOUND"
              }{
                "access_token": "EAAA_m9",
                "token_type": "bearer",
                "expires_at": "2022-11-03T14:25:44Z",
                "merchant_id": "FSTCK6",
                "refresh_token": "EQAAgbC",
                "short_lived": false
              }​

              Any ideas on how to "clear" that value in CURL after the insert??? It just keeps appending the values to FILE
              NWCOPRO: Nuisance Wildlife Control Software My Application: http://www.nwcopro.com "Without forgetting, we would have no memory at all...now what was I saying?"

              Comment


              • #8
                I got it! cf_1.clear() was all that was needed after the insert and before the "next"
                so the trailing end of my code now looks like this!

                updatedata = "UPDATE alphanwcopro.squaredata set access_token = :mytoken, expiration_date = :expdate WHERE merchant_id = :merchid"
                cn.execute(updatedata,args)


                cf_1.Clear()


                next
                ce.close()
                cn.close()
                end function​


                Full xbasic function now looks like this:

                Code:
                function getnewoauth as c (e as p)
                
                dim getnewoauth as c
                'debug(1)
                dim cn as sql::Connection
                dim result as l = .f.
                dim args as sql::Arguments
                dim rs as sql::ResultSet
                dim sqlstm as c
                dim vResult[0] as p
                dim merchid as c
                dim flag_1 as l
                dim slist1[0] as c = [ "Square-Version: 2022-08-23" , "Content-Type: application/json" ]
                
                
                
                
                result = cn.open("::Name::Connection1")
                sqlstm = "SELECT * FROM squaredata"
                result = cn.Execute(sqlstm)
                rs = cn.ResultSet
                merchid = rs.ToPropertyArray(vResult)
                
                
                debug(1)
                
                for each banana in vResult
                
                f.client_id = "sq0iyow"
                f.client_secret = "sq0csthK0Bc"
                f.grant_type = "refresh_token"
                f.refresh_token = banana.refresh_token
                js = json_generate(f)
                posted_fields = js
                dim ce as extension::Curl
                dim jso as extension::JSON
                dim cf_1 as extension::CurlFile
                ce = extension::Curl.Init()
                ce.setOpt("BUFFERSIZE",102400)
                ce.setOpt("URL","https://connect.squareup.com/oauth2/token")
                ce.setOpt("HTTPHEADER",slist1)
                ce.setOpt("USERAGENT","curl/7.81.0")
                ce.setOpt("MAXREDIRS",50)
                ce.setOpt("CAINFO",a5.Get_Exe_Path()+"\caroot\ca-cert.pem")
                ce.setOpt("CAPATH",a5.Get_Exe_Path()+"\caroot")
                ce.setOpt("PROXY_CAPATH", a5.get_exe_path() + "\caroot")
                ce.setOpt("CUSTOMREQUEST","POST")
                ce.setOpt("FTP_SKIP_PASV_IP",1)
                ce.setOpt("TCP_KEEPALIVE",1)
                dim f as p
                dim js as c
                dim posted_fields as c
                ce.setOpt("POSTFIELDS",posted_fields)
                ce.setOpt("POSTFIELDSIZE_LARGE", len(posted_fields) )
                ce.SetOpt("FILE",cf_1)
                
                flag_1 = ce.Exec()
                if flag_1 then
                
                dim headers as c
                dim contents as c
                headers = cf_1.GetHeaders()
                contents = cf_1.GetContent()
                
                end if
                jso.setJson(contents)
                dim mytoken as c
                mytoken = jso.getProperty("access_token")
                dim myrefresh as c
                myrefresh = jso.getProperty("refresh_token")
                dim expdate as c
                expdate = jso.getProperty("expires_at")
                dim merchid as c
                merchid = jso.getProperty("merchant_id")
                args.Add("mytoken",mytoken)
                args.Add("reftoken",myrefresh)
                args.Add("expdate",expdate)
                args.Add("merchid",merchid)
                updatedata = "UPDATE alphanwcopro.mysquaredata set access_token = :mytoken, expiration_date = :expdate WHERE merchant_id = :merchid"
                cn.execute(updatedata,args)
                
                'this clears the memory stream response found when calling getcontent
                cf_1.clear()
                
                next
                ce.close()
                cn.close()
                end function​​
                Sorry to drag all of you through this but hopefully it helps someone in the future!
                Last edited by CharlesParker; 10-04-2022, 12:25 PM.
                NWCOPRO: Nuisance Wildlife Control Software My Application: http://www.nwcopro.com "Without forgetting, we would have no memory at all...now what was I saying?"

                Comment


                • #9
                  Nice thanks
                  Insanity: doing the same thing over and over again and expecting different results.
                  Albert Einstein, (attributed)
                  US (German-born) physicist (1879 - 1955)

                  Comment


                  • #10
                    This would be more appropriately named Curl Issue, rather than JSON but I don't think I can edit the title...regardless for those of you that might want to reuse any of this code be forewarned that there really isn't much error trapping in here. You could have an issue where a user would disconnect their square account, or you have data that isn't what square is expecting - this could halt the flow of the xbasic. Watching the code run in the debugger perfectly is so oddly satisfying, but having it fail is so painful...
                    NWCOPRO: Nuisance Wildlife Control Software My Application: http://www.nwcopro.com "Without forgetting, we would have no memory at all...now what was I saying?"

                    Comment


                    • #11
                      I seem to remember guiding k2kcc away from using curl for this because of the difficulty trying debug it.
                      For those rare occasions when http_fetch won't work, I created a function to use curl, but the setup
                      is basically the same as we used for http_fetch.
                      Gregg
                      https://paiza.io is a great site to test and share sql code

                      Comment


                      • #12
                        I really like curl so far, this was my first real issue and believe it or not I found the answer in the AA documentation - literally the first entry very simply provided the answer.
                        https://documentation.alphasoftware....r%20Method.xml

                        the rest of the internet, including the curl website sent me down a bunch of rabbit holes.

                        Took me two days to find it, lol. Since the failure was with the cf_1 extension I should've looked there, instead I searched for CURL which I found this page
                        https://documentation.alphasoftware....e%20Method.xml
                        you'll notice the curl clear method is not listed here as there is a difference in the documentation of CURL vs CurlFile as a related topic but if you back up one you find curlfile and others.

                        So it's really just a matter of digging around, it's in there. I don't think AA gets enough credit for the improvements done to the documentation over the last few years.

                        NWCOPRO: Nuisance Wildlife Control Software My Application: http://www.nwcopro.com "Without forgetting, we would have no memory at all...now what was I saying?"

                        Comment

                        Working...
                        X