1. 程式人生 > >IDEA支付寶小程式開發流程——授權登入

IDEA支付寶小程式開發流程——授權登入


IDEA,支付寶小程式

grammar_cjkRuby: true

前置條件

  • 獲取APPID

    我的小程式頁面

    點選列表裡的檢視頁面

  • 新增獲取會員資訊服務
    詳情 > 開發管理 > 功能列表 > 新增功能 > 勾選 獲取會員資訊 > 確認,新增完成後的效果如下圖所示

    新增獲取會員資訊服務

    *PS:如果想獲取手機號和姓名等真實資訊,需要額外申請獲取 敏感資訊申請 流程

  • 設定祕鑰

    • 用阿里的金鑰生成工具生成公私鑰
    • 上傳應用公鑰並獲取支付寶公鑰
      • 登入開放平臺-開發者中心,選擇小程式,找到對應的小程式,點選【檢視】>【設定】> 【開發設定】 >【介面加簽方式】 > 【設定應用公鑰】 > 【設定應用公鑰】 > 把簽名驗籤工具裡“公鑰”的內容複製到此處,點選“儲存”完成金鑰設定

    生成公鑰

    儲存成功後頁面變成下圖所示

    公鑰設定成功頁面

    公鑰用於驗籤使用

伺服器端

  • 在專案的pom.xml中新增服務端SDK

    <dependency>
    	<groupId>com.alipay.sdk</groupId>
    	<artifactId>alipay-sdk-java</artifactId>
    	<version>3.4.49.ALL</version>
    </dependency>
    
    
  • 在application.yaml檔案中新增appid、公鑰、私鑰的配置

    公私鑰的配置

tips: 公鑰不是工具生成的公鑰,而是【公鑰設定成功頁面]裡】點選檢視支付寶公鑰裡獲取的公鑰

  • 讀取配置檔案工具類AliXcxProperty.java

    package com.example.demo.properties;
    
    import lombok.Data;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.stereotype.Component;
    
    /**
     * @Description
     * @Author LW-mochengdong
     * @Date 2018/12/22 11:42
     **/
    @Data
    @Component
    @ConfigurationProperties(prefix = "luwei.ali.xcx")
    public class AliXcxProperty {
    	private String serverUrl;
    	private String appId;
    	private String privateKey;
    	private String publicKey;
    }
    
    
  • IndexController.java的程式碼

    @GetMapping("/auth")
    public AlipayUserInfoShareResponse auth(@RequestParam String authcode){
    	return indexService.auth(authcode);
    }
    
    
  • IndexService.java

    package com.example.demo.service;
    
    import com.alibaba.fastjson.JSONObject;
    import com.alipay.api.AlipayApiException;
    import com.alipay.api.AlipayClient;
    import com.alipay.api.DefaultAlipayClient;
    import com.alipay.api.request.AlipaySystemOauthTokenRequest;
    import com.alipay.api.request.AlipayUserInfoShareRequest;
    import com.alipay.api.response.AlipaySystemOauthTokenResponse;
    import com.alipay.api.response.AlipayUserInfoShareResponse;
    import com.example.demo.properties.AliXcxProperty;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.stereotype.Service;
    
    import javax.annotation.Resource;
    
    /**
     * @Description
     * @Author LW-mochengdong
     * @Date 2018/12/22 11:38
     **/
    @Slf4j
    @Service
    public class IndexService {
    
    	@Resource
    	private AliXcxProperty aliXcxProperty;
    
    	public AlipayUserInfoShareResponse auth(String authcode) {
    		AlipayClient alipayClient = new DefaultAlipayClient(aliXcxProperty.getServerUrl(),
    				aliXcxProperty.getAppId(),
    				aliXcxProperty.getPrivateKey(),
    				"JSON", "utf-8", aliXcxProperty.getPublicKey(), "RSA2");
    		//獲取uid&token
    		AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
    		request.setGrantType("authorization_code");//值為authorization_code時,代表用code換取;值為refresh_token時,代表用refresh_token換取
    		request.setCode(authcode);
    		try {
    			AlipaySystemOauthTokenResponse response = alipayClient.execute(request);
    			if (response.isSuccess()) {
    				log.info("auth success [{}]", JSONObject.toJSONString(response));
    
    				AlipayUserInfoShareRequest alipayUserInfoShareRequest = new AlipayUserInfoShareRequest();
    				AlipayUserInfoShareResponse alipayUserInfoShareResponse = alipayClient.execute(alipayUserInfoShareRequest, response.getAccessToken());
    				if (alipayUserInfoShareResponse.isSuccess()) {
    					log.info("AlipayUserInfoShareResponse success [{}]", JSONObject.toJSONString(alipayUserInfoShareResponse));
    				} else {
    					log.info("AlipayUserInfoShareResponse fail [{}]", JSONObject.toJSONString(alipayUserInfoShareResponse));
    				}
    				return alipayUserInfoShareResponse;
    			} else {
    				log.info("auth fail [{}]", JSONObject.toJSONString(response));
    			}
    		} catch (AlipayApiException e) {
    			log.error("auth exception", e);
    		}
    		return null;
    	}
    
    }
    

以上,伺服器端的授權登入工作完畢,釋出即可!

客戶端

  • index.axml檔案

    <view>  
      {{index}}  
      <button onTap="index"> 首頁 </button>
      <button onTap="getAuthCode"> 授權 </button>
    </view>
    
    
  • index.js檔案

    getAuthCode(){
      my.getAuthCode({
      scopes: 'auth_user', // 主動授權(彈框):auth_user,靜默授權(不彈框):auth_base
      success: (res) => {
    
      if (res.authCode) {
        // 認證成功
        // 呼叫自己的服務端介面,讓服務端進行後端的授權認證,並且種session,需要解決跨域問題
        my.httpRequest({
          url: 'https://app2120230256test.mapp-test.xyz/auth', // 該url是自己的服務地址,實現的功能是服務端拿到authcode去開放平臺進行token驗證
          data: {
            authcode: res.authCode
          },
          success: () => {
            // 授權成功並且伺服器端登入成功
          },
          fail: () => {
            // 根據自己的業務場景來進行錯誤處理
          },
        });
      }
      },
      });
    }
    
    • 儲存用真機掃碼測試

      真機測試頁面

  • 點選 授權 檢視控制檯network檢視的資料如下

    成功頁面

    以上說明整個授權過程成功!

  • 伺服器控制檯的log也證實了這點

    伺服器控制檯log

開啟日誌流程

  • 我的小程式 > 檢視 > 雲服務(公測) > 環境資源 > 更多 > 開啟遠端日誌服務
    下次部署專案時即可生效,不記得伺服器密碼的可以重置伺服器密碼,重置後需要重啟伺服器才能生效,日誌的路徑為/home/admin/logs

至此,支付寶小程式的授權登入流程已完成,感謝各位大神的觀看、評價、校正。PS:下一篇將實現授支付功能!

成東

廣州蘆葦科技Java開發團隊

蘆葦科技-廣州專業網際網路軟體服務公司

抓住每一處細節 ,創造每一個美好

關注我們的公眾號,瞭解更多

想和我們一起奮鬥嗎?lagou搜尋“ 蘆葦科技 ”或者投放簡歷到 [email protected] 加入我們吧

關注我們,你的評論和點贊對我們最大的支援