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.

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
2
3
4
$wt = curl_init("https://api.heweather.com/x3/weather?cityid=CN101340101&key=YOUR_KEY");
curl_setopt($wt, CURLOPT_RETURNTRANSFER, 1);
$weatherjson = curl_exec($wt);
curl_close($wt);

Store the city-code mapping in weathercode.json, load it with:

1
2
$jsoncontent = file_get_contents('weathercode.json');
$locationarray = json_decode($jsoncontent, true);

Extract the live conditions with a regex:

1
2
preg_match('/"now":({.*?{.*?}.*?}.*?})/', $weatherjson, $matches);
$weathernow = $matches[1];

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
2
3
4
5
if ($locationcode) {
// fetch weather
} else {
$contentStr = "没有找到这个城市哦~ 请确认城市或区名。示例: 南京天气";
}

References:

  1. 中国天气网 天气预报API 城市ID
  2. 中国天气网天气预报API接口城市代码
  3. 怎么用PHP发送HTTP请求
  4. curl网站开发指南
  5. PHP cURL manual
  6. PHP通过SimpleXML访问xml文档
  7. json_decode
  8. PHP创建和解析JSON数据的方法
  9. 在PHP语言中使用JSON
  10. PHP正则表达式用法