1. 程式人生 > >小程式獲取使用者unionid的方法

小程式獲取使用者unionid的方法

$code = $_GET['code'];//獲取使用者授權會有一個code,但要沒被使用過的

//$code = "0113y3ff1keMCx0jK9gf1nHVef13y3fp";
$appid = "";
$secret = "";
//https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$code."&grant_type=authorization_code
$weixin =  file_get_contents("https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code");//通過code換取網頁授權access_token
$jsondecode = json_decode($weixin); //對JSON格式的字串進行編碼
$array = get_object_vars($jsondecode);//轉換成陣列
$expires_in = $array["expires_in"];
$openid = $array['openid'];//輸出openid
//$session_key = $array['session_key'];
$unionid = $array['unionid'];

$u_openid = "user_openid='".$openid."'";
$data['unionid'] = $unionid;   //使用者unionid

以上你就可以拿到小程式返回給你的unionid,這個是跟微信公眾號是同一個unionid,但是前提條件就是 你的微信公眾號需要在微信開放平臺進行一個資質認證,通過則需要關聯小程式和微信公眾號,這樣就可以拿到了。