1. 程式人生 > >微信小程式通過code獲取openid和unionid

微信小程式通過code獲取openid和unionid

程式碼如下,前端傳入code即可

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/14 0014
 * Time: 上午 11:17
 */
class topapi_api_v1_user_authorization implements topapi_interface_api
{
    /**
     * 介面作用說明
     */
    public $apiDescription = '使用者授權';

    /**
     * 定義API傳入的應用級引數
     * @desc 用於在呼叫介面前,根據定義的引數,過濾必填引數是否已經參入,並且定義引數的資料型別,引數是否必填,引數的描述
     * @return array 返回傳入引數
     */
    public function setParams()
    {
        // TODO: Implement setParams() method.
        return [
            'code'         => ['type'=>'string', 'valid'=>'required', 'example'=>'', 'desc'=>'', 'msg'=>''],
        ];
    }
    public function handle($params)
    {
        $appid = '*****';
        $secret = '*****';
        $code = $params['code'];

        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=" . $params['code'] . "&grant_type=authorization_code";
     
        $data = get_object_vars(json_decode(file_get_contents($url)));
        $openid = $data['openid'];

        return ['data' => $data];
    }
}