PHP code example of luckyhjh / wechat-mini-program
1. Go to this page and download the library: Download luckyhjh/wechat-mini-program library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
luckyhjh / wechat-mini-program example snippets
namespace App\Libs;
use Illuminate\Support\Facades\Cache;
use WechatMiniProgram\Api\AccessToken;
use WechatMiniProgram\ApiException;
class WechatMiniProgram extends \WechatMiniProgram\WechatMiniProgram
{
public function __construct($appid = '', $secret = '')
{
empty($appid) and $appid = env('WX_APPID');
empty($secret) and $secret = env('WX_SECRET');
parent::__construct($appid, $secret);
}
/**
* 读取token
* @return string
*/
public function getAccessToken()
{
$cache_name = 'wx_token_' . $this->getAppid();
$access_token = Cache::get($cache_name);
if ($access_token) {
return $access_token;
}
$AccessToken = new AccessToken($this);
try {
$Token = $AccessToken->getAccessToken();
$access_token = $Token->access_token;
$this->setAccessToken($access_token, $Token->expires_in);
return $access_token;
} catch (ApiException $apiException) {
return '';
}
}
/**
* 保存token
* @param string $access_token
* @param int $expire
* @return bool
*/
public function setAccessToken($access_token, $expire = 7200)
{
$cache_name = 'wx_token_' . $this->getAppid();
return Cache::set($cache_name, $access_token, $expire);
}
}
use WechatMiniProgram\Api\AccessToken;
use WechatMiniProgram\ApiException;
class WechatMiniProgram extends \WechatMiniProgram\WechatMiniProgram
{
public function __construct($appid = '', $secret = '')
{
empty($appid) and $appid = env('WX_APPID');
empty($secret) and $secret = env('WX_SECRET');
parent::__construct($appid, $secret);
}
/**
* 读取token
* @return string
*/
public function getAccessToken()
{
$cache_name = 'wx_token_' . $this->getAppid();
$access_token = cache($cache_name);
if ($access_token) {
return $access_token;
}
$AccessToken = new AccessToken($this);
try {
$Token = $AccessToken->getAccessToken();
$access_token = $Token->access_token;
$this->setAccessToken($access_token, $Token->expires_in);
return $access_token;
} catch (ApiException $apiException) {
return '';
}
}
/**
* 保存token
* @param string $access_token
* @param int $expire
* @return bool
*/
public function setAccessToken($access_token, $expire = 7200)
{
$cache_name = 'wx_token_' . $this->getAppid();
return cache($cache_name, $access_token, $expire);
}
}
$mp = new WechatMiniProgram();
$Auth = new Auth($mp);
$User = new \WechatMiniProgram\Api\User($mp);//如果要调用其它接口,可复用$mp
try {
$session = $Auth->code2session($code);
$openid = $session->openid;
} catch (ApiException $apiException) {
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.