獲取openID 步驟:
第一步 請求微信服務器獲取code
第二步 代上code 去請求微信服務器獲取openID
- 注意:具體祕鑰需要自己填寫真實的祕鑰,在微信中打開測試!
index.php 文件代碼
<?php
session_start();
include './Base.php';
class WeiXinPay extends Base
{
public function __construct()
{
}
}
$obi = new WeiXinPay();
$obi->getOpenId();
base.php 文件代碼
<?php
header("Content-type: text/html; charset=utf-8");
class Base
{
const KEY ='kkkkksdio87923';
const CODEURL = "https://open.weixin.qq.com/connect/oauth2/authorize?";
const APPID = 'ssdfqwxx';
const OPENIDURL = 'https://api.weixin.qq.com/sns/oauth2/access_token?';
const SECRET = 'b8sdjfi28379923834';
public function getOpenId()
{
if(isset($_SESSION['openid']))
{
return $_SESSION['openid'];
}
else
{
if(! isset($_GET['code']))
{
$redirect_uri = self::CODEURL .'appid='.self::APPID.'&redirect_uri='.$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].'&response_type=code&scope='.self::SCOPE.'&state=STATE#wechat_redirect';
header("location:{$redirect_uri}");
}
else
{
$openidurl = self::OPENIDURL.'appid='.self::APPID.'&secret='.self::SECRET.'&code='.$_GET['code'].'&grant_type=authorization_code';
$data = file_get_contents($openidurl);
$arr = json_decode($data,true);
$_SESSION['openid'] = $arr['openid'];
return $_SESSION;
}
}
}
}