PHP + MySQL micro-channel circle of friends to share by jsapi and other platforms, to achieve set pictures, links

Background to the issue:

Micro-channel development is the application development field a relatively hot plate, based on the public number, micro-channel payment and other development after another, numerous and colorful, and today here based on micro-channel developed another small section within the micro-letter web page sharing to a circle of friends and other platforms flexibility to set link and a small icon (see below) to perform the function of design ideas and code.

problem analysis:

We all know that, for the average browser, can only be shared by sharing the links on this page to others, but can not do flexible control, but as a support for a variety of micro-channel development experience and a good development platform that enables developers who better to set a lot of dynamic content, here to do a detailed analysis for the share in the case of micro-channel page.

ISSUES:

If it wants to support micro-channel sharing, we must first be sure there must be micro-channel developer account, for the previous version, there are many online versions when it comes to micro-channel sharing is the default web crawl inside the first picture <img> tag to share this version is said to be able to be implemented on a long time ago, the current version can not in this way, can only come step by step. In addition Before doing this, the first thing to get appId and appSercert micro-channel public number, if not need to micro-channel platform to apply. Please visit: https: //mp.weixin.qq.com/

Program implementation:

1. First, get through to the temporary appId and appSercert signature within a page, or can not be verified, obtaining signatures need to get access_token and jsapi_ticket two micro-channel information from the server, but the two have a certain expiration date information, while requests frequency can not be too high, it must be stored and expired when it acquired again, this is the reason why use MySQL, where to build a table to store information. This table can be created by some SQL.

CREATE TABLE IF NOT EXISTS `wechat_share_info` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `access_token` varchar(500) COLLATE utf8mb4_bin DEFAULT NULL,
  `jsapi_ticket` varchar(500) COLLATE utf8mb4_bin DEFAULT NULL,
  `add_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin AUTO_INCREMENT=4 ;

2. access_token created the cache table and jsapi_ticket, following the necessary information to the memory through a micro channel which this table, the third step for the front-end, used herein ThinkPHP framework implementation, other similar frame.

/ * 
* Get jsapi sharing signature 
* / 
function getWinChatShareSignature () { 
    $ PageURL = $ _ the POST [ 'URL' ]; 
    date_default_timezone_set ( "Asia / of Shanghai" ); 
    $ Share = D ( 'wechat_share_info') -> Find ();  $ = jsapi_ticket "" ;  // If you have not been to obtain information, add information  IF (isset ($ report this content share! {// get access_token $ getTokenUrl =)) "https://api.weixin.qq.com/cgi-bin /token?grant_type=client_credential&appid=".C('WEI_SHARE_APPID')."&secret=".C('WEI_APP_SECERT ' ); $ tokenContent = file_get_contents ($ getTokenUrl ); $ = tokenContentObj of json_decode ($ tokenContent); // get $ getTicketUrl = jsapi_ticket "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" $ tokenContentObj-> the access_token "of the type = & JSAPI.". ; $ TicketContent = file_get_contents ($ getTicketUrl ); $ = ticketContentObj of json_decode ($ ticketContent ); $ Data [ 'the access_token'] = $ tokenContentObj-> the access_token; $ Data [ 'jsapi_ticket'] = $ ticketContentObj-> Ticket; $ Data [ 'ADD_TIME'] = DATE ( 'Ymd H: I: S' ); // add information D ( 'wechat_share_info') -> the Add ($ Data ); jsapi_ticket = $ $ ticketContentObj-> Ticket;} // if the acquired information, and information is not expired, the information on the use of IF the else ($ Share [ 'jsapi_ticket'] && Time () - strtotime (Share $ [ 'ADD_TIME']) <2 * 3600 ) = $ {$ jsapi_ticket Share [ 'jsapi_ticket' ];} // If the information is out of date, it updates else{ //获取access_token $getTokenUrl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".C('WEI_SHARE_APPID')."&secret=".C('WEI_APP_SECERT'); $tokenContent=file_get_contents($getTokenUrl); $tokenContentObj=json_decode($tokenContent); //获取jsapi_ticket $getTicketUrl="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$tokenContentObj->access_token."&type=jsapi"; $ticketContent=file_get_contents($getTicketUrl); $ticketContentObj=json_decode($ticketContent); $data['access_token']=$tokenContentObj->access_token; $data['jsapi_ticket']=$ticketContentObj->ticket; $data['add_time']=date('Y-m-d H:i:s');// update information D ( 'wechat_share_info') -> where ( "id =% d", $ share [ 'id']) -> save ($ data); $jsapi_ticket=$ticketContentObj->ticket; } $noncestr=substr(md5(date('Y-m-d H:i:s').time()),0,16); $timestamp=time(); $stringSign="jsapi_ticket=".$jsapi_ticket."&noncestr=".$noncestr."×tamp=".$timestamp."&url=".$pageUrl.""; //echo $stringSign; //组装返回结果,供前端使用 $signature=sha1($stringSign); $res['signature']=$signature; $res['noncestr']=$noncestr; $res['timestamp']=$timestamp; echo json_encode($res); } 

Core 3. js-api share the front page of the configuration settings icon would be achieved, place the following code at the bottom of your page, imgUrl custom icon, the icon you want to set into this position.

<! - configuring a micro channel sharing -> 
<Script type = "text / JavaScript" the src = "http://res.wx.qq.com/open/js/jweixin-1.0.0.js"> </ Script > 
<Script type = "text / JavaScript"> 
    var timestamp; // timestamp 
    var noncestr; // random string 
    var signature; // signature 
    var PageURL = window.location.href; 
    var conUrl location.href.split = ( '#') [0 ]; 
    $ .ajax ({ 
        URL: "{: the U-( 'getWinChatShareSignature')}" , 
        Data: { 
            URL: conUrl 
        }, 
        dataType: 'JSON' ,  the async: to false, // set to synchronize acquisition, to avoid thread delay  Method,: 'POST' ,  Success:function (Data) {// set data timestamp =data.timestamp; noncestr = data.noncestr; Signature = data.signature;}}); // share initial configuration wx.config ({Debug: to false , for appId: 'wx63e1ae0f43d8825c' , timestamp: timestamp, nonceStr: noncestr, Signature: Signature, jsApiList: [ "onMenuShareTimeline", "onMenuShareAppMessage", "onMenuShareQQ", "onMenuShareWeibo", "onMenuShareQZone" ]}); // internet sharing configuration wx.ready (function () {wx.onMenuShareTimeline ({title: 'title ', // share the title link: pageUrl, // share links imgUrl: "http: //" + window.location.host + "/Public/sharelogo.png", // Share icon Success: function () {Alert ( " Share success "! );}, the cancel: function () {// the user cancels the callback function to execute after sharing}}); Wx.onMenuShareAppMessage ({title : 'title', // share title desc: 'desc', // share Description link: pageUrl, // share links imgUrl: "http: //" + window.location. host + "/ Public / sharelogo.png" , // icon share type: '', // share type, music, video, or link, do not fill defaults to link dataUrl: '', // if the type is music or video, then to provide data links, default is empty Success: function () {// the user to confirm execution of the callback function to share }, cancel: function () {// the user cancels the execution of the callback function to share }}); wx.onMenuShareQQ ( {title: 'title', // share title desc: 'desc', // share description link: pageUrl, // share links imgUrl: "http: //" + window.location.host + "/Public/sharelogo.png "// Share icon Success: function () {// callback function performed by the user to confirm the share }, the cancel: function () {// callback function to execute when the user cancel Share}}); Wx.onMenuShareWeibo ({title : 'title', // share title desc: 'desc', // share Description link: pageUrl, // share links imgUrl: "http: //" + window.location. host + "/ Public / sharelogo.png" , // share icon Success: function () {// the user to confirm execution of the callback function to share }, cancel: function () {// the user cancels the execution of the callback function to share }} ); wx.onMenuShareQZone ({title: ' title', // share title desc: 'desc', // share description link: pageUrl, // share links imgUrl: "http: //" + window.location.host + " /Public/sharelogo.png ", // share icon Success: function () {// the user to confirm execution of the callback function to share }, cancel: function () {// the user cancels the execution of the callback function to share }}); }); </ script>

4. Open the front-end code below surface corresponding to the page, click on the upper right corner to share a circle of friends and other platforms, look at the effect it!

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

 

From the micro-channel public number: Programming Society

Advanced programmers daily book, please pay attention!

Guess you like

Origin www.cnblogs.com/ai10999/p/11448658.html