为了实现小程序的长期订阅消息功能,需要前后端的协作。这里将为您提供一个简化的流程及其代码示例。
1. 前端:小程序代码
1.1. 用户登录并获取 code
wx.login({
success: function(res) {
if (res.code) {
// 发送 res.code 到后台换取 openId
getOpenIdFromServer(res.code);
} else {
console.log('登录失败!' + res.errMsg);
}
}
});
1.2. 使用 code
获取 openId
function getOpenIdFromServer(code) {
wx.request({
url: 'https://yourserver.com/get-openid',
method: 'POST',
data: { code: code },
success(res) {
const openId = res.data.openId;
// 保存 openId 或进行其他操作
},
fail(err) {
console.error('请求服务端失败:', err);
}
});
}
1.3. 请求用户订阅
function requestSubscription() {
wx.requestSubscribeMessage({
tmplIds: ['YOUR_TEMPLATE_ID'],
success(res) {
if (res['YOUR_TEMPLATE_ID'] === 'accept') {
// 用户同意了订阅
console.log('订阅成功');
} else {
// 用户拒绝了订阅或发生了其他异常
console.log('订阅失败');
}
},
fail(err) {
console.error('请求订阅失败', err);
}
});
}
2. 后端:PHP 代码
2.1. 使用 code
获取 openId
<?php
$appId = 'YOUR_APP_ID';
$appSecret = 'YOUR_APP_SECRET';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$code = $_POST['code'];
$apiUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=$appId&secret=$appSecret&js_code=$code&grant_type=authorization_code";
$response = file_get_contents($apiUrl);
$data = json_decode($response, true);
if (isset($data['openid'])) {
// 您可以选择存储这个 openId 到数据库
storeOpenId($data['openid']);
echo json_encode(['openId' => $data['openid']]);
} else {
// 错误处理
echo json_encode(['error' => 'Failed to get openId']);
}
}
function storeOpenId($openId) {
// 这里是一个示例,您应该连接到您的数据库并存储 openId
// 例如使用 PDO 或其他库
}
?>
注意:上述代码为简化示例,为了安全性和稳定性,在生产环境中应该处理更多的异常情况,使用更安全的数据库存储方式,并确保所有外部输入都经过适当的验证和清理。
3. 注意事项
- 请确保替换上述代码中的
'YOUR_APP_ID'
、'YOUR_APP_SECRET'
和'YOUR_TEMPLATE_ID'
为您实际的值。 - 本示例假设您有一个可用的数据库连接,并提供了一个
storeOpenId
函数来存储openId
。在实际应用中,您需要实现这个函数并确保openId
的持久化存储。 - 出于安全考虑,不建议直接在前端小程序中存储
openId
。您应该在需要时从服务端获取。 - 在生产环境中,请确保使用HTTPS,因为涉及到的信息是敏感的。