Use javascript to obtain the internal fields of wx. config for WeChat sharing, and use wx. config for sharing.

Source: Internet
Author: User
Tags php server

Javascript obtains the internal fields of wx. config for sharing. wx. config for sharing.

Background
When sharing development, our general process is

<? Php require_once "jssdk. php"; $ jssdk = new JSSDK ("yourAppID", "yourAppSecret"); $ signPackage = $ jssdk-> GetSignPackage ();?> <! DOCTYPE html> 

The above is a PHP file. A major drawback of such code is that the front and back ends are not separated from each other, and the other is that hybrid writing is not very beautiful. Therefore, we need to separate PHP from HTML, to implement the sharing function, you must first call the jssdk Api to obtain the configuration parameters, which must be obtained through the php background language, and then configure these parameters on wx. config, in wx. you must introduceHttp://res.wx.qq.com/open/js/jweixin-1.0.0.jsThen you can write the shared function. Their dependency is that wx. config requires parameters in the js library and config, and shares the dependency on wx. config.
So the most important thing is to separate the configuration parameters of php and obtain them separately.

Solution
Write the PHP code that gets the configuration parameters as an interface and call ajax in js to get the parameters and convert them to objects. Then, use the callback function to plug the parameters obtained by ajax into wx. config.

Code structure and functions


  • Index.html page entry
  • Weixin. php server obtains configuration parameters
  • Configdata. php converts configuration into an excuse to output
  • Getconfig. js use ajax to get configdata. php Data
  • Share. js share callback
  • Webpack. config. js webpack configuration file
  • After index. js is packaged, the final html calls the js File

Index.html static file

<! DOCTYPE html> 

Configdata. php backend obtains the configuration parametersNote that the url should be written into the url of the page to be shared. Otherwise, the invalid signature error will be reported.

<? Phpclass JSSDK {private $ appId; private $ appSecret; public function _ construct ($ appId, $ appSecret) {$ this-> appId = $ appId; $ this-> appSecret = $ appSecret;} public function getSignPackage () {$ jsapiTicket = $ this-> getJsApiTicket (); $ url = "http: // $ _ SERVER [HTTP_HOST] $ _ SERVER [REQUEST_URI] "; $ timestamp = time (); $ nonceStr = $ this-> createNonceStr (); // here, the parameter order is in ascending order of the key value ASCII code $ string = "jsapi_ti Cket = $ 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;} private function createNonceStr ($ length = 16) {$ chars = "signature 3456789 "; $ str =" "; for ($ I = 0; $ I <$ length; $ I ++) {$ str. = substr ($ chars, mt_rand (0, strlen ($ chars)-1), 1) ;}return $ str ;} private function getJsApiTicket () {// jsapi_ticket should be globally stored and updated. The following code is written to the file as an example $ data = json_decode (file_get_contents ("jsapi_ticket.json ")); if ($ data-> expire_time <time () {$ accessToken = $ this-> getAccessToken (); $ url = "https://api.weixin.qq.com/cgi-bin/ticket/gettic Ket? Type = jsapi & access_token = $ accessToken "; $ res = json_decode ($ this-> httpGet ($ url); $ ticket = $ res-> ticket; if ($ ticket) {$ data-> expire_time = time () + 7000; $ data-> jsapi_ticket = $ ticket; $ fp = fopen ("jsapi_ticket.json", "w "); fwrite ($ fp, json_encode ($ data); fclose ($ fp) ;}} else {$ ticket = $ data-> jsapi_ticket;} return $ ticket ;} private function getAccessToken () {// access_token should be stored and updated globally. The following code uses Example $ data = json_decode (file_get_contents ("access_token.json"); if ($ data-> expire_time <time () {$ url = "https://api.weixin.qq.com/cgi-bin/token? Grant_type = client_credential & appid = $ this-> appId & secret = $ this-> appSecret "; $ res = json_decode ($ this-> httpGet ($ url )); $ access_token = $ res-> access_token; if ($ access_token) {$ data-> expire_time = time () + 7000; $ data-> access_token = $ access_token; $ fp = fopen ("access_token.json", "w"); fwrite ($ fp, json_encode ($ data); fclose ($ fp );}} else {$ access_token = $ data-> access_token;} return $ access_token;} private function httpGet ($ url) {$ curl = curl_init (); curl_setopt ($ curl, CURLOPT_RETURNTRANSFER, true); curl_setopt ($ curl, CURLOPT_TIMEOUT, 500); curl_setopt ($ curl, CURLOPT_URL, $ url); $ res = curl_exec ($ curl); curl_close ($ curl ); return $ res ;}}

Weixin. php format the configuration parameters

 <?php require_once "weixin.php"; $jssdk = new JSSDK(appId, appSecretecret); $signPackage = $jssdk->GetSignPackage();  class Config{  var $appId;  var $timestamp;  var $nonceStr;  var $signature;  var $url; }   $config = new Config();   $config -> appId = $signPackage["appId"];  $config -> timestamp = $signPackage["timestamp"];  $config -> nonceStr = $signPackage["nonceStr"];  $config -> signature = $signPackage["signature"]; $config -> url = $signPackage["url"];   echo json_encode($config);?>

Getconfig. js use ajax to obtain interface data (configuration parameters)

var getConfig = function(callback) { $.ajax({ url: "http://www.goxueche.com/api/configdata.php", type: "get", success: function(data) {  callback(data); } })}module.exports = getConfig;

Share. js sharing functions

Var getWeixincofig = require (". /getconfig. js "); getWeixincofig (invalid Weixin); function construct Weixin (data) {var data = JSON. parse (data); console. log (data); window. wx. config ({debug: true, appId: data. appId, timestamp: data. timestamp, nonceStr: data. nonceStr, signature: data. signature, jsApiList: ['checkjsapi ', 'onmenusharetimeline', 'onmenushareappmessage']}); wxShare ();} function wxShare () {// check whether an api is generated Valid wx. ready (function () {wx. checkJsApi ({jsApiList: ['getnetworktype', 'previewimage'], success: function (res) {console. log (JSON. stringify (res) ;}}); // share it with your friend wx. onMenuShareAppMessage ({title: 'quxue Che-Internet driving schools with temperature ', desc: 'quxue Che if you want to learn it! ', Link: 'http: // www.goxueche.com', imgUrl: 'http: // www.goxueche.com/....png'}); // share it with your friends. onMenuShareTimeline ({title: 'quxue Che-Internet driving schools with temperature ', desc: 'qushi Che if you want to learn it! ', Link: 'http: // www.goxueche.com', imgUrl: 'http: // www.goxueche.com/....png '});});}

Webpack. config. js

var webpack = require('webpack'); module.exports = {  entry: { index: './share.js', }, output: { path: './', filename: '[name].js' }};

The above is all the content of this article, hoping to help you learn.

Articles you may be interested in:
  • Examples of common share components implemented by js
  • Javascript allows you to modify the title and content of a shared object.
  • Javascript sharing
  • Based on js, how to send friends to moments and Weibo
  • JavaScript code sharing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.