php一个文件搞定微信jssdk配置


Posted in PHP onDecember 12, 2016

php一个文件搞定微信jssdk配置:

包括缓存,包括https通讯,获取微信access_token,签名什么的都有。但是防范性编程做得比较少,商业用的话,需要完善下代码。

使用姿势

^ajax(Common.ServerUrl + "GetWX.php", {
 data: {
  Type: "config",
  url: location.href.split('#')[0]
 },
 dataType: 'json',
 type: 'get',
 timeout: 5000,
 success: function(data) {
  wx.config({
   debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
   appId: '……', // 必填,公众号的唯一标识
   timestamp: data.timestamp, // 必填,生成签名的时间戳
   nonceStr: data.nonceStr, // 必填,生成签名的随机串
   signature: data.signature, // 必填,签名,见附录1
   jsApiList: ["getLocation"] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
  });
 }
})
wx.ready(function() {
 wx.getLocation({
  type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
  success: function(res) {
   var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
   var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。
   plus2.storage.setItem("latitude", latitude);
   plus2.storage.setItem("longitude", longitude);
  }
 });
});

服务端

GetWX.php

<?php
 include "lib/Cache.php";
 define($APPID, "……");
 define($SECRET, "……")
 if($_GET['Type'] == "access_token"){
//  echo getAccess_token();
 }
 else if($_GET['Type'] == "jsapi_ticket"){
//  echo getJsapi_ticket();
 }
 else if($_GET['Type'] == "config"){
  $jsapi_ticket = getJsapi_ticket();
  $nonceStr = "x".rand(10000,100000)."x"; //随机字符串
  $timestamp = time(); //时间戳
  $url = $_GET['url'];
  $signature = getSignature($jsapi_ticket,$nonceStr, $timestamp, $url);

  $result = array("jsapi_ticket"=>$jsapi_ticket, "nonceStr"=>$nonceStr,"timestamp"=>$timestamp,"url"=>$url,"signature"=>$signature);
  echo json_encode($result);
 }

 function getSignature($jsapi_ticket,$noncestr, $timestamp, $url){
  $string1 = "jsapi_ticket=".$jsapi_ticket."&noncestr=".$noncestr."×tamp=".$timestamp."&url=".$url;
  $sha1 = sha1($string1);
  return $sha1;
 }

 function getJsapi_ticket(){
  $cache = new Cache();
  $cache = new Cache(7000, 'cache/'); //需要创建cache文件夹存储缓存文件。
  //从缓存从读取键值 $key 的数据
  $jsapi_ticket = $cache -> get("jsapi_ticket");
  $access_token = getAccess_token();
  //如果没有缓存数据
  if ($jsapi_ticket == false) {
   $access_token = getAccess_token();
   $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket'; 
   $data = array('type'=>'jsapi','access_token'=>$access_token); 
   $header = array(); 
   $response = json_decode(curl_https($url, $data, $header, 5)); 
   $jsapi_ticket = $response->ticket;
   //写入键值 $key 的数据
   $cache -> put("jsapi_ticket", $jsapi_ticket);
  }
  return $jsapi_ticket;
 }

 function getAccess_token(){
  $cache = new Cache();
  $cache = new Cache(7000, 'cache/');
  //从缓存从读取键值 $key 的数据
  $access_token = $cache -> get("access_token");

  //如果没有缓存数据
  if ($access_token == false) {
   $url = 'https://api.weixin.qq.com/cgi-bin/token'; 
   $data = array('grant_type'=>'client_credential','appid'=>$APPID,'secret'=>$SECRET); 
   $header = array();

   $response = json_decode(curl_https($url, $data, $header, 5)); 
   $access_token = $response->access_token;
   //写入键值 $key 的数据
   $cache -> put("access_token", $access_token);
  }
  return $access_token;
 }

 /** curl 获取 https 请求 
 * @param String $url 请求的url 
 * @param Array $data 要?送的?? 
 * @param Array $header 请求时发送的header 
 * @param int $timeout 超时时间,默认30s 
 */ 
 function curl_https($url, $data=array(), $header=array(), $timeout=30){ 
  $ch = curl_init(); 
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查 
  curl_setopt($ch, CURLOPT_URL, $url); 
  curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 
  curl_setopt($ch, CURLOPT_POST, true); 
  curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); 
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
  curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);

  $response = curl_exec($ch);

  if($error=curl_error($ch)){ 
  die($error); 
  }

  curl_close($ch);

  return $response;

 } 
?>

Cache.php
不知道哪位写的源代码~

<?php
class Cache {
 private $cache_path;
 //path for the cache
 private $cache_expire;
 //seconds that the cache expires

 //cache constructor, optional expiring time and cache path
 public function Cache($exp_time = 3600, $path = "cache/") {
  $this -> cache_expire = $exp_time;
  $this -> cache_path = $path;
 }

 //returns the filename for the cache
 private function fileName($key) {
  return $this -> cache_path . md5($key);
 }

 //creates new cache files with the given data, $key== name of the cache, data the info/values to store
 public function put($key, $data) {
  $values = serialize($data);
  $filename = $this -> fileName($key);
  $file = fopen($filename, 'w');
  if ($file) {//able to create the file
   fwrite($file, $values);
   fclose($file);
  } else
   return false;
 }

 //returns cache for the given key
 public function get($key) {
  $filename = $this -> fileName($key);
  if (!file_exists($filename) || !is_readable($filename)) {//can't read the cache
   return false;
  }
  if (time() < (filemtime($filename) + $this -> cache_expire)) {//cache for the key not expired
   $file = fopen($filename, "r");
   // read data file
   if ($file) {//able to open the file
    $data = fread($file, filesize($filename));
    fclose($file);
    return unserialize($data);
    //return the values
   } else
    return false;
  } else
   return false;
  //was expired you need to create new
 }

}
?>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

PHP 相关文章推荐
php 防止单引号,双引号在接受页面转义
Jul 10 PHP
php visitFile()遍历指定文件夹函数
Aug 21 PHP
php中函数的形参与实参的问题说明
Sep 01 PHP
第4章 数据处理-php正则表达式-郑阿奇(续)
Jul 04 PHP
ThinkPHP实现将本地文件打包成zip下载
Jun 26 PHP
php中opendir函数用法实例
Nov 15 PHP
PDO防注入原理分析以及注意事项
Feb 25 PHP
PHP中iconv函数知识汇总
Jul 02 PHP
PHP实现多级分类生成树的方法示例
Feb 07 PHP
PHP实现双链表删除与插入节点的方法示例
Nov 11 PHP
PHP convert_cyr_string()函数讲解
Feb 13 PHP
Yii框架中使用PHPExcel的方法分析
Jul 25 PHP
php自定义扩展名获取函数示例
Dec 12 #PHP
DWZ+ThinkPHP开发时遇到的问题分析
Dec 12 #PHP
php中引用&amp;的用法分析【变量引用,函数引用,对象引用】
Dec 12 #PHP
简单谈谈PHP中的Reload操作
Dec 12 #PHP
php的laravel框架快速集成微信登录的方法
Dec 12 #PHP
php 遍历目录,生成目录下每个文件的md5值并写入到结果文件中
Dec 12 #PHP
php+ajax+json 详解及实例代码
Dec 12 #PHP
You might like
PHP接收json 并将接收数据插入数据库的实现代码
2015/12/01 PHP
PHP简单实现DES加密解密的方法
2016/07/12 PHP
如何离线执行php任务
2017/02/21 PHP
thinkphp5.0自定义验证规则使用方法
2017/11/16 PHP
PHP仿tp实现mvc框架基本设计思路与实现方法分析
2018/05/23 PHP
Extjs学习笔记之七 布局
2010/01/08 Javascript
javascript中的对象创建 实例附注释
2011/02/08 Javascript
复制js对象方法(详解)
2013/07/08 Javascript
jquery获取一组checkbox的值(实例代码)
2013/11/04 Javascript
利用js动态添加删除table行的示例代码
2013/12/16 Javascript
分享五个有用的jquery小技巧
2015/10/08 Javascript
JavaScript数据类型学习笔记分享
2016/09/01 Javascript
js自定义QQ菜单效果
2017/01/10 Javascript
Angular 4依赖注入学习教程之组件服务注入(二)
2017/06/04 Javascript
Vue组件选项props实例详解
2017/08/18 Javascript
Vue2几种常见开局方式详解
2017/09/09 Javascript
vue-router 路由基础的详解
2017/10/17 Javascript
vue添加axios,并且指定baseurl的方法
2018/09/19 Javascript
深入理解Puppeteer的入门教程和实践
2019/03/05 Javascript
IntelliJ IDEA编辑器配置vue高亮显示
2019/09/26 Javascript
vue从零实现一个消息通知组件的方法详解
2020/03/16 Javascript
pyqt4教程之实现windows窗口小示例分享
2014/03/07 Python
python实现通过代理服务器访问远程url的方法
2015/04/29 Python
解决pycharm界面不能显示中文的问题
2018/05/23 Python
Python实现读写INI配置文件的方法示例
2018/06/09 Python
详解python实现识别手写MNIST数字集的程序
2018/08/03 Python
基于django ManyToMany 使用的注意事项详解
2019/08/09 Python
TensorFlow实现自定义Op方式
2020/02/04 Python
40行Python代码实现天气预报和每日鸡汤推送功能
2020/02/27 Python
CSS3的column-fill属性对齐列内容高度的用法详解
2016/07/01 HTML / CSS
部队党性分析材料
2014/02/16 职场文书
班主任经验交流会主持词
2014/04/01 职场文书
2015年后勤工作总结范文
2015/04/08 职场文书
校运会通讯稿
2015/07/18 职场文书
信息简报范文
2015/07/21 职场文书
Python集合set()使用的方法详解
2022/03/18 Python