发票管理apiadmin
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

116 lines
2.9 KiB

<?php
declare (strict_types=1);
namespace app\service\wechat;
use app\service\BaseService;
use fast\Http;
use fast\FuncException;
class WechatService extends BaseService
{
protected $token = "";
protected $appid = "";
protected $appsecret = "";
protected $redis = null;
public function __construct()
{
parent::__construct();
if ($token = env('wechat.token')) {
$this->token = $token;
}
$this->appid = env('wechat.appid');
$this->appsecret = env('wechat.appsecret');
$this->redis = new \Redis();
$this->redis->connect('127.0.0.1', 6379);
}
public function wechatChekToken($signature, $timestamp, $nonce): bool
{
$data = array($this->token, $timestamp, $nonce);
sort($data, SORT_STRING);
$str = sha1(implode($data));
if ($str == $signature) {
return true;
}
return false;
}
/**
* 获取accessToken
* @return mixed|\Redis|string
* @throws FuncException
*/
public function getAccessToken(): string
{
$access_token = $this->redis->get('wechat_access_token');
if ($access_token) {
return $access_token;
}
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appsecret}";
$http = new Http();
$res = $http::get($url);
if ($res['code'] != 200) {
throw new FuncException($res['msg']);
}
$data = json_decode($res['data'], true);
if (isset($data['errcode']) && $data['errcode'] != 0) {
throw new FuncException($data['errmsg']);
}
$this->redis->set('wechat_access_token', $data['access_token'], 7200);
return $data['access_token'];
}
/**
*
* @param $url
* @return array
* @throws FuncException
*/
public function getJsSdkSignature($url): array
{
$timestamp = time();
$nonceStr = generate_random_string(10);
$jsapi_ticket = $this->getJsApiTicket();
$signature = sha1(sprintf('jsapi_ticket=%s&noncestr=%s&timestamp=%s&url=%s', $jsapi_ticket, $nonceStr, $timestamp, $url));
return [
'appId' => env('wechat.appid'),
'timestamp' => $timestamp,
'nonceStr' => $nonceStr,
'signature' => $signature,
];
}
/**
*
* @throws FuncException
*/
protected function getJsApiTicket()
{
$access_token = $this->getAccessToken();
$url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' . $access_token . '&type=jsapi';
$res = Http::get($url);
if ($res['code'] != 200) {
throw new FuncException($res['msg']);
}
$data = json_decode($res['data'],true);
return $data['ticket'];
}
}