Force.com微信开发系列(四)申请Access Token及自定义菜单之创
在微信接口 开发 中,许多服务的使用都离不开Access Token,Access Token相当于打开这些服务的钥匙,正常情况下会在7200秒内失效,重复获取将导致上次获取的Token失效,本文将首先介绍如何获取Access Token,再介绍如何通过Access Token来在微信内添加自 定
在微信接口开发中,许多服务的使用都离不开Access Token,Access Token相当于打开这些服务的钥匙,正常情况下会在7200秒内失效,重复获取将导致上次获取的Token失效,本文将首先介绍如何获取Access Token,再介绍如何通过Access Token来在微信内添加自定义菜单(注意,开发者需要申请测试账号来测试自定义菜单,如何申请请参照前文)。
申请Access Token
获取Access Token接口的网址如下:
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=[APPID]&secret=[APPSECRET]
方括号内的参数可以在测试账号首页找到,被涂抹处即是:
真实请求的实例如下:
执行上述请求后,接口返回的内容如下:
这里我们就拿到了接下来需要使用的access_token:
ZiBTYeRMEMeCEM-Ol9ny_NE-XkgRbsP4snOqTRLh_nfp_UzFsYXVDtguf7jbZt70IQRkmEwU1n0cbxdWmJTdNg
,该Token将在7200秒,也就是2个小时内失效,之后需要重新请求前面的URL获取新的Token。
创建自定义菜单目前服务号和通过认证的订阅号均可申请自定义菜单,成功创建自定义菜单后,微信公众账号界面如下图所示:
<img src="/static/imghw/default1.png" data-src="/inc/test.jsp?url=http%3A%2F%2Fimages.cnitblog.com%2Fblog%2F119628%2F201407%2F132115222233941.png&refer=http%3A%2F%2Fwww.cnblogs.com%2Fjohnsonwong%2Fp%2F3841675.html" class="lazy" alt="Force.com微信开发系列(四)申请Access Token及自定义菜单之创" >
目前自定义菜单最多包括三个一级菜单,每个一级菜单最多包含五个二级菜单。一级菜单最多4个汉字,二级菜单最多7个汉字,多出来的部分会以“…”代替。请注意,创建自定义菜单后,由于微信客户端缓存,需要一定时间才在微信客户端展现出来,最快捷的方式是重新关注微信公众账号,这样马上就能看到自定义菜单。
目前自定义菜单接口可实现两种类型的按钮:
click:用户点击click类型按钮后,微信服务器会通过消息接口推送类型为event的结构给开发者,并且带上按钮中开发者填写的key值,开发者可以通过自定义的key值与用户进行交互。
view:用户点击view类型按钮后,微信客户端将会打开开发者在按钮中填写的url值(网页链接),达到打开网页的目的。建议与网页授权获取用户基本信息接口结合,获得用户的登入个人信息。
创建菜单的接口如下:
https://api.weixin.qq.com/cgi-bin/menu/create?access_token=[ACCESS_TOKEN]
其中中括号内的变量ACCESS_TOKEN即为我们前面获得的Token值。接下来我们开发一个简单的Apex网页,我们将通过这个网页来创建自定义菜单。
WeChatUtilityPage:网页,负责提交创建自定义菜单的申请,并显示创建成功与否的结果;
WechatUtilityController: 控制器类,负责网页背后的具体业务逻辑处理。
WeChatUtilityPage的源代码如下:
<span>1</span> <page standardstylesheets="<span">"<span>false</span><span>"</span> showHeader=<span>"</span><span>false</span><span>"</span> sidebar=<span>"</span><span>false</span><span>"</span> controller=<span>"</span><span>WechatUtilityController</span><span>"</span>> <span>2</span> <form> <span>3</span> <font face="<span">"<span>微软雅黑</span><span>"</span>><strong><strong><strong>菜单</strong></strong>服务<strong>系列</strong>:</strong><br><br> <span>4</span> <commandbutton value="<span">"<span>注册微信<strong><strong>菜单</strong></strong></span><span>"</span> action=<span>"</span><span>{!register}</span><span>"</span> id=<span>"</span><span>register</span><span>"</span> /> <span>5</span> </commandbutton></font> </form> <span>6</span> {!<span>msg} </span><span>7</span> <pagemessages></pagemessages> <span>8</span> </page>
画面非常简单,只有一段文字显示以及一个“注册微信菜单”按钮,点击按钮将处罚WechatUtilityController里的register方法,返回消息通过msg对象来显示,该对象的定义也在WechatUtilityController里,如果有系统异常,则将通过
<span> 1</span> <span>public</span> <span>class</span><span> WechatUtilityController { </span><span> 2</span> <span>public</span> <span>static</span> String msg{<span>get</span>;<span>set</span><span>;} </span><span> 3</span> <span> 4</span> <span>public</span> String accessToken{<span>get</span>;<span>set</span><span>;} </span><span> 5</span> <span>public</span><span> WechatUtilityController (){ </span><span> 6</span> accessToken = ‘ZiBTYeRMEMeCEM-Ol9ny_NE-<span>XkgRbsP4snOqTRLh_nfp_UzFsYXVDtguf7jbZt70IQRkmEwU1n0cbxdWmJTdNg’; </span><span> 7</span> <span> } </span><span> 8</span> <span> 9</span> <span>public</span> <span>void</span><span> register(){ </span><span>10</span> Http h = <span>new</span><span> Http(); </span><span>11</span> HttpRequest req = <span>new</span><span> HttpRequest(); </span><span>12</span> req.setMethod(<span>'</span><span>POST</span><span>'</span><span>); </span><span>13</span> req.setHeader(<span>'</span><span>Accept-Encoding</span><span>'</span>,<span>'</span><span>gzip,deflate</span><span>'</span><span>); </span><span>14</span> req.setHeader(<span>'</span><span>Content-Type</span><span>'</span>,<span>'</span><span>text/xml;charset=UTF-8</span><span>'</span><span>); </span><span>15</span> req.setHeader(<span>'</span><span>User-Agent</span><span>'</span>,<span>'</span><span>Jakarta Commons-HttpClient/3.1</span><span>'</span><span>); </span><span>16</span> <span>17</span> String xml = <span>'</span><span>{"button":[{"name":"关于我们","sub_button":[{"type":"click","name":"公司简介","key":"公司简介"},{"type":"click","name":"社会责任","key":"社会责任"},{"type":"click","name":"联系我们","key":"联系我们"}]},{"name":"产品服务","sub_button":[{"type":"click","name":"微信平台","key":"微信平台"},{"type":"click","name":"微博应用","key":"微博应用"},{"type":"click","name":"手机网站","key":"手机网站"}]},{"name":"技术支持","sub_button":[{"type":"click","name":"文档下载","key":"文档下载"},{"type":"click","name":"技术社区","key":"技术社区"},{"type":"click","name":"服务热线","key":"服务热线"}]}]}</span><span>'</span><span>; </span><span>18</span> <span>19</span> <span> req.setBody(xml); </span><span>20</span> req.setEndpoint(<span>'</span><span>https://api.weixin.qq.com/cgi-bin/menu/create?access_token=‘ + accessToken);</span> <span>21</span> String bodyRes =<span> ‘’; </span><span>22</span> <span>23</span> <span>try</span><span>{ </span><span>24</span> HttpResponse res =<span> h.send(req); </span><span>25</span> bodyRes =<span> res.getBody(); </span><span>26</span> <span> } </span><span>27</span> <span>catch</span><span>(System.CalloutException e) { </span><span>28</span> System.debug(<span>'</span><span>Callout error: </span><span>'</span>+<span> e); </span><span>29</span> ApexPages.addMessage(<span>new</span><span> ApexPages.Message(ApexPages.Severity.FATAL, e.getMessage())); </span><span>30</span> <span> } </span><span>31</span> msg =<span> bodyRes; </span><span>32</span> <span> } </span><span>33</span> <span>34</span> }
上面的代码构造了一段XML文,并将此XML问Post到req.setEnpoint方法里制定的URL。XML里即包含了对自定义菜单内容的具体定义,该XML的接口要求如下:
完成后保存代码即可看到前面微信截图所显示的效果。
创建菜单点击事件处理方法
前面的菜单中我们定义的都是click类型的菜单,但该类型菜单被点击的时候,微信将经由腾讯服务器向开发者指定的URL发送一段XML文,该XML的结构说明如下:
这和我们前面处理用户发送消息的方式其实是一致的,我们可以在前文准备的方法架构基础上添加处理代码,找到前文的如下代码段:
<span>1</span> <span>if</span>(msgType.equals(<span>'</span><span>text</span><span>'</span><span>)){ </span><span>2</span> rtnMsg =<span> handleText(inMsg); </span><span>3</span> }
在该代码段的基础上点击else处理分支:
<span>1</span> <span>if</span>(msgType.equals(<span>'</span><span>text</span><span>'</span><span>)){ </span><span>2</span> <span>3</span> rtnMsg =<span> handleText(inMsg); </span><span>4</span> <span>5</span> <span>} </span><span>6</span> <span>else</span> <span>if</span>(msgType.equals(<span>'</span><span>event</span><span>'</span><span>)){ </span><span>7</span> rtnMsg =<span> handleEvent(inMsg); </span><span>8</span> }
上面的代码else分支判断如果用户发送来的消息类型是event类型则调用handleEvent方法来处理,此时用户可能是关注了微信账号,可能是取消了关注,也可能是点击了菜单…,在handleEvent方法里要进一步判断,留意方法里的eventKey是前面XML里用户自定义的:
<span> 1</span> <span>private</span> <span>static</span><span> String handleEvent(IncomingMsg msg){ </span><span> 2</span> String <span>event</span> = msg.<span>event</span><span>; </span><span> 3</span> String strTmp = <span>''</span><span>; </span><span> 4</span> <span>if</span>(<span>event</span>.equals(<span>'</span><span>subscribe</span><span>'</span><span>)){ </span><span> 5</span> strTmp = <span>'</span><span>欢迎关注本账号!</span><span>'</span><span>; </span><span> 6</span> <span> } </span><span> 7</span> <span>else</span> <span>if</span>(<span>event</span>.equals(<span>'</span><span>unsubscribe</span><span>'</span><span>)){ </span><span> 8</span> strTmp = <span>''</span><span>; </span><span> 9</span> <span> } </span><span>10</span> <span>else</span> <span>if</span>(<span>event</span>.equals(<span>'</span><span>CLICK</span><span>'</span><span>)){ </span><span>11</span> strTmp = <span>'</span><span>您点击了</span><span>'</span> +<span> msg.eventKey; </span><span>12</span> <span> } </span><span>13</span> String result =<span> composeTextReply(msg, strTmp); </span><span>14</span> <span>return</span><span> result; </span><span>15</span> }
其中composeTextReply方法的定义如下:
<span>1</span> <span>private</span> <span>static</span><span> String composeTextReply(IncomingMsg msg, String content){ </span><span>2</span> String strTmp = <span>'</span><span><xml><tousername></tousername><fromusername></fromusername><createtime>12345678</createtime><msgtype></msgtype><content></content></xml></span><span>'</span><span>; </span><span>3</span> String[] arguments = <span>new</span><span> String[]{msg.fromUserName, msg.toUserName, content}; </span><span>4</span> String strReply =<span> String.format(strTmp, arguments); </span><span>5</span> <span>return</span><span> strReply; </span><span>6</span> }
方法运行效果如下,当用户点击了微信菜单后,系统会自动将eventKey里包含的信息发送给用户,这里是为了演示效果进行的简化,真实场景里可以根据需求进行具体功能订制:
<img src="/static/imghw/default1.png" data-src="/inc/test.jsp?url=http%3A%2F%2Fimages.cnitblog.com%2Fblog%2F119628%2F201407%2F132115245352567.png&refer=http%3A%2F%2Fwww.cnblogs.com%2Fjohnsonwong%2Fp%2F3841675.html" class="lazy" alt="Force.com微信开发系列(四)申请Access Token及自定义菜单之创" >

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

DeepSeek cannot convert files directly to PDF. Depending on the file type, you can use different methods: Common documents (Word, Excel, PowerPoint): Use Microsoft Office, LibreOffice and other software to export as PDF. Image: Save as PDF using image viewer or image processing software. Web pages: Use the browser's "Print into PDF" function or the dedicated web page to PDF tool. Uncommon formats: Find the right converter and convert it to PDF. It is crucial to choose the right tools and develop a plan based on the actual situation.

Thanks to netizens Qing Qiechensi, HH_KK, Satomi Ishihara and Wu Yanzu of South China for submitting clues! According to news on September 2, there are recent rumors that "iPhone 16 may not support WeChat." In response to this, a reporter from Shell Finance called Apple's official hotline. Apple's technical consultant in China responded that whether iOS systems or Apple devices can continue to use WeChat, and WeChat The issue of whether it can continue to be listed and downloaded on the Apple App Store requires communication and discussion between Apple and Tencent to determine the future situation. Software App Store and WeChat Problem Description Software App Store technical consultant pointed out that developers may need to pay fees to put software on the Apple Store. After reaching a certain number of downloads, Apple will need to pay corresponding fees for subsequent downloads. Apple is actively communicating with Tencent,

DeepSeek: A powerful AI image generation tool! DeepSeek itself is not an image generation tool, but its powerful core technology provides underlying support for many AI painting tools. Want to know how to use DeepSeek to generate images indirectly? Please continue reading! Generate images with DeepSeek-based AI tools: The following steps will guide you to use these tools: Launch the AI Painting Tool: Search and open a DeepSeek-based AI Painting Tool (for example, search "Simple AI"). Select the drawing mode: select "AI Drawing" or similar function, and select the image type according to your needs, such as "Anime Avatar", "Landscape"

The Xiaomi Mi 15 series is expected to be officially released in October, and its full series codenames have been exposed in the foreign media MiCode code base. Among them, the flagship Xiaomi Mi 15 Ultra is codenamed "Xuanyuan" (meaning "Xuanyuan"). This name comes from the Yellow Emperor in Chinese mythology, which symbolizes nobility. Xiaomi 15 is codenamed "Dada", while Xiaomi 15Pro is named "Haotian" (meaning "Haotian"). The internal code name of Xiaomi Mi 15S Pro is "dijun", which alludes to Emperor Jun, the creator god of "The Classic of Mountains and Seas". Xiaomi 15Ultra series covers

Since the Huawei Mate60 series went on sale last year, I personally have been using the Mate60Pro as my main phone. In nearly a year, Huawei Mate60Pro has undergone multiple OTA upgrades, and the overall experience has been significantly improved, giving people a feeling of being constantly new. For example, recently, the Huawei Mate60 series has once again received a major upgrade in imaging capabilities. The first is the new AI elimination function, which can intelligently eliminate passers-by and debris and automatically fill in the blank areas; secondly, the color accuracy and telephoto clarity of the main camera have been significantly upgraded. Considering that it is the back-to-school season, Huawei Mate60 series has also launched an autumn promotion: you can enjoy a discount of up to 800 yuan when purchasing the phone, and the starting price is as low as 4,999 yuan. Commonly used and often new products with great value

Rumors of WeChat supporting iPhone 16 were debunked. Thanks to netizens Xi Chuang Jiu Shi and HH_KK for submitting clues! According to news on September 2, there are rumors today that WeChat may not support iPhone 16. Once the iPhone is upgraded to the iOS 18.2 system, it will not be able to use WeChat. According to "Daily Economic News", it was learned from people familiar with the matter that this rumor is a rumor. Apple's response: According to Shell Finance, Apple's technical consultant in China responded that the issue of whether WeChat can continue to be used on iOS systems or Apple devices, and whether WeChat can continue to be listed and downloaded in the Apple App Store, needs to be resolved between Apple and Tencent. Only through communication and discussion can we determine the future situation. Currently, Apple is actively communicating with Tencent to confirm whether Tencent will continue to

Gate.io, a leading cryptocurrency trading platform founded in 2013, provides Chinese users with a complete official Chinese website. The website provides a wide range of services, including spot trading, futures trading and lending, and provides special features such as Chinese interface, rich resources and community support.

Gateio Exchange app download channels for old versions, covering official, third-party application markets, forum communities and other channels. It also provides download precautions to help you easily obtain old versions and solve the problems of discomfort in using new versions or device compatibility.
