Home  >  Article  >  WeChat Applet  >  H5 page custom title, link, description, picture sharing to WeChat friends, Moments, QQ and QQ space

H5 page custom title, link, description, picture sharing to WeChat friends, Moments, QQ and QQ space

越努力越幸运
越努力越幸运Original
2020-05-07 14:52:52119browse

Recently, I encountered a function at work, which requires us to customize the H5 page on our mobile phone to share it with WeChat friends, Moments, QQ and QQ space.

The following is a method I got from Baidu and tested it myself; I will share it with everyone and learn from each other.

Implementation principle: Custom sharing of H5 requires the use of the sharing interface of the WeChat public platform, which is the JSSDK in WeChat web development, [specific documentation: https://developers.weixin. qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html】Use the sharing interface in WeChat’s SDK, as shown in the figure below:

H5 page custom title, link, description, picture sharing to WeChat friends, Moments, QQ and QQ space

Note: The following custom sharing function can only be shared in WeChat's built-in browser; it is not available in other browsers.

# 1. Register a WeChat public account

First we need to open a WeChat public account. The type of public account must be a subscription account or a personal account There is no sharing interface function.

# 2. Activating permissions

After the registration of our official account is completed, we need to log in to the WeChat public platform, go to the development-"interface permissions, and activate the permissions for the sharing interface [Authentication is required to open permissions Enterprise and payment certification], the following picture is the situation that has been certified:

H5 page custom title, link, description, picture sharing to WeChat friends, Moments, QQ and QQ space

# 3. After the interface permission is activated, we need to set a JS interface security domain name for the official account

Log in to the WeChat public platform, go to Settings-"Public Account Settings-"Function Settings, fill in the valid JS interface security domain name [your project access domain name], as shown in the following figure:

H5 page custom title, link, description, picture sharing to WeChat friends, Moments, QQ and QQ space

# 4. After the safe domain name is filled in successfully, you need to configure an IP whitelist

Click on Development-"Basic Settings-"IP Whitelist to fill in a server IP [you IP address of the server where the project is located], the specific reasons will be mentioned below, as shown in the following figure:

H5 page custom title, link, description, picture sharing to WeChat friends, Moments, QQ and QQ space

# 5. The above functions need to be configured in the public account. Completed, let’s start putting the interface into the specific project

## (1)Introduce the JS file

Introduce the following JS file on the page that needs to call the JS interface, (Supports https): http://res.wx.qq.com/open/js/jweixin-1.4.0.js

If you need to further improve service stability, when the above resources are inaccessible, you can Change access: http://res2.wx.qq.com/open/js/jweixin-1.4.0.js (supports https)

## (2) Inject permission verification through the config interface Configuration

All pages that need to use JS-SDK must first inject configuration information, otherwise they will not be able to call

wx.config({
  debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
  appId: '', // 必填,公众号的唯一标识
  timestamp: , // 必填,生成签名的时间戳
  nonceStr: '', // 必填,生成签名的随机串
  signature: '',// 必填,签名
  jsApiList: [] // 必填,需要使用的JS接口列表
});

Among the parameters for the above permission verification,

1. "appId" is the unique identifier of the official account, which can be obtained on the WeChat public platform

H5 page custom title, link, description, picture sharing to WeChat friends, Moments, QQ and QQ space

2. "timestamp", timestamp

3. "nonceStr ", random string, [length should not exceed 32 characters]

4."signature", signature (needs to splice parameters and then encrypt it)

5.jsApiList is a list of JS interfaces, as follows Figure: [Link: https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#62]

H5 page custom title, link, description, picture sharing to WeChat friends, Moments, QQ and QQ space

(3) Generate signature "signature" [a more complicated place]

a. To generate a signature, we need to use several parameters, and then The parameters are concatenated into a string and then encrypted using sha1().

The parameters are: noncestr: random string [This needs to be consistent with the random string in permission verification]

jsapi_ticket: jsapi_ticket is a temporary ticket used by the public account to call the WeChat JS interface. Under normal circumstances, the jsapi_ticket is valid for 7200 seconds and is obtained through access_token.

timestamp: timestamp [This timestamp also needs to be consistent with the timestamp in permission verification, the unit is seconds]

url: The URL of the current web page, excluding # and its following characters

Then concatenate all parameters into one string ,For example:

jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg&noncestr=Wm3WZYTPz0wzccnW×tamp=1414587457&url=http://mp.weixin.qq.com?params=value

然后对上面的字符串进行加密【sha1()函数进行加密】,得到signature。

b.现在来说说怎样获得调用微信调用JS接口的临时票据jsapi_ticke

因为jsapi_ticket的有效期为7200秒,并且需要通过access_token来获取到,所以我们先获取access_token;access_token公众号的一天获取次数有限,2000次,且有效时间为7200秒,所以我们可以考虑每次获取到的access_token放入缓存或者让数据表中,在有效期内反复调用【我是存储到数据表中的】。

下面是我自己写的一个简单类和数据表结构

H5 page custom title, link, description, picture sharing to WeChat friends, Moments, QQ and QQ space

class Wxapi{
    protected $appid;
    protected $appsecret;
 
    /**
     * 构造函数
     * 2019-12-10
     */
    public function __construct($appid,$appsecret){
        $this->appid=$appid;
        $this->appsecret=$appsecret;
        $this->sessionKey_url="https://api.weixin.qq.com/sns/jscode2session";
        $this->accessToken_url="https://api.weixin.qq.com/cgi-bin/token";
        $this->jsapi_ticket_url="https://api.weixin.qq.com/cgi-bin/ticket/getticket";
        $this->qrcodeUrl="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode";
    }
 
    /**
     * 获取access_token
     * 2019-12-10
     *
     * @param string  appid         appid
     * @param string  appsecret     appsecret
     * @param string  tableName     表名(wx_account)
     * @return string token         token
     */
    public function getToken($appid,$appsecret,$tableName){
        $accountInfo = DB::table($tableName)->where('appid',$appid)->where('appsecret',$appsecret)->first();
        $now_time = time();//当前时间戳
        if(empty($accountInfo)){
            return false;
        }
        if($now_time-$accountInfo->access_token_time<7000){
            $token = $accountInfo->access_token;
            return $token;
        }else{
            $get_token_url = $this->accessToken_url."?grant_type=client_credential&appid=".$appid.&#39;&secret=&#39;.$appsecret;
            $getToken_json = curl_get($get_token_url);
            $getToken_arr = json_decode($getToken_json[&#39;output&#39;],true);
            $token = $getToken_arr[&#39;access_token&#39;];
            $arr = [
                &#39;access_token_time&#39;=>time(),
                &#39;access_token&#39;=>$token,
                &#39;updated_at&#39;=>date(&#39;Y-m-d H:i:s&#39;,time())
            ];
            $res = DB::table($tableName)->where(&#39;appid&#39;,$appid)->where(&#39;appsecret&#39;,$appsecret)->update($arr);
            if($res){
                return $token;
            }else{
                return false;
            }
        }
    }
 
    /**
     * 获取jssdk-ticket
     * 2019-12-10
     *
     * @param string  appid         appid
     * @param string  appsecret     appsecret
     * @param string  tableName     表名(wx_account)
     * @return string token         token
     */
    public function getJssdkTicket($appid,$appsecret,$tableName){
        $accountInfo = DB::table($tableName)->where(&#39;appid&#39;,$appid)->where(&#39;appsecret&#39;,$appsecret)->first();
        if(empty($accountInfo)){
            return false;
        }
        $now_time = time();//当前时间戳
        if($now_time-$accountInfo->jsapi_ticket_time<7000){
            $jsapi_ticket = $accountInfo->jsapi_ticket;
            return $jsapi_ticket;
        }else{
            $access_token=$this->getToken($appid,$appsecret,$tableName);
            if(!$access_token){
                return false;
            }
            $get_jsapi_ticket_url = $this->jsapi_ticket_url."?access_token=".$access_token."&type=jsapi";
            $getJssdkTicket_json = curl_get($get_jsapi_ticket_url);
            $getJssdkTicket_arr = json_decode($getJssdkTicket_json[&#39;output&#39;],true);
            $jsapi_ticket = $getJssdkTicket_arr[&#39;ticket&#39;];
            $arr = [
                &#39;jsapi_ticket_time&#39;=>time(),
                &#39;jsapi_ticket&#39;=>$jsapi_ticket,
                &#39;updated_at&#39;=>date(&#39;Y-m-d H:i:s&#39;,time())
            ];
            $res = DB::table($tableName)->where(&#39;appid&#39;,$appid)->where(&#39;appsecret&#39;,$appsecret)->update($arr);
            if($res){
                return $jsapi_ticket;
            }else{
                return false;
            }
        }
    }
}

这边我们的操作是,我们后端获取jsapi_ticket返回给前端,然后前端进行权限验证。

为了方便调试,我们可以在微信开发者工具中进行调试。下载链接:https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html

当页面去调用微信的JSSDK接口时,成功可以看到对应的微信返回数据。

H5 page custom title, link, description, picture sharing to WeChat friends, Moments, QQ and QQ space

如果出现错误,请根据开发文档进行修改:

11H5 page custom title, link, description, picture sharing to WeChat friends, Moments, QQ and QQ space

然后在手机上进行分享,测试是否成功;下面是我成功的操作。

朋友圈分享:

H5 page custom title, link, description, picture sharing to WeChat friends, Moments, QQ and QQ space

微信群组分享:

H5 page custom title, link, description, picture sharing to WeChat friends, Moments, QQ and QQ space

QQ分享:

1H5 page custom title, link, description, picture sharing to WeChat friends, Moments, QQ and QQ space

The above is the detailed content of H5 page custom title, link, description, picture sharing to WeChat friends, Moments, QQ and QQ space. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn