微信JSSDK生成

<?php

namespace WeChat;
class JSSDK
{
  protected $appId;
  protected $appSecret;

  public function __construct($appid, $appsecret)
  {
    $this->appId = $appid;
    $this->appSecret = $appsecret;
  }

  //获取accesstoken
  public function getAccessToken()
  {
    $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $this->appId . '&secret=' . $this->appSecret;
    $result = $this->https_request_get($url);
    $result = json_decode($result, true);
    return $result['access_token'];
  }

  //获取jsapi_ticket
  private function ticket()
  {
    $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' . $this->getAccessToken() . '&type=jsapi';
    $result = $this->https_request_get($url);
    $result = json_decode($result, true);
    return $result['ticket'];
  }

  //生成签名用于网页
  public function signature($url = null, $nonceStr = null, $timestamp = null)
  {
    $url = $url ? $url : $this->getUrl();
    $nonceStr = $nonceStr ? $nonceStr : $this->nonceStr(16);
    $timestamp = $timestamp ? $timestamp : time();
    $ticket = $this->ticket();
    $sign = [
      'appId' => $this->appId,
      'nonceStr' => $nonceStr,
      'timestamp' => $timestamp,
      'url' => $this->getUrl(),
      'signature' => $this->getSignature($ticket, $nonceStr, $timestamp, $url),
    ];

    return $sign;
  }

  //签名算法
  private function getSignature($ticket, $nonceStr, $timestamp, $url)
  {
    return sha1("jsapi_ticket={$ticket}&noncestr={$nonceStr}×tamp={$timestamp}&url={$url}");
  }

  //随机生成nonceStr
  private function nonceStr($length = 16)
  {
    $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

    return substr(str_shuffle(str_repeat($pool, $length)), 0, $length);
  }

  //获取当前的URL
  private function getUrl()
  {
    if (defined('PHPUNIT_RUNNING')) {
      return 'http://localhost';
    }

    $protocol = 'http://';

    if (!empty($_SERVER['HTTPS'])
      || (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https')
    ) {
      $protocol = 'https://';
    }

    return $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  }

  public function https_request_get($url)
  {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
  }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值