Home > Backend Development > PHP Tutorial > Illustration of developing WeChat service account with PHP

Illustration of developing WeChat service account with PHP

小云云
Release: 2023-03-20 10:50:01
Original
2928 people have browsed it

It turned out that there was a WeChat ID registered 3 years ago, but the background operation could not be changed from "Subscription Account" to "Service Account", so I immediately contacted Tencent's customer service. The customer service was quite enthusiastic, and mm patiently told me that the system has been updated. , for the WeChat account that cannot be upgraded, you can only re-register----"*#*(*¥)¥K30#$e)". After getting crazy for a while, you can only re-register. Let's start from registration to Internal requirements discussion, to graphic and text summary of development. <br>

Step1: WeChat registration

On the official WeChat public account website: https://mp.weixin.qq.com, click Register

Illustration of developing WeChat service account with PHP

#As shown in the picture above, WeChat ID is registered by email. Each email can only apply for one kind of account: service account, subscription account or enterprise account.

      • Basic information

      • Email activation

      • Select type

      • Information registration

      • Public account information

Enter the company according to the instructions here Information is enough. This time we chose the Certification Service Number option:

Illustration of developing WeChat service account with PHP

In order to authenticate the service number, you need to pay 300 yuan/year, this step is a little more troublesome: financial payment, waiting 7 working days, mailing the invoice, etc.

It should be noted that WeChat’s certification is not official from Tencent, but a third party of its client. This was quite different at the beginning.

Illustration of developing WeChat service account with PHP

After completing the certification, the certification information is as follows (skip the middle step of scanning the company’s business license, scanning and stamping the official seal Authentication protocol and other details):

Illustration of developing WeChat service account with PHP

Authenticated WeChat (the one with the golden check mark is the WeChat developed this time):

                                                  Illustration of developing WeChat service account with PHPIllustration of developing WeChat service account with PHP

Step2: WeChat Documentation & API Learning

WeChat development is the same as learning to use ComponentOne control. The first thing you need to do is to read WeChat’s official documentation, API, and demo sample code. This can greatly reduce the risk of making detours.

Note: I originally planned to read several popular WeChat development books, but later gave up due to time reasons.

Illustration of developing WeChat service account with PHP

Log in to the WeChat backend, click "Developer Center" on the left, and "Developer Documentation" appears on the right , "Online interface debugging tool" is the document and API tool officially provided by WeChat. During the development process, it will be used repeatedly and many times. These two are very important materials.

In the public account "Developer Center", write down the AppID and AppSecret, which will be used many times later.

Illustration of developing WeChat service account with PHP

WeChat’s official document, first read it from top to bottom:

Illustration of developing WeChat service account with PHP

在文档的开始,微信官方就提供了PHP示例代码,下载地址。 且其明确的告之,微信公众号接口只支持80接口.

官方文档写的非常细,如获取access token是基于HTTP请求,用的是GET方式,其他的文档请直接参阅文档

access_token是公众号的全局唯一票据,公众号调用各接口时都需使用access_token。开发者需要进行妥善保存。access_token的存储至少要保留512个字符空间。access_token的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取的access_token失效。

http请求方式: GET
Copy after login
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
Copy after login

Illustration of developing WeChat service account with PHP

<br>
Copy after login
Copy after login
Copy after login
备注:access_token的有效时间是7200s,既需要自行做一个缓存,2小时刷新一次access_token; 我在这里用的是文件的缓存方式,添加了时间戳。
Copy after login
<br>
Copy after login
Copy after login
Copy after login

Step3:开发环境搭建

这节,我们着手搭建环境。

首先选择http://git.oschina.net 搭建源码托管环境,OSC提供了免费的私有项目,配合使用TortoiseGit-1.8.11.0-64bit,使得搭建源码托管环境非常简单。另外,其在国内访问Git速度超快(赞一个!)

接着安装软件,配置电脑开发环境:

    • Windows 8.1 64位 中文版

    • JetBrains PhpStorm 8.0.2

    • SQL Server 2008

    • PHP 5

为了方便测试,和公司网管沟通,把微信的***.gcpowertools.com.cn/ 80端口映射到我的局域网电脑。事后证明,这种本地调试方法非常高效,极大了提高了开发、调试效率。最后,为了方便调试微信数据,需要写log进行日志呈现,这里我使用的是读写文件的方式。

function writeLogBegin($msg = "begin log..............")
Copy after login
{
Copy after login
    $logFile = date('Y-m-d') . '.txt';
Copy after login
    $msg = date('Y-m-d H:i:s') . ' >>> ' . $msg . "\r\n";
Copy after login
    file_put_contents("c:\\log.txt", $msg);
Copy after login
}
Copy after login

 

Step4:微信开发

首先,结合业务特点,规划微信底部的自定义菜单。

Illustration of developing WeChat service account with PHP

小技巧:自定义菜单不用写代码,用微信官方自带的调试页面即可完成。

 

规划好自定义菜单后,POST JSON到微信服务器,可直接使用微信公众平台接口调试工具

Illustration of developing WeChat service account with PHP

保存生成的access_token, 类似如下的文本:

vU2rq8nzdXZWmcS3jO1OAZzRL5dnm3OIlsPF8ZCKHkTGfrG8f87QpwYa4mBpkTvnuy0pQJsfyq_L5xLIqPSoIBIqdsVAaKOuEgBrPpQ4

 

接着选择“自定义菜单”,输入刚才保存的access_token,输入如下的JSON字符串:

{ <br>      "button":[    <br>      {    <br>           "name":"学习中心",    <br>           "sub_button":[    <br>            {    <br>               "type":"click",    <br>               "name":"联系葡萄城",    <br>               "key":"101"    <br>            }]

                                                                                                          "view", <br> "name ": "Latest news", <br> "url": "<br>https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9665cf3fcdaee2f1&redirect_uri=http://www.gcpowertools.com. cn&response_type=code&scope=snsapi_base&state=118#wechat_redirect"<br>                                                                     "name":"latest version", <br> "url ": "<br>https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9665cf3fcdaee2f1&redirect_uri=http://www.gcpowertools.com.cn&response_type=code&scope=snsapi_base&state=118#wechat_redirect"<br>                                                                                                      "key":"102" },                                                                                                                                     }<br>

                                                                                                           "type":"click", <br> "name":"Daily check-in", <br> "key":"104" <br> }, <br> "type":"click" , <br> "name":"Information Query", <br> "key":"105" <br>                                "name":"My post", <br> " key":"106" <br>                                          "key":"107" <br>                                                                                                                                            #https://open. weixin.qq.com/connect/oauth2/authorize?appid=wx9665cf3fcdaee2f1&redirect_uri=http://www.gcpowertools.com.cn&response_type=code&scope=snsapi_base&state=118#wechat_redirect"<br>                                   }] <br>}<br><br><br><br><br><br><br><br> <br><br> Note: After creating <br>custom menu<br>, due to WeChat customers It is cached on the client and takes 24 hours to be displayed on the WeChat client. It is recommended that when testing, you can try to unfollow the public account and follow it again, and you can see the effect after creation. <br>

Next, we proceed with core functional development.

<br>The core of the WeChat service account revolves around the GCDN community, so the "GCDN Community" submenu has 5 secondary menus. Among them, the daily check-in, information query, my posts, and gift redemption functions need to be bound to your own first. <br>GCDN accountGCDN account. <br><br><br>

依据上面的逻辑,绑定GCDN账号是前提环节,故需要开发绑定功能。 绑定功能,做了一个页面,通过a标签跳转,用户在输入用户名、密码后进行GCDN鉴权验证,验证通过存储在表:包含GCDN ID、微信的OpenID,既完成账号绑定。

Illustration of developing WeChat service account with PHP

后面的多个功能,通过这个表,可从微信的OpenID获得GCDN ID,继而可以使用GCDN论坛中的个人信息。

 

每日签到功能

打开论坛页面,在底部可看到目前GCDN使用的引擎较早,是Discuz!NT 3.6.711版本,故X3.1版本中时尚的签到功能是没有的。针对这个遗憾,本次微信开发做了弥补:用户可通过微信的签到完成这个功能。

Illustration of developing WeChat service account with PHP

 

GCDN回帖微信通知

这是另外一个特色功能:无需操作,只需要绑定GCDN账号,当你在GCDN的发帖有人回复时,会自动收到微信通知。

这个功能的开发,主要是为了还GCDNer的一个期待:在《2013年葡萄城控件用户满意度调查》,论坛用户对此类功能呼声很高,“谢谢你们的努力和尽职尽责,我希望GCDN回帖及时些,最好有及时的短信通知功能,省的我时不时的刷新GCDN页面,催促你们!”--某GCDN用户。

 

实现思路如下图所示:

Illustration of developing WeChat service account with PHP

 

微信通知用户,刚开始想的是文本通知,结果发现微信公众号的政策:如果用户未在24小时内主动和微信互动,则无法用文本通知用户。想到另外一个变通的办法,各大银行的余额动态通知功能。接着仔细找微信提供的功能,原来这种功能是“微信模板消息”。

Illustration of developing WeChat service account with PHP

 

这段文档关于微信的模板消息写的很详细:

为了保证用户不受到骚扰,在开发者出现需要主动提醒、通知用户时,才允许开发者在公众平台网站中模板消息库中选择模板,选择后获得模板ID,再根据模板ID向用户主动推送提醒、通知消息。

约花了半天时间,开发出的功能效果看起来还不错(用户是否在24小时内主动联系,均可发送模板消息),截图如下:

Illustration of developing WeChat service account with PHP

如想配置这个功能,通过回复文字指令。

    • 回复"取消提醒": 自动关闭微信通知提醒

    • 回复"开通提醒":自动开通微信通知提醒(需要你绑定GCDN账号)

 

上面的开发过程,用到的PHP的 curl 实现HTTP GET、POST请求的源码:

/**
 * @param $url
 * @param null $data
 * @return mixed
 */
function https_request($url, $data = null)
{
    // 模拟提交数据函数
    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
    curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
    if (!empty($data)) {
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
    }
    curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
    curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回

   

    $tmpInfo = curl_exec($curl); // 执行操作
    if (curl_errno($curl)) {
        echo 'Errno' . curl_error($curl);//捕抓异常
    }
    curl_close($curl); // 关闭CURL会话
    return $tmpInfo; // 返回数据
}
Copy after login

 

雷区:如果你所在电脑有代理,务必添加如下代码:

   //使用网络代理begin
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_PROXY, '192.168.0.1');  //替换代理地址
    curl_setopt($curl, CURLOPT_PROXYPORT, '880');      //替换代理端口
    curl_setopt($curl, CURLOPT_PROXYTYPE, 'HTTP');
    curl_setopt($curl, CURLOPT_PROXYUSERPWD, 'grapecity/r:r'); //替换代理用户名
    //使用网络代理end
Copy after login
<br>
Copy after login
Copy after login
Copy after login

Step5:开发总结

  • 近2个月的开发时间,投入了约1.5人,粗略估算有3个人月开发投入。

  • 少数的几次非控件业务的研发,主要为了方便GCDN社区用户的使用,桥接微信、GCDN。

  • 选择使用PHP脚本语言不错,微信官方用PHP作为默认微信开发脚本,另外PHP开发微信的博客非常多。

  • 完整项目经验很重要:“坑才是大爱!”

坑的定义:有时候没有问题,有时候有问题。100%有问题的,不叫坑,叫bug。

  • Git利器: 协作开发,牛!

  • include_onece This pitfall of path error, PHPStorm provides enough intelligent perception, should be paid attention to.

  • include_onece Use single quotation marks for the path, do not use double quotation marks

  • Teamwork: When people work together, mountains can move. The iteration of WeChat functions is communicated bit by bit.

Related recommendations:

springmvc integrated jfinal WeChat WeChat service account development

The above is the detailed content of Illustration of developing WeChat service account with PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template