Rapid development of WeChat public platform using Golang (iii): Customized menu

Source: Internet
Author: User
Tags cdata openid parse error
This is a creation in Article, where the information may have evolved or changed.

When you're done with Golang rapid development Public Platform (ii): After getting accesstoken, we can start customizing the menu

The custom menu is simple and brutal, and the post request is plugged into the menu you want to define.

Start rubbing code

Func pushwxmenucreate (Accesstoken string, menujsonbytes []byte) error {postreq, err: = http. Newrequest("POST", strings. Join([]string{"Https://api.weixin.qq.com/cgi-bin/menu/create","? access_token=", Accesstoken},""), bytes. Newreader(menujsonbytes)) If err! = Nil {FMT. Println("failed to make request to send menu", err) logutils. GetLog(). Error("failed to make request to send menu", err) return err} postreq. Header. Set("Content-type","Application/json; Encoding=utf-8 ") Client: = &http. Client{} resp, err: = Client. do(postreq) If err! = Nil {FMT. Println("Client failed to make request to send menu", err) logutils. GetLog(). Error("Client failed to make request to send menu", err) return err} else {FMT. Println("Build success to send Menu")} Defer RESP. Body. Close() return Nil}func Createwxmenu (o orm. Ormer) {//btn1: = Models. Btn{Name:"Enter the mall"Url:"http://www.baidu.com/", Btype:"View"}//BTN2: = Models. Btn{Name:"Member Center", Key:"Molan_user_center", Btype:"click"}//BTN3: = Models. Btn{Name:"My"Url:"Http://www.baidu.com/user_view", Btype:"View"}////btns: = []models. Btn{btn1, btn2, btn3}//wxmenu: = Models. Wxmenu{Button:btns}//menujsonbytes, err: = JSON. Marshal(wxmenu) Menustr: = ' {"button": [            {"Name":"Enter the mall","Type":"View","url":"http://www.baidu.com/"},            {"Name":"Central Administration","Sub_button":[                        {"Name":"User Center","Type":"click","Key":"Molan_user_center"},                        {"Name":"Announcements","Type":"click","Key":"Molan_institution"}]            },            {"Name":"Data modification","Type":"View","url":"Http://www.baidu.com/user_view"}]} '//if err = = Nil {//fmt. Println("generated menu JSON--->", menustr) at: = Models. Wxaccesstoken{Id:1} o. Readorcreate(&at,"id")//Send POST request to build menu Wxplatutil. Pushwxmenucreate(at. Accesstoken, []byte (MENUSTR))//} else {//Logutils. GetLog(). Error("Menu JSON conversion error", err)//}}

The use of structs to generate JSON received a miserable effect, so I simply rudely write the JSON directly into the ...

When the user clicks on the menu, the response message is sent to the URL that we fill in the server configuration by the post request, that is, using Beego to quickly develop the public platform (a): Turn on the/wx_connect in the server configuration. This document does not mention, if you are up to do the payment function, this step will certainly greet the document author's eight fathers.

Fortunately, we put the payment function in the back, not to our thinking caused confusion, so the next is no pressure.

When the user clicks on the menu, the server will post an XML, similar to this:

<XML><tousername><! [cdata[touser]]></tousername><fromusername><! [cdata[fromuser]]></fromusername><createtime>123456789</createtime><msgtype><! [cdata[event]]></msgtype><Event><! [cdata[view]]></Event><eventkey><! [cdata[www.qq.com]]></eventkey><MenuId>MENUID</MenuId></xml>

We can find out who is sent (Tousername) which user triggered (fromusername) by what way triggered (Event Eventkey), parse the XML on the line

I'm going to rub the code:

Wxconnect.go

//type wxmenuevent struct {//Tousername string ' xml: ' Tousername '//Fromusername string ' xml: ' Fromusername '//createtime Int64 ' xml: "Createtime" '//Msgtype string ' xml: ' Msgtype '//Event string ' xml: ' event ' '//view//Eventkey string ' xml: ' Eventkey '//MenuId string ' xml: ' MenuId '//Scancodeinfo *scancodeinfo ' xml: "Scancodeinfo" '//exclusive to scan code//Content string ' xml: ' content '//Ticket string ' xml: ' Ticket '//}//type scancodeinfo struct {//ScanType string ' xml: ' ScanType '//Scanresult string ' xml: ' Scanresult '//}//menu user clicks Scan Code Responsefunc(c *wxconnectcontroller) Post () {ifBytes, err: = Ioutil. ReadAll (C.ctx.request.body); Err = =Nil{//parsing XMLWxevent: =New(Models. Wxmenuevent)ifERR: = XML. Unmarshal (bytes, wxevent); Err = =Nil{//Processing menu clickDealwithmenuevent (&wxevent)}Else{FMT. Println ("Menu user clicks, Scan Code Response error", err)}}Else{FMT. Println ("Menu user click, Sweep code Parse body error", err)} C.enablerender =false}funcDealwithmenuevent (Wxevent **models. Wxmenuevent) {Switchwxevent.event { Case "VIEW"://Description is click on the bottom menu bar to enter the marketplace page             Case "click"://Click the button                ifStrings. Equalfold (Wxevent.eventkey,"Molan_user_center") {//Click User Center}Else ifStrings. Equalfold (Wxevent.eventkey,"Molan_institution") {//Click Announcements} Case "Subscribe"://Sweep code            ifStrings. Contains (Wxevent.eventkey,"Qrscene") {//Not concerned about the mall scanning others QR Code first attentionUpperid: = Strings. Split (Wxevent.eventkey,"_")[1]//eventkey:qrscene_16 This 16 is upper in the database ID note is not WXID}Else{//attention (sweep the official QR code instead of sweeping the individual QR code)} Case "SCAN"://have been concerned about scanning others QR code}}

Here sweep code is disgusting, Eventkey can be recognized as the current user to sweep which user's code, QRSCENE_XXXX this xxxx is your own set, you know on the line.
In this step, the response is basically finished.

But GRD demand always leave us alone.

The boss said: I want to know which user has clicked a button, and then give different responses according to different users.
This needs to use the Wxmenuevent.fromusername, this fromusername is the user OpenID, notice this thing is not the user's number.

This is what the official website says:

Come on, I can't Hold it:

Func Fetchwxinfoandicon (o orm. Ormer, OpenID, Wxuserinforurlstring) (*models. Wxuserinfo,Error) {at: = models. Wxaccesstoken{id:1} o.readorcreate (&at,"id") Requestline: = Strings.Join([]string{Wxuserinforurl,"? access_token=", at. Accesstoken,"&openid="Openid"&LANG=ZH_CN"},"") RESP,Err: = http.Get(Requestline)if Err! = Nil | | Resp. StatusCode! = http. Statusok {fmt. Println ("Send GET request get wxuserinfo Error",Err) Logutils.getlog ().Error("Send GET request get wxuserinfo Error",Err) return nil,Err} Defer resp. Body.close () body,Err: = Ioutil. ReadAll (resp. Body)if Err! = Nil {fmt. Println ("Send GET request get Wxuserinfo Read return body error",Err) Logutils.getlog ().Error("Send GET request get Wxuserinfo Read return body error",Err) return nil,Err}ifbytes. Contains (Body, []byte ("Errcode") {ater: = models. accesstokenerrorresponse{}Err= json. Unmarshal (body, &ater)if Err! = Nil {fmt. Printf ("Send GET request to get wxuserinfo error message%+v\n", ater) Logutils.getlog ().Error("Send GET request to get wxuserinfo error message%+v\n", ater) return nil,Err} return nil, FMT. Errorf ('%s ', Ater. ERRMSG)}Else{ATR: = models. wxuserinfo{}Err= json. Unmarshal (body, &atr)if Err! = Nil {fmt. Println ("Send GET request get wxuserinfo return data JSON parse error",Err) Logutils.getlog ().Error("Send GET request get wxuserinfo return data JSON parse error",Err) return nil,0.0,Err} return &atr, nil}}

Okay, now we got the user's nickname Avatar, and we're done.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.