微信公众号开发者平台提供了短网址生成API,最终生成的短网址为w.url.cn,下面是详细代码。官方文档https://developers.weixin.qq.com/doc/offiaccount/Account_Management/URL_Shortener.html请求参数access_tokenaction此处填写long2short,代表长链接转短链接long_url需要转换的原始链接HTTPPOST请求URLhttps:///api.weixin.qq.com/cgi-bin/shorturl?access_token=ACCESS_TOKEN请求流程1、获取本地缓存的access_token。如果过期,请重新获取。如果还没有过期,直接使用缓存的access_token2。构建请求参数,发起POST请求3、获取短网址代码appid和appsecret申请微信公众号开发测试账号,申请地址:http://mp.weixin.qq.com/debug...$result['expires']){$data=array();$data['access_token']=getNewToken();$data['过期']=时间()+7000;$jsonStr=json_encode($data);$fp=fopen("access_token.json","w");fwrite($fp,$jsonStr);fclose($fp);返回$data['access_token'];}else{返回$result['access_token'];}}//获取新的access_token函数getNewToken($appid,$appsecret){global$appid;全局$appsecret;$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credessential&appid=".$appid."&secret=".$appsecret."";$access_token_Arr=file_get_contents($url);$token_jsonarr=json_decode($access_token_Arr,true);return$token_jsonarr["access_token"];}//获取长链接$long_url=trim($_GET["long_url"]);//过滤if(empty($long_url)){$result=array("result"=>"101","msg"=>"Please传入长链接");}elseif(strpos($long_url,'http')!==false){//初始化CURL$ch=curl_init();//请求地址curl_setopt($ch,CURLOPT_URL,'https://api.weixin.qq.com/cgi-bin/shorturl?access_token='.getToken());curl_setopt($ch,CURLOPT_CUSTOMREQUEST,"POST");$postdata='{"action":"long2short","long_url":"'.$long_url.'"}';curl_setopt($ch,CURLOPT_POSTFIELDS,$postdata);//检查认证证书来源curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);//从证书检查是否SSL加密算法存在curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);//获取的信息以文件流的形式返回i而不是直接输出curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);//发起请求$dwzStr=curl_exec($ch);//解析数据$arr_dwzStr=json_decode($dwzStr,true);$dwz=$arr_dwzStr["short_url"];//关闭请求curl_close($ch);//返回结果$result=array("result"=>"100","msg"=>"解析成功","dwz"=>$dwz);}else{$result=array("result"=>"102","msg"=>"长链接无效");}//返回JSONechojson_encode($result,JSON_UNESCAPED_UNICODE);?>生成示例{"result":"100","msg":"生成成功","dwz":"https:\/\/w.url.cn\/s\/AF5p0UM"}体验http://www.likeyunba.com/api/wurl/?long_url=longlink作者:TANKING日期??:2020-09-18网址:http://www.likeyun.cn微信:face6009
