微信公眾平台開發4-長鏈接轉短鏈接口調用實例(含源碼)


微信公眾平台開發-access_token獲取及應用(含源碼)
作者: 孟祥磊-《微信公眾平台開發實例教程》

  將一條長鏈接轉成短鏈接。開發者用於生成二維碼的原鏈接(商品、支付二維碼等)太長導致掃碼速度和成功率下降,將原長鏈接通過此接口轉成短鏈接再生成二維碼將大大提升掃碼速度和成功率。

  一.實例調用

接口說明

http請求方式:GET

接口調用地址:

https://api.weixin.qq.com/cgi-bin/shorturl?access_token=ACCESS_TOKEN

請求參數說明,如表所示:

參數

是否必須

說明

access_token

調用接口憑證

action

此處填long2short,代表長鏈接轉短鏈接

long_url

需要轉換的長鏈接,支持http://、https://、weixin://wxpay 格式的url

返回說明:

正常情況下,微信會返回JSON數據包給公眾號,如下所示:

{"errcode":0,"errmsg":"ok","short_url":"http:\/\/w.url.cn\/s\/AvCo6Ih"}

返回信息參數說明,如表所示:

參數

說明

errcode

錯誤碼。

errmsg

錯誤信息。

short_url

短鏈接。

使用程序調用接口獲取:

<?php
/*
 *微信長鏈接轉短鏈接
*/
require('wei_function.php');
$appid="wx78478e595939c538";
$secret="5540e8ccab4f71dfad752f73cfb85780";
$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret."";
$output=getdata($url);
$tokenarr=(array)json_decode($output);
$token=$tokenarr['access_token'];
$date='{"action":"long2short","long_url":"https://item.jd.com/12041625.html"}';
$shorturl="https://api.weixin.qq.com/cgi-bin/shorturl?access_token=".$token."";
$shortarr=(array)json_decode(getshort($date,$shorturl));
echo $shortarr['short_url'];

function sendcontent($date, $url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $date);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}
?>

²代碼解析

require('wei_function.php');包含wei_function.php,使用getdata()函數,獲取到access_token后,我們需要將指定數據發送到對應網址服務器,然后獲取服務器返回的數據。

$date='{"action":"long2short","long_url":"http://www.jikexueyuan.com/course/1578.html"}';

為需要發送的數據,格式為JSON,這里轉換的一個長鏈接為:

https://item.jd.com/12041625.html

將數據發送到:$shorturl="https://api.weixin.qq.com/cgi-bin/shorturl?access_token=".$token."";

這里除了getdata()函數外,增加了一個sendcontent()的函數,該函數與getdata()不同的是,它除向服務器發送鏈接請求外,還可以發送單獨的數據到對方服務器,對方服務器再根據所發送的數據,返回對應的結果。

同樣將sendcontent()函數寫到wei_function.php文件中,此時wei_function.php文件內的函數分別有object_array()、get_weather()、getdata()、以及sendcontent(),該文件見《微信公眾平台開發實例一書》第95頁,優化后的代碼:

<?php
/*
 *微信長鏈接轉短鏈接
*/
require('wei_function.php');
$appid="wx78478e595939c538";
$secret="5540e8ccab4f71dfad752f73cfb85780";
$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret."";
$output=getdata($url);

$tokenarr=(array)json_decode($output);
$token=$tokenarr['access_token'];
//發送xml數據
$date='{"action":"long2short","long_url":"https://item.jd.com/12041625.html"}';
//長鏈接轉短鏈接接口地址
$shorturl="https://api.weixin.qq.com/cgi-bin/shorturl?access_token=".$token."";
$shortarr=(array)json_decode(sendcontent($date,$shorturl));
echo $shortarr['short_url'];
?>

運行該文件,得到如圖所示的信息,長鏈接成功被轉換為短鏈接。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM