微信公衆平臺開發4-長連接轉短連接口調用實例(含源碼)

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

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

  一.實例調用json

接口說明api

http請求方式:GET服務器

接口調用地址:微信

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

請求參數說明,如表所示:微信公衆平臺

參數curl

是否必須函數

說明

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'];
?>

運行該文件,獲得如圖所示的信息,長連接成功被轉換爲短連接。

相關文章
相關標籤/搜索