In the actual process, we will have such a scene, that is, when sending SMS, it needs to be embedded in our website, but the website is very long.

If you usually operate on your mobile phone, you can search for “short link generation” in wechat mini program

Or scan the small program QR code at the bottom of the article to use it

However, the text message content, can only be about 70 words, more than two will be sent, but this is not what we want. Therefore, we need to convert long links to short links. Frequently, you can see the share address of Sina Weibo. Now, how do you do that?Copy the code

Sina provides an API for converting long links to short links, which can be converted to short links in the format of t.cn/xxx.

(T.cn sina has stopped service, temporarily unavailable, if you want to use the official sina)

Baidu provides an API for converting long links to short links, which can convert long links to short links in dwz.cn/xxx format.

Baidu old interface will be out of service in the near future, please use the new interface

Baidu old interface: https://dwz.cn/admin/create (short urls generated interface) baidu new interface: https://dwz.cn/admin/v2/create (short urls generated interface)Copy the code

Baidu API :(not included links need to be included to generate)

<? php$host = 'https://dwz.cn';
    $path = '/admin/v2/create';
    $url = $host . $path;
    $method = 'POST';
    $content_type = 'application/json'; // TODO: Sets the Token$token = 'your Token'; // TODO: set the long url to be registered$bodys = array('url'= >'Your long url'); / / configuration headers$headers = array('Content-Type:'.$content_type.'Token:'.$token); // Create a connection$curl = curl_init($url);
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_FAILONERROR, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($bodys)); // Send the request$response = curl_exec($curl);
    curl_close($curl); // read response var_dump($response); ? >Copy the code

Sample response results

{
    "Code": 0."ShortUrl": "https://dwz.cn/de3rp2Fl"."LongUrl": "http://www.baidu.com"."ErrMsg": ""
}Copy the code

Response Parameter Description

field type instructions
Code int 0: returns the short URL normally
int -1: failed to generate the short URL
int -2: The long URL is invalid
int -3: Long URLS have security risks
int -4: Failed to insert the long URL into the database
int -5: Long urls are in the blacklist and are not allowed to register
ShortUrl string Short url
LongUrl string Long Url (original url)
ErrMsg string The error message

Sina API:

http://api.t.sina.com.cn/short_url/shorten.xml http://api.t.sina.com.cn/short_url/shorten.json (return result is a JSON format) (Return result in XML format)Copy the code

Request parameters:

Source Indicates the AppKey assigned when applying for an application and the unique identity of the application when invoking the interface.

Url_long Long links for conversion, URLencoded, up to 20.

Multiple URL parameters need to be requested in the following manner: url_long= AAa&url_long = BBB

Create source method

1. Access open.weibo.com/ and choose Micro Connection > Website Access.

2. Click Add Now to create an application, enter the name of the application, and click Create.

3. After successful creation, AppKey is the value of the source parameter and can be used to request short links.

<? php namespace App\Services; Class ShortUrlService {/** ** call sina interface to convert long link to short link * @param string$sourceApplication of AppKey * @ param array | string$urlLongLong link that supports multiple conversions (urlencode needs to be executed first) * @return array
     */
    public static function getSinaShortUrl($source.$urlLong) {// Check parametersif(empty($source) || !$urlLong) {return false; } // The string is converted to an arrayif(! is_array($urlLong)) {$urlLong = array($urlLong); } // concatenate the urL_long parameter request format$url_param = array_map(function($value) {return '&url_long='.urlencode($value);
        }, $urlLong);
        $url_param = implode(' '.$url_param); // Sina generates a short link interface$api = 'http://api.t.sina.com.cn/short_url/shorten.json'; / / request url$request_url = sprintf($api.'? source=%s%s'.$source.$url_param);
        $result= array(); // Execute the request$ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $request_url);
        $data = curl_exec($ch);
        if($error=curl_errno($ch)) {return false;
        }
        curl_close($ch);
        $result = json_decode($data.true);
        return $result; }}Copy the code

AppKey below is the public API, temporarily available. If invalid, register sina developer account can

$source = config('app.sina');Copy the code

Single link conversion

$urlLong = config('app.url');

$shortUrl = ShortUrlService::getSinaShortUrl($source.$urlLong);Copy the code

Returns the result

array:1 [
  0 => array:3 [
    "url_short"= >"http://t.cn/*******"
    "url_long"= >"http://***********.com/#/***********"
    "type"= > 0]]Copy the code

Multiple link conversion

$urlLong = [
            'http://www.***.com/article/1.html'.'http://www.***.com/article/2.html'.'http://www.***.com/index.html'
        ];

$shortUrl = ShortUrlService::getSinaShortUrl($source.$urlLong);Copy the code

Returns the result

array:3 [
  0 => array:3 [
    "url_short"= >"http://t.cn/RD12"
    "url_long"= >"http://www.***.com/article/1.html"
    "type" => 0
  ]
  1 => array:3 [
    "url_short"= >"http://t.cn/RD134KV"
    "url_long"= >"http://www.***.com/article/2.html"
    "type" => 0
  ]
  2 => array:3 [
    "url_short"= >"http://t.cn/RA8u231F"
    "url_long"= >"http://www.***.com/index.html"
    "type"= > 0]]Copy the code

Through the above method, it is very easy to achieve the function of generating short link urls with PHP.

Project source code contains short connection generation API interface: github.com/WXiangQian/…

Additional small program QR code:

​​​​