微信小程序 使用unique_id 多平臺賬號通用

小程序端獲取數據:使用session_key 去獲取uniqueid。

app.js

login: function () {
    var that = this;
    // 登錄
    wx.login({
      success: res => {
        // 發送 res.code 到後臺換取 openId, sessionKey
        wx.request({
          url: 'https://www******l/api/jscode2session.php',
          data: { code: res.code },
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: function (data) {
            that.getUserInfo(data.data.data.user_info.session_key);//解碼獲取unionID
          }
        })
      }
    })
  },
  getUserInfo:function(sessionKey){
    var that = this
    wx.getUserInfo({
      success: res => {
        res.sessionKey = sessionKey
        // 可以將 res 發送給後臺解碼出 unionId
        wx.request({
          url: 'https://*****/api/aes_data.php',
          data: res,
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: function (data) {
            //解碼獲取unionID
            that.globalData.userInfo = data.data
          }
        })

        // 由於 getUserInfo 是網絡請求,可能會在 Page.onLoad 之後才返回
        // 所以此處加入 callback 以防止這種情況
        if (this.userInfoReadyCallback) {
          this.userInfoReadyCallback(res)
        }
      }
    })
  },

後臺:

jscode2session.php   獲取session_key

aes_data.php              使用session_key獲取unique_id(使用微信提供的加密解密方式)

 

jscode2session.php 

<?php
include_once('config.php');
$code = trim($_POST['code']);      //小程序端傳來的登陸code
$url  = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';   
$r =  curlN($url);
$r = json_decode($r,true);
$arr = array(
		'ret' => 1,
		'msg' => '操作成功',
		'data' => array(
			'user_info' => $r,
			)	
		);
echo json_encode($arr);	

function curlN($url,$data=null)
{	
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$tmpInfo = curl_exec($ch);
	if (curl_errno($ch)) {
	  return curl_error($ch);
	}
	curl_close($ch);
	return $tmpInfo;
}
?>

aes_data.php

<?php
include_once('config.php');
include_once('wxBizDataCrypt.php');

$appid			= $appid;
$sessionKey		= $_POST['sessionKey'];
$encryptedData  = $_POST['encryptedData'];
$iv				= $_POST['iv'];
$pc				= new WXBizDataCrypt($appid, $sessionKey);
$errCode = $pc->decryptData($encryptedData, $iv, $data );
if ($errCode == 0) {
    print($data . "\n");
} else {
    print($errCode . "\n");
}

wxBizDataCrypt.php

<?php

/**
 * 對微信小程序用戶加密數據的解密示例代碼.
 *
 * @copyright Copyright (c) 1998-2014 Tencent Inc.
 */


include_once "errorCode.php";


class WXBizDataCrypt
{
    private $appid;
	private $sessionKey;

	/**
	 * 構造函數
	 * @param $sessionKey string 用戶在小程序登錄後獲取的會話密鑰
	 * @param $appid string 小程序的appid
	 */
	public function __construct( $appid, $sessionKey)
	{
		$this->sessionKey = $sessionKey;
		$this->appid = $appid;
	}


	/**
	 * 檢驗數據的真實性,並且獲取解密後的明文.
	 * @param $encryptedData string 加密的用戶數據
	 * @param $iv string 與用戶數據一同返回的初始向量
	 * @param $data string 解密後的原文
     *
	 * @return int 成功0,失敗返回對應的錯誤碼
	 */
	public function decryptData( $encryptedData, $iv, &$data )
	{
		if (strlen($this->sessionKey) != 24) {
			return ErrorCode::$IllegalAesKey;
		}
		$aesKey=base64_decode($this->sessionKey);

        
		if (strlen($iv) != 24) {
			return ErrorCode::$IllegalIv;
		}
		$aesIV=base64_decode($iv);

		$aesCipher=base64_decode($encryptedData);

		$result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

		$dataObj=json_decode( $result );
		if( $dataObj  == NULL )
		{
			return ErrorCode::$IllegalBuffer;
		}
		if( $dataObj->watermark->appid != $this->appid )
		{
			return ErrorCode::$IllegalBuffer;
		}
		$data = $result;
		return ErrorCode::$OK;
	}

}


errorCode.php

<?php

/**
 * error code 說明.
 * <ul>

 *    <li>-41001: encodingAesKey 非法</li>
 *    <li>-41003: aes 解密失敗</li>
 *    <li>-41004: 解密後得到的buffer非法</li>
 *    <li>-41005: base64加密失敗</li>
 *    <li>-41016: base64解密失敗</li>
 * </ul>
 */
class ErrorCode
{
	public static $OK = 0;
	public static $IllegalAesKey = -41001;
	public static $IllegalIv = -41002;
	public static $IllegalBuffer = -41003;
	public static $DecodeBase64Error = -41004;
}

?>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章