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网页木马一枚 附PHP木马的防范方法
Oct 09 PHP
apache mysql php 源码编译使用方法
May 03 PHP
PHP字符串的编码问题的详细介绍
Apr 27 PHP
CentOS 6.2使用yum安装LAMP以及phpMyadmin详解
Jun 17 PHP
怎样使用php与jquery设置和读取cookies
Aug 08 PHP
php短网址和数字之间相互转换的方法
Mar 13 PHP
typecho插件编写教程(五):核心代码
May 28 PHP
thinkphp在低版本Nginx 下支持PATHINFO的方法分享
May 27 PHP
php获取当前url地址的方法小结
Jan 10 PHP
PHP使用 Imagick 扩展实现图片合成,圆角处理功能示例
Sep 09 PHP
PHP pthreads v3下worker和pool的使用方法示例
Feb 21 PHP
php 原生分页
Apr 01 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的日期处理函数及uchome的function_coomon中日期处理函数的研究
2011/01/12 PHP
跨浏览器PHP下载文件名中的中文乱码问题解决方法
2015/03/05 PHP
PHP读取配置文件类实例(可读取ini,yaml,xml等)
2015/07/28 PHP
php parse_str() 函数的定义和用法
2016/05/23 PHP
Prototype ObjectRange对象学习
2009/07/19 Javascript
JS延迟加载(setTimeout) JS最后加载
2010/07/15 Javascript
jquery下div 的resize事件示例代码
2014/03/09 Javascript
吐槽一下我所了解的Node.js
2014/10/08 Javascript
详解AngularJS中的filter过滤器用法
2016/01/04 Javascript
js实现页面跳转的五种方法推荐
2016/03/10 Javascript
jQuery实现大图轮播
2017/02/13 Javascript
JavaScript实现的数字与字符串转换功能示例
2017/08/23 Javascript
浅谈JavaScript中的属性:如何遍历属性
2017/09/14 Javascript
BootStrap模态框不垂直居中的解决方法
2017/10/19 Javascript
完美解决axios跨域请求出错的问题
2018/02/05 Javascript
写一个移动端惯性滑动&amp;回弹Vue导航栏组件 ly-tab
2018/03/06 Javascript
为vue项目自动设置请求状态的配置方法
2019/06/09 Javascript
Layui 数据表格批量删除和多条件搜索的实例
2019/09/04 Javascript
[02:44]DOTA2英雄基础教程 魅惑魔女
2014/01/07 DOTA
python中日期和时间格式化输出的方法小结
2015/03/19 Python
对Tensorflow中的矩阵运算函数详解
2018/07/27 Python
Centos下实现安装Python3.6和Python2共存
2018/08/15 Python
python 高效去重复 支持GB级别大文件的示例代码
2018/11/08 Python
画pytorch模型图,以及参数计算的方法
2019/08/17 Python
基于Python新建用户并产生随机密码过程解析
2019/10/08 Python
python实现横向拼接图片
2020/03/23 Python
python学生管理系统的实现
2020/04/05 Python
学习Python需要哪些工具
2020/09/04 Python
英国文胸专家:AmpleBosom.com
2018/02/06 全球购物
单位消防安全制度
2014/01/12 职场文书
十岁生日父母答谢词
2014/01/18 职场文书
《画风》教学反思
2014/04/16 职场文书
初中教师业务学习材料
2014/05/12 职场文书
领导欢送会主持词
2015/07/06 职场文书
JavaScript高级程序设计之基本引用类型
2021/11/17 Javascript
警用民用对讲机找不同
2022/02/18 无线电