Building a WeChat Backend on SAE with PHP
Setup
SAE
Create an empty PHP 5.6 app on Sina App Engine (SAE), enable Git in “Code Management,” and note the app URL—it becomes the callback URL for WeChat.
Register an official account and edit Developer → Basic Configuration:
- URL: the SAE app address
- Token: any string you choose
- EncodingAESKey: optional (start with plaintext mode)
Download the PHP sample from the WeChat docs (http://mp.weixin.qq.com/wiki/8/f9a0b8382e0b77d87b3bcc1ce6fbc104.html), set the TOKEN to match, name the file index.php
, and push it to SAE. Once the callback responds correctly, enable developer mode in the WeChat portal.
Building features
Comment out $wechatObj->valid();
and call $wechatObj->responseMsg();
instead to handle incoming messages.
Weather lookup example
The old China Weather API stopped working, so switch to HeWeather (https://api.heweather.com). After registering for an API key, fetch weather data via cURL:
1 | $wt = curl_init("https://api.heweather.com/x3/weather?cityid=CN101340101&key=YOUR_KEY"); |
Store the city-code mapping in weathercode.json
, load it with:
1 | $jsoncontent = file_get_contents('weathercode.json'); |
Extract the live conditions with a regex:
1 | preg_match('/"now":({.*?{.*?}.*?}.*?})/', $weatherjson, $matches); |
Put it all together inside responseMsg()
—look for keywords ending with “天气”, map the city, call the API, and return the formatted text.
Handle unknown cities gracefully:
1 | if ($locationcode) { |
References: