iami233
iami233
文章153
标签38
分类4

文章分类

文章归档

为你的网站添加 Do you like me 小组件

为你的网站添加 Do you like me 小组件

应该有人注意到博主在侧边栏添加了一个 Do You Like Me 的小组件,其实我觉得更为简便的方法就是使用 PHP+SQL+AJAX ,但本着折腾+降低成本(白嫖)的想法,用 VercelLeandCloudNode.JS 撸了一个出来。

Node版本

由于 Node.Js 属于半入门状态,所以代码质量不高,但程序终究是以奇怪的方式跑起来了。

项目地址:https://github.com/5ime/likeMe

PHP 版本

由于我是 vercel 托管没有 创建修改 文件的权限,所以说每一次获取 like 数量都会请求 LeanCloud,导致请求数很高。

所以又撸了一个 PHP 版本出来,把 like 数量写入到了 count.dat 文件中,请求时读取 count.dat 点击后更新 count.dat。下面的代码上传到自己的服务器即可。

先使用 composer 安装LeanCloud SDK:

1
composer require leancloud/leancloud-sdk

具体代码如下,参数获取组件调用 请参考 https://github.com/5ime/likeMe/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
// title: Do U Like Me
// update: 2024-05-03
// author: iami233
error_reporting(0);
header('Access-Control-Allow-Origin: *');
header('Content-type: application/json');

require_once("vendor/autoload.php");
use LeanCloud\Query;
use LeanCloud\Client;
use LeanCloud\CloudException;

// 初始化LeanCloud客户端一次,避免每次请求都初始化
initializeLeanCloud();

// 文件名常量
define("COUNT_FILE", "count.dat");

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$response = incrementLikeCount();
} else {
$response = getLikeCount();
}

echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

function initializeLeanCloud() {
// 参数依次为 app-id, app-key, master-key
Client::initialize("你的app-id", "你的app-key", "你的master-key");
// Client::setDebug(true); // 可以开启调试模式查看详细信息
}

function incrementLikeCount() {
$query = new Query("likeCount");
$objectId = "你的objectId"; // 修改为你的objectId
try {
$todo = $query->get($objectId);
$todo->increment("count", 1);
$todo->save();
$count = $todo->get("count");
writeToFile($count);
return [
'code' => 200,
'msg' => 'success'
];
} catch (CloudException $e) {
return [
'code' => 500,
'msg' => $e->getMessage()
];
}
}

function getLikeCount() {
$count = readFromFile();
return [
'code' => 200,
'msg' => 'success',
'data' => [
'count' => $count
]
];
}

function writeToFile($data) {
if ($file = fopen(COUNT_FILE, "w")) {
fwrite($file, $data);
fclose($file);
}
}

function readFromFile() {
if ($file = fopen(COUNT_FILE, "r")) {
$count = fread($file, filesize(COUNT_FILE));
fclose($file);
return $count;
}
return "0";
}
?>
本文作者:iami233
本文链接:https://5ime.cn/doyoulikeme.html
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可