dd

ThinkPHP实现PayPal登录

jerry thinkphp 2015年11月19日 收藏
最近做跨境电子商务程序的第三方登录用到了PayPal登录,发上来给需要的人。
<?php
namespace Home\Controller;
use Think\Controller;
class User extends Controller{
    public function paypal(){
        $_SESSION['state'] = md5(uniqid(rand(), TRUE)); 
        $client_id = '你的client_id';
        $client_secret = '你的client_secret';
        $nonce = time() . rand();
        $app_return_url = 'http://yourdomain/user/paypal_return';  //这里的返回地址必须要与你在paypal上创建client_id时填写的返回地址一致
        $scopes = 'profile+email+address+phone';
    $paypal_auth_url = "https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/authorize?"
            ."client_id=".$client_id
            ."&response_type=code"
            ."&scope=".$scopes
            ."&nonce=".$nonce
            ."&state=".$_SESSION['state']
            ."&redirect_uri=".urlencode($app_return_url);
        //echo $paypal_auth_url;exit;
    header("Location: $paypal_auth_url"); 
    }

    /**
     * Paypal返回地址
     * @return void
     */
    public function paypal_return(){
        $code = trim($_GET['code']);
        
        $client_id = '你的client_id';
        $client_secret = '你的client_secret';
        //根据授权码获取到access_token    
        if(!isset($_SESSION['access_token'])){    
            $token_url = "https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/tokenservice";    
        $postvals = "client_id=".$client_id
            ."&client_secret=".$client_secret
            ."&grant_type=authorization_code"
            ."&code=".$code;
        $response = Http::fsockopenDownload($token_url,array(
            'post' => $postvals,
        ));
        $atoken = json_decode($response);
        $access_token = $atoken->access_token;
        $_SESSION['access_token'] = $access_token;  //token可以保存起来使用,貌似15分钟后才会失效
      }
       //获取到用户资料
       $profile_url = "https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/userinfo?"
            ."schema=openid"
            ."&access_token=".$_SESSION['access_token'];
    $profile = file_get_contents($profile_url);
    $profile = json_decode($profile);
    if(isset($profile->error)){
        exit($profile->message);
    }
    //注意:有些资料不一定会返回
    $email = $profile->email;
    $name = $profile->name;
    $first_name = $profile->family_name;
    $last_name = $profile->given_name;
    $phone = $profile->phone_number;
    $locale = $profile->locale;
    $address = $profile->address;
  }
}
?>
dd