Home Database Mysql Tutorial Force.com微信开发系列(四)申请Access Token及自定义菜单之创

Force.com微信开发系列(四)申请Access Token及自定义菜单之创

Jun 07, 2016 pm 03:43 PM
access t develop WeChat Apply series

在微信接口 开发 中,许多服务的使用都离不开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]

方括号内的参数可以在测试账号首页找到,被涂抹处即是:

Force.com微信开发系列(四)申请Access Token及自定义菜单之创

 

真实请求的实例如下:

Force.com微信开发系列(四)申请Access Token及自定义菜单之创

 

执行上述请求后,接口返回的内容如下:

Force.com微信开发系列(四)申请Access Token及自定义菜单之创

 

这里我们就拿到了接下来需要使用的access_token:

ZiBTYeRMEMeCEM-Ol9ny_NE-XkgRbsP4snOqTRLh_nfp_UzFsYXVDtguf7jbZt70IQRkmEwU1n0cbxdWmJTdNg
Copy after login

,该Token将在7200秒,也就是2个小时内失效,之后需要重新请求前面的URL获取新的Token。

 
Copy after login
Copy after login
Copy after login

创建定义菜单目前服务号和通过认证的订阅号均可申请定义菜单,成功创建定义菜单后,微信公众账号界面如下图所示:

<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及自定义菜单之创" >
Copy after login

目前自定义菜单最多包括三个一级菜单,每个一级菜单最多包含五个二级菜单。一级菜单最多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>
Copy after login

 

画面非常简单,只有一段文字显示以及一个“注册微信菜单”按钮,点击按钮将处罚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> }
Copy after login

 

上面的代码构造了一段XML文,并将此XML问Post到req.setEnpoint方法里制定的URL。XML里即包含了对自定义菜单内容的具体定义,该XML的接口要求如下:

Force.com微信开发系列(四)申请Access Token及自定义菜单之创

 

完成后保存代码即可看到前面微信截图所显示的效果。

 

创建菜单点击事件处理方法

前面的菜单中我们定义的都是click类型的菜单,但该类型菜单被点击的时候,微信将经由腾讯服务器向开发者指定的URL发送一段XML文,该XML的结构说明如下:

Force.com微信开发系列(四)申请Access Token及自定义菜单之创

 

这和我们前面处理用户发送消息的方式其实是一致的,我们可以在前文准备的方法架构基础上添加处理代码,找到前文的如下代码段:

<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> }
Copy after login

 

在该代码段的基础上点击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> }
Copy after login

 

上面的代码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> }
Copy after login

 

其中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> }
Copy after login

 

方法运行效果如下,当用户点击了微信菜单后,系统会自动将eventKey里包含的信息发送给用户,这里是为了演示效果进行的简化,真实场景里可以根据需求进行具体功能订制:

 
Copy after login
Copy after login
Copy after login
<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及自定义菜单之创" >
Copy after login
 
Copy after login
Copy after login
Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The difference between H5 and mini-programs and APPs The difference between H5 and mini-programs and APPs Apr 06, 2025 am 10:42 AM

H5. The main difference between mini programs and APP is: technical architecture: H5 is based on web technology, and mini programs and APP are independent applications. Experience and functions: H5 is light and easy to use, with limited functions; mini programs are lightweight and have good interactiveness; APPs are powerful and have smooth experience. Compatibility: H5 is cross-platform compatible, applets and APPs are restricted by the platform. Development cost: H5 has low development cost, medium mini programs, and highest APP. Applicable scenarios: H5 is suitable for information display, applets are suitable for lightweight applications, and APPs are suitable for complex functions.

How to choose H5 and applets How to choose H5 and applets Apr 06, 2025 am 10:51 AM

The choice of H5 and applet depends on the requirements. For applications with cross-platform, rapid development and high scalability, choose H5; for applications with native experience, rich functions and platform dependencies, choose applets.

What is the difference between H5 page production and WeChat applets What is the difference between H5 page production and WeChat applets Apr 05, 2025 pm 11:51 PM

H5 is more flexible and customizable, but requires skilled technology; mini programs are quick to get started and easy to maintain, but are limited by the WeChat framework.

How to use sql if statement How to use sql if statement Apr 09, 2025 pm 06:12 PM

SQL IF statements are used to conditionally execute SQL statements, with the syntax as: IF (condition) THEN {statement} ELSE {statement} END IF;. The condition can be any valid SQL expression, and if the condition is true, execute the THEN clause; if the condition is false, execute the ELSE clause. IF statements can be nested, allowing for more complex conditional checks.

What are the different ways of promoting H5 and mini programs? What are the different ways of promoting H5 and mini programs? Apr 06, 2025 am 11:03 AM

There are differences in the promotion methods of H5 and mini programs: platform dependence: H5 depends on the browser, and mini programs rely on specific platforms (such as WeChat). User experience: The H5 experience is poor, and the mini program provides a smooth experience similar to native applications. Communication method: H5 is spread through links, and mini programs are shared or searched through the platform. H5 promotion methods: social sharing, email marketing, QR code, SEO, paid advertising. Mini program promotion methods: platform promotion, social sharing, offline promotion, ASO, cooperation with other platforms.

Unable to log in to mysql as root Unable to log in to mysql as root Apr 08, 2025 pm 04:54 PM

The main reasons why you cannot log in to MySQL as root are permission problems, configuration file errors, password inconsistent, socket file problems, or firewall interception. The solution includes: check whether the bind-address parameter in the configuration file is configured correctly. Check whether the root user permissions have been modified or deleted and reset. Verify that the password is accurate, including case and special characters. Check socket file permission settings and paths. Check that the firewall blocks connections to the MySQL server.

The difference between H5 page production and traditional web pages The difference between H5 page production and traditional web pages Apr 06, 2025 am 07:27 AM

The H5 page adopts client rendering, focusing on visual effects and interactivity, and is suitable for mobile display; traditional web pages rely on server-side rendering, focusing on content and SEO, and are suitable for occasions where a large amount of data needs to be processed and SEO is paid attention to. Depending on the project requirements, you can choose the appropriate technical solution to balance the lightweight experience and the implementation of complex functions.

How to solve the 'Network Error' caused by Vue Axios across domains How to solve the 'Network Error' caused by Vue Axios across domains Apr 07, 2025 pm 10:27 PM

Methods to solve the cross-domain problem of Vue Axios include: Configuring the CORS header on the server side using the Axios proxy using JSONP using WebSocket using the CORS plug-in

See all articles