Use Golang to develop WeChat public platform-Send customer service message

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

Attention and use of "flying constant" public number of friends have had the following experience: After inquiring about a flight situation, the flight checkin, boarding, landing and other information will be sent to you in succession, the service is through the public platform of customer service messages to achieve.

The customer service message is explained in the Public platform development documentation as follows: "When the user proactively sends the message to the public number (including sending messages, clicking on custom menus, subscribing to events, scanning QR codes, payment success events, user activism), the message data will be pushed to the developer, Developers in a period of time (currently modified to 48 hours) can call the customer service message interface, by post a JSON packet to send a message to a normal user, within 48 hours without limiting the number of sends. This interface is mainly used for customer service, such as the function of human message processing, to facilitate the developers to provide users with better service ".

In this article we will talk about how to use Golang to send a text customer service message.

I. Acquisition of Access_token

Access_token is the public number's globally unique ticket, and the public number calls the platform to use Access_token when invoking each interface. We have to proactively send a customer service message to the platform, the Access_token is our voucher. We need to get this access_token before we construct and distribute the customer service message.

The Access_token is valid for 2 hours (7200s) and can be used within two hours. The Public platform development documentation also gives technical advice on Access_token acquisition, storage, and refresh. But here we are only demo, no need to consider so much.

Via HTTPS GET request, we can get the access_token that belong to us, request line to:

Https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

Golang provides the default HTTP client implementation, which we can get Access_token by default client implementations.

Const (
token = "Wechat4go"
AppID = "Wx8e0fb2659c2eexxx"
Appsecret = "22746009b0162fe50cb915851c53fyyy"
Accesstokenfetchurl = "Https://api.weixin.qq.com/cgi-bin/token"
)

Func Fetchaccesstoken () (String, float64, error) {
Requestline: = Strings. Join ([]string{accesstokenfetchurl,
"? Grant_type=client_credential&appid=",
AppID,
"&secret=",
Appsecret}, "")

RESP, err: = http. Get (Requestline)
If err! = Nil | | Resp. StatusCode! = http. Statusok {
Return "", 0.0, err
}

Defer resp. Body.close ()
Body, err: = Ioutil. ReadAll (resp. Body)
If err! = Nil {
Return "", 0.0, err
}

Fmt. Println (String (body))
... ...
}

Whether successful or not, the platform returns a response that contains JSON data:

If you get it correctly, the JSON data in the answer is:

{"Access_token": " 0qcehwirtprucim5mm0cspyip5qounydb8usrsgvzcsfuvf6mu3vqq41oiifjdrtjpgn7b1x90hdvuanpb7ezhxg40b6bu_sgszh2byyf40 "," Expires_in ": 7200}

If you get an error, the JSON data in the answer is:

{"Errcode": 40001, "errmsg": "Invalid Credential"}

Like XML packets, Golang also provides Marshal and Unmarshal methods for JSON-formatted packets, using the same way as a JSON packet corresponding to a struct. From the above, with HTTP response, we cannot tell whether we have successfully obtained token, so we need to first determine whether the body contains some feature strings, such as "Access_token":

If bytes. Contains (Body, []byte ("Access_token")) {
Unmarshal to Accesstokenresponse struct
} else {
Unmarshal to Accesstokenerrorresponse struct
}

For two JSON data that succeeded and failed, we defined two structs:

Type Accesstokenresponse struct {
Accesstoken string ' JSON: ' Access_token '
Expiresin float64 ' JSON: "Expires_in"
}

Type Accesstokenerrorresponse struct {
Errcode float64
ErrMsg string
}

The code snippet for Json Unmarshal is as follows:

Json decoding
If bytes. Contains (Body, []byte ("Access_token")) {
ATR: = accesstokenresponse{}
Err = json. Unmarshal (body, &atr)
If err! = Nil {
Return "", 0.0, err
}
Return ATR. Accesstoken, ATR. Expiresin, Nil
} else {
Fmt. Println ("Return err")
Ater: = accesstokenerrorresponse{}
Err = json. Unmarshal (body, &ater)
If err! = Nil {
Return "", 0.0, err
}
Return "", 0.0, FMT. Errorf ("%s", ater. ERRMSG)
}

Our main function is as follows:
Func Main () {
Accesstoken, Expiresin, err: = Fetchaccesstoken ()
If err! = Nil {
Log. Println ("Get access_token Error:", err)
Return
}
Fmt. Println (Accesstoken, Expiresin)
}

Compile execution, the output of Access_token successfully obtained is as follows:

0qcehwirtprucim5mm0cspyip5qounydb8usrsgvzcsfuvf6mu3vqq41oiifjdrtjpgn7b1x90hdvuanpb7ezhxg40b6bu_sgszh2byyf40 7200

On failure, the output is as follows:

2014/12/30 12:39:56 Get Access_token error:invalid Credential

Second, send customer service message

The body format of the text customer service message is defined in the Platform development document, and a JSON data:

{
"Touser": "OPENID",
"Msgtype": "Text",
"Text":
{
"Content": "Hello World"
}
}

One of the touser filled in is OpenID. As mentioned in the previous article, each user has a unique OpenID for a subscription number/service number, which can be seen on the subscription number/Service number Management page, and can be seen in messages forwarded to the platform received (Fromusername). For example, my personal subscription to my Test experience number after the OpenID to be:

Bqcwuabkpisabbvd_dezg7q27qi

All we have to do is construct such a JSON data and put it into the HTTP POST package and send it to:

Https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=ACCESS_TOKEN

From the sample JSON packet given in the Platform development documentation, this is a nested JSON packet, which we Marshall by the following method:

Type customservicemsg struct {
Touser string ' JSON: ' Touser '
Msgtype string ' JSON: ' Msgtype '
Text textmsgcontent ' JSON: ' Text '
}

Type textmsgcontent struct {
Content string ' JSON: ' content '
}

Func pushcustommsg (Accesstoken, Touser, msg string) error {
        csmsg: = & Amp customservicemsg{
                 touser:  Touser,
                 msgtype: "Text",
                 text:    textmsgcontent{content:msg},
       }

Body, err: = json. Marshalindent (Csmsg, "", "")
If err! = Nil {
return err
}
Fmt. Println (String (body))
... ...
}

If you simply output the results of the above marshal, you can see:

{
"Touser": "Obqcwuabkpisabbvd_dezg7q27qi",
"Msgtype": "Text",
"Text": {
"Content": "Hello"
}
}

Next the Marshal []byte into the body of an HTTP post, sent to the specified URL:

var OpenID = "Obqcwuabkpisabbvd_dezg7q27qi"

Func pushcustommsg (Accesstoken, Touser, msg string) error {
... ...

Postreq, Err: = http. Newrequest ("POST",
Strings. Join ([]string{customserviceposturl, "? access_token=", Accesstoken}, ""),
bytes. Newreader (body))
If err! = Nil {
return err
}

PostReq.Header.Set ("Content-type", "Application/json; Encoding=utf-8 ")

Client: = &http. client{}
RESP, err: = client. Do (Postreq)
If err! = Nil {
return err
}
Resp. Body.close ()

return Nil
}

In the main function we add the sending link of the customer service message:

Func Main () {
       //Fetch Access_token
         Accesstoken, Expiresin, err: = Fetchaccesstoken ()
        If err! = nil {
                log. Println ("Get access_token Error:", err)
                 return
       }
         FMT. Println (Accesstoken, Expiresin)

Post Custom Service message
msg: = "Hello"
Err = Pushcustommsg (Accesstoken, OpenID, msg)
If err! = Nil {
Log. Println ("Push Custom Service message err:", err)
Return
}
}

Compile execution, phone sounded beep, open watch, public platform test number sent a message: "Hello."

The above demo complete code can be seen here, do not forget Appid,appsecret changed to your own value.

Currently the customer service interface is only available to the certified subscription number and service number, for an unauthenticated subscription number, unable to send customer service messages.

, Bigwhite. All rights reserved.

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.