1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
| use Think\Cache;
class WeChat { // 你的 appid private $appId = ''; // 秘钥 private $appSecret = ''; // 获取 token 的 url private $getAccessTokenUrl = 'https://api.weixin.qq.com/cgi-bin/token'; // 获取 jsticket 的 url private $getJsTicketUrl = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket';
private $cacheLiefTime = 3600;
private $cacheKey = 'ticket';
/** * 获取签名 * * @time at 2018年12月10日 * @param $url * @return array */ public function getSignature($url) { $nonceStr = $this->createNonceStr(18); $timeStamp = time(); $params = [ 'jsapi_ticket' => $this->getJsTicket(), 'noncestr' => $nonceStr, 'timestamp' => $timeStamp, ]; // 只有唯一的注意点,就是不要把 url 放在 http_build_query 函数里面,它会转义 // 验证你的签名请到这里 http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign $signature = sha1(http_build_query($params) . '&url=' . $url);
return ['noncestr' => $nonceStr, 'timestamp' => $timeStamp, 'signature' => $signature, 'appid' => $this->appId]; }
/** * 获取 TOKEN * * @time at 2018年12月10日 * @return void */ private function getAccessToken() { $params = [ 'grant_type' => 'client_credential', 'appid' => $this->appId, 'secret' => $this->appSecret, ];
$res = $this->httpGet($this->getAccessTokenUrl .'?'.http_build_query($params)); $res = json_decode($res, true); if (isset($res['errcode'])) { return false; }
return $res['access_token'];
}
/** * 获取签名 * * @time at 2018年12月10日 * @return void */ private function getJsTicket() { $ticket = cache($this->cacheKey);
if ($ticket) { return $ticket; }
$accessToken = $this->getAccessToken();
$params = [ 'access_token' => $accessToken, 'type' => 'jsapi', ];
if (!$accessToken) { return false; } $res = $this->httpGet($this->getJsTicketUrl .'?'.http_build_query($params)); $res = json_decode($res, true);
if (isset($res['errcode']) && $res['errcode']) { return false; } Cache::remember($this->cacheKey, $res['ticket'], $this->cacheLiefTime);
return $res['ticket']; }
private function httpGet($url) { $curl = curl_init(); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_TIMEOUT, 500); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($curl, CURLOPT_URL, $url); $res = curl_exec($curl); curl_close($curl);
return $res; }
private function createNonceStr($n) { if (!is_numeric($n)) { return false; } $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; $nonceStr = ''; $strLen = strlen($str); for ($i = 1; $i < intval($n); $i++) { $nonceStr .= $str[rand(0, $strLen-1)]; } return $nonceStr; } }
|