天天看點

微信分享到朋友圈縮略圖功能(php接口)

首先:你得有一個公衆号(訂閱号、服務号),因為需要用到開發者ID

其次:你必須是這個公衆号的開發者,公司公衆号的管理權一般都不在自己手裡(個人的就友善了,但個人的公衆号有很多接口用不了,比如:不能認證、不能支付)

我分享的是個人公衆号

先捋一捋,看看這個功能大概涉及到哪些技術:

1、要分享的文章頁面,需要引入微信接口的sdk

2、調用相關接口之前,需要一個接口配置(注入到sdk的)

3、調用的功能接口,需要在這個配置中提前聲明(這很重要)

本篇我會貼出來自己的代碼

例子:

<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script><!--微信SDK-->

<script>
  /*
   * 注意:
   * 1. 所有的JS接口隻能在公衆号綁定的域名下調用,公衆号開發者需要先登入微信公衆平台進入“公衆号設定”的“功能設定”裡填寫“JS接口安全域名”。
   * 2. 如果發現在 Android 不能分享自定義内容,請到官網下載下傳最新的包覆寫安裝,Android 自定義分享接口需更新至 6.0.2.58 版本及以上。
   */

    // 接口配置
    wx.config({
        debug: true,
        appId: 'wx19511f261b26ccee',
        timestamp: '1527216192',
        nonceStr: 'AXnuEFRrinkXt4t0',
        signature: 'ec77f0163366ea04d5858539f6a6666fd2afe920',
        jsApiList: [
            'onMenuShareTimeline',
            'onMenuShareAppMessage'
        ]
    });

    wx.ready(function () {
        // 分享到朋友圈
        wx.onMenuShareTimeline({
            title: '标題',
            link: 'http://aa.com/vue', // 該連結域名必須與公衆号JS安全域名一緻
            imgUrl: 'http://aa.com/vue/test.png' // 分享圖示
            success: function () {
            }
        });
    
        // 分享給朋友
        wx.onMenuShareAppMessage({
            title: '标題',
            desc: '描述',
            link: 'http://aa.com/vue',
            imgUrl: 'http://aa.com/vue/test.png',
            type: '',    // 分享類型,music、video或link,不填預設為link
            dataUrl: '', // 如果type是music或video,則要提供資料連結,預設為空
            success: function () {
            }
        });
    });
</script>
           

上面的代碼中,這3個值就涉及到背景了,純前端是搞不定的:

timestamp: '1527216192',
nonceStr: 'AXnuEFRrinkXt4t0',
signature: 'ec77f0163366ea04d5858539f6a6666fd2afe920',
           

背景代碼,以php為例:

// http://aa.com/vue/jssdk.php
<?php
class JSSDK {
  private $appId;
  private $appSecret;

  public function __construct($appId, $appSecret) {
    $this->appId = $appId;
    $this->appSecret = $appSecret;
  }

  public function getSignPackage() {
    $jsapiTicket = $this->getJsApiTicket();
    $nonceStr = $this->createNonceStr();
    $timestamp = time();
    $url = ...

    // 代碼省略

    $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
    $signature = sha1($string);

    $signPackage = array(
      "appId"     => $this->appId,
      "nonceStr"  => $nonceStr,
      "timestamp" => $timestamp,
      "url"       => $url,
      "signature" => $signature,
      "rawString" => $string
    );
    return $signPackage; 
  }
?>
           
// http://aa.com/vue/index.php
<?php
require_once "jssdk.php";
$jssdk = new JSSDK("wx19511f261b26ccee", "9992d42e94e38128e0544730b8409012");
$signPackage = $jssdk->GetSignPackage();
?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8"><title>文章标題</title>
</head>
<body>
<p>文章内容</p>
<p><img src="http://aa.com/vue/test.png" alt="test"></p>
</body>
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script>
   wx.config({
   	debug: false,
   	appId: '<?php echo $signPackage["appId"];?>',
   	timestamp: <?php echo $signPackage["timestamp"];?>,
   	nonceStr: '<?php echo $signPackage["nonceStr"];?>',
   	signature: '<?php echo $signPackage["signature"];?>',
   	jsApiList: [
      // 所有要調用的 API 都要加到這個清單中
      'onMenuShareTimeline',
      'onMenuShareAppMessage'
      ]
  });
   wx.ready(function () {
    // 在這裡調用 API
    wx.onMenuShareTimeline({
        title: '文章标題',
        link: 'http://aa.com/vue',
        imgUrl: 'http://aa.com/vue/test.png'
    });
    });
});
</script>
</html>
           

說好的捋一捋~ 不止講了個大概吧...

準備工作 (正式開始):

一、要玩微信開發(公衆号、小程式),肯定有一個雲伺服器(VPS)

1、PHP環境

2、xshell 或 putty,SFTP(SSH)也行

二、登入到公衆号背景,php開發中需要用到的:

1、左側菜單最後一項[開發]->基本配置:

    a)開發者ID(AppID)

    b)開發者密碼(AppSecret)

    c)IP白名單(本機外網IP&網站IP)

2、左側菜單[設定]->公衆号設定:

    a)JS接口安全域名(要分享的文章的頂級域名)

三、官方文檔:

1、微信網頁開發->微信JS-SDK說明文檔

https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115
           

在【目錄】中找到: 3 分享接口

2、擷取access_token

https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140183
           

網頁調試工具,就在這個頁面的底部

四、網頁調試工具

https://mp.weixin.qq.com/debug/cgi-bin/apiinfo?t=index

https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign
           

 注意!!!

使用[網頁調試工具]擷取token很有必要親自操作一遍,這表示你已經十厘清楚這套流程的來龍去脈

微信分享到朋友圈縮略圖功能(php接口)
微信分享到朋友圈縮略圖功能(php接口)

以上兩張截圖,是擷取token的全部過程

因為是get請求,也可以在浏覽器直接檢視(參數就是開發者的appid和secret)

需要注意的是:公衆号->基本配置->IP白名單,必須包含你的外網IP

五、封裝PHP類(功能說明)

1、一共5個函數:getSignPackage()、getAccessToken()、getTicket()、http_url()、getRandCode

2、最終傳回資料的GetSignPackage()方法裡,有兩次需要請求微信伺服器

一次是擷取ACCESS_TOKEN(token)

https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=AppId&secret=Secret
           

另一次是擷取Ticket(票據):

https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi
           

3、簽名算法

簽名生成規則如下:參與簽名的字段包括noncestr(随機字元串), 有效的jsapi_ticket, timestamp(時間戳), url(目前網頁的URL,不包含#及其後面部分) 。對所有待簽名參數按照字段名的ASCII 碼從小到大排序(字典序)後,使用URL鍵值對的格式(即key1=value1&key2=value2…)拼接成字元串string1。這裡需要注意的是所有參數名均為小寫字元。對string1作sha1加密,字段名和字段值都采用原始值,不進行URL 轉義。

// 這裡參數的順序要按照 key 值 ASCII 碼升序排序
 $string = "jsapi_ticket=$jsapi_ticket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
 $signature = sha1($string);
           

簽名用的4個參數:jsapi_ticket、noncestr、timestamp、url

其中,noncestr是包含大寫\小寫\數字的16位随機碼,對應getRandCode()函數

[詳情說明]請看官方文檔:

https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115
           

左側菜單[微信JS-SDK說明文檔]->16 附錄1-JS-SDK使用權限簽名算法

完整的PHP類函數:

<?php

class JSSDK
{
    private $appId;
    private $appSecret;

    public function __construct($appId, $appSecret)
    {
        $this->appId = $appId;
        $this->appSecret = $appSecret;
    }

    public function getSignPackage()
    {
        $jsapi_ticket = $this->getTicket();      // 票據
        $nonceStr = $this->getRandCode();        // 随機碼
        $timestamp = time();                     // 時間戳

        // 注意 URL 一定要動态擷取,不能 hardCode.
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

        // 這裡參數的順序要按照 key 值 ASCII 碼升序排序
        $string = "jsapi_ticket=$jsapi_ticket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        $signature = sha1($string);

        $arr = array(
            'appId' => $this->appId,
            'nonceStr' => $nonceStr,
            'timestamp' => $timestamp,
            'signature' => $signature,
            "url"       => $url,
            "rawString" => $string
        );
        return $arr;
    }

    // 票據
    function getTicket()
    {
        if ($_SESSION['jsapi_ticket'] && $_SESSION['ticket_expire_time'] > time()) {
            $jsapi_ticket = $_SESSION['jsapi_ticket'];
        } else {
            $access_token = $this->getAccessToken();
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" . $access_token . "&type=jsapi";

            $res = $this->http_url($url);
            $arr = json_decode($res);

            $jsapi_ticket = $arr->ticket;
            $_SESSION['jsapi_ticket'] = $jsapi_ticket;// session
            $_SESSION['ticket_expire_time'] = time() + 7200;
        }
        return $jsapi_ticket;
    }

    // Token
    function getAccessToken()
    {
        if ($_SESSION['access_token'] && $_SESSION['token_expire_time'] > time()) {
            return $_SESSION['access_token'];
        } else {
            $appid = $this->appId;
            $appsecret = $this->appSecret;
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $appsecret;

            $res = $this->http_url($url);
            $arr = json_decode($res);

            $access_token = $arr->access_token;
            $_SESSION['access_token'] = $access_token;
            $_SESSION['token_expire_time'] = time() + 7000;
            return $access_token;
        }
    }

    // URL請求
    private function http_url($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }

    // 随機碼
    private function getRandCode($length = 16)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
}
           

轉載于:https://my.oschina.net/u/3398936/blog/1818576