JavaScript get wx.config inner field solve micro-credit sharing _javascript Tips

Source: Internet
Author: User
Tags curl php class php server ticket

Background
Our usual process for micro-credit sharing development is

 <?php require_once "jssdk.php";
 $JSSDK = new Jssdk ("Yourappid", "Yourappsecret"); $signPackage = $jssdk->getsignpackage ();?> <! DOCTYPE html>  

Above is a PHP file, a big drawback of such code is that the front and back end of the decoupling is too high, and then the mixed write is not very beautiful, so we want to let PHP and HTML separation, to achieve the sharing function, the first is to invoke the JSSDK API to obtain configuration parameters, This must be obtained through the PHP background language, and then configure these parameters in Wx.config, before wx.config to introduce http://res.wx.qq.com/open/js/jweixin-1.0.0.js then you can write the function of sharing, their dependency is wx.config need JS Library and config internal parameters, share dependencies wx.config
So the most important thing is to separate the configuration parameters of PHP to get it alone

Solution
Write PHP to get configuration parameters as an interface, use Ajax calls in JS, get parameters and convert to objects, and then plug the AJAX-acquired parameters into Wx.config via callback function

Code Structure and function


    • Index.html Page Entry
    • weixin.php server-side Get configuration parameters
    • configdata.php configuration to excuse output
    • Getconfig.js use Ajax to get configdata.php data
    • Share.js Share Callback Letter
    • Webpack.config.js webpack configuration file
    • Index.js Final HTML Call JS file after package

index.html html static file

<! DOCTYPE html>
 
 

configdata.php Background to get configuration parameters Note that the URL is to write the URL of its own share of the page, or you will report invalid signature error

 <?php class Jssdk {private $appId;

 Private $appSecret;
 Public function __construct ($appId, $appSecret) {$this->appid = $appId;
 $this->appsecret = $appSecret;
 The Public Function Getsignpackage () {$jsapiTicket = $this->getjsapiticket ();
 $url = "Http://$_server[http_host]$_server[request_uri]";
 $timestamp = time ();

 $NONCESTR = $this->createnoncestr (); Here the order of the parameters is sorted according to the key value of the ASCII code ascending $string = "jsapi_ticket= $jsapiTicket &noncestr= $nonceStr &timestamp= $timestamp &

 Amp;url= $url ";

 $signature = SHA1 ($string); $signPackage = Array ("AppId" => $this->appid, "Noncestr" => $nonceStr, "timestamp" => $timestamp, "url" =
 > $url, "signature" => $signature, "rawstring" => $string); 
 return $signPackage; The Private function createnoncestr ($length =) {$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456
 789 ";
 $str = ""; for ($i = 0; $i < $length; $i + +) {$str. = substr ($chars, Mt_rand (0, strlen ($chars)-1), 1);
 return $str; The Private Function Getjsapiticket () {//jsapi_ticket should be stored and updated globally, with the following code 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/getticket?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; The Private Function Getaccesstoken () {//Access_token should be stored and updated globally, with the following code written to the file as an 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-&GT;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 output

 <?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 get 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 Share function

 var Getweixincofig = require ("./getconfig.js"); Getweixincofig (shareweixin);
 function Shareweixin (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 (); The function Wxshare () {//detects whether the API is in effect Wx.ready (function () {Wx.checkjsapi ({jsapilist: [' getnetworktype ', ' Previewima
 GE '], success:function (res) {Console.log (json.stringify (res));
 }
 }); Share to Friends Wx.onmenushareappmessage ({title: ' Fun Learning car-have the temperature of the internet Driving School ', desc: ' Want to learn the car, learn the fun car! ', Link: ' http://www.goxueche.com ', Imgur
 
 L: ' Http://www.goxueche.com/....png '}); Share to the circle of Friends Wx.onmenusharetimeline ({title: ' Fun Learning car-have the temperature of the internet Driving School ', desc: ' Want to learn the car, learn the fun car! ', 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 '
 }
};

This article has been organized into the "JavaScript micro-Credit Development Skills Summary", welcome to learn to read.

For everyone to recommend now more attention than the micro-letter Program Tutorial: "Micro-letter Small Program Development tutorial" Small series for everyone carefully organized, hope like.

The above is the entire content of this article, I hope to help you learn.

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.