PHP快速获取微信公众号文章短链接,让你的内容更简洁!
优采云 发布时间: 2023-04-29 15:42微信公众号是新时代的信息传播平台,越来越多的人开始关注和使用。而作为一名自媒体人,我们在撰写文章时需要考虑到用户的使用习惯。在微信公众号中,长链接不仅占用篇幅,而且不方便用户分享。因此,本文将介绍如何使用PHP获取微信公众号文章短链接,让你的文章更加简洁、易读。
一、微信公众平台API
要获取微信公众号文章短链接,我们需要先了解微信公众平台提供的API。在微信公众平台开发文档中,我们可以找到相关接口:https://developers.weixin.qq.com/doc/offiaccount/Account_Management/URL_Shortener.html
二、申请微信公众平台接口权限
在使用微信公众平台API之前,我们需要先申请接口权限。具体操作如下:
1.登录微信公众平台开发者中心,进入“开发”->“基本设置”->“开发者ID”,获取AppID和AppSecret。
2.进入“开发”->“接口权限”,勾选“网页服务”和“生成带参数的二维码”,点击“修改”按钮。
3.进入“开发”->“接口权限”->“网页服务”->“网页服务设置”,设置JS接口安全域名。
4.获取access_token。在PHP中,我们可以使用以下代码获取:
php
$url ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appId."&secret=".$appSecret;
$result = file_get_contents($url);
$json = json_decode($result, true);
$access_token =$json['access_token'];
三、获取长链接
在获取短链接之前,我们需要先获取微信公众号文章的长链接。具体操作如下:
1.登录微信公众平台,在左侧菜单中选择“素材管理”->“图文消息”,选择一篇文章,点击右侧的“查看”按钮。
2.在浏览器地址栏中可以看到长链接,复制即可。
四、通过API获取短链接
获取长链接之后,我们可以使用微信公众平台提供的接口生成短链接。具体操作如下:
1.构造请求URL:
php
$url ='https://api.weixin.qq.com/cgi-bin/shorturl?access_token='.$access_token;
2.构造请求参数:
php
$data = array(
'action'=>'long2short',
'long_url'=>$longUrl
);
$data_string = json_encode($data);
3.发送POST请求:
php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length:'. strlen($data_string)
));
$result = curl_exec($ch);
$json = json_decode($result, true);
$shortUrl =$json['short_url'];
五、完整代码
php
<?php
$appId ='your_app_id';
$appSecret ='your_app_secret';
$longUrl ='your_long_url';
$url ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appId."&secret=".$appSecret;
$result = file_get_contents($url);
$json = json_decode($result, true);
$access_token =$json['access_token'];
$url ='https://api.weixin.qq.com/cgi-bin/shorturl?access_token='.$access_token;
$data = array(
'action'=>'long2short',
'long_url'=>$longUrl
);
$data_string = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length:'. strlen($data_string)
));
$result = curl_exec($ch);
$json = json_decode($result, true);
$shortUrl =$json['short_url'];
?>
六、总结
使用PHP获取微信公众号文章短链接,可以让我们的文章更加简洁、易读,提高用户体验。在实际操作中,我们需要先了解微信公众平台API,申请接口权限,获取长链接,然后通过API获取短链接。在代码实现中,我们需要注意参数传递、请求方式、请求头等细节问题。希望本文能对大家有所帮助。
优采云,提供一站式SEO优化服务,让你的网站排名更靠前。详情请访问:www.ucaiyun.