Skip to content

Commit 3be78af

Browse files
committed
🎨 【小程序】修复 getUserEncryptKey 签名计算问题
1 parent 1697535 commit 3be78af

2 files changed

Lines changed: 36 additions & 2 deletions

File tree

weixin-java-miniapp/src/main/java/cn/binarywang/wx/miniapp/api/impl/WxMaInternetServiceImpl.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
import me.chanjar.weixin.common.enums.WxType;
1010
import me.chanjar.weixin.common.error.WxError;
1111
import me.chanjar.weixin.common.error.WxErrorException;
12-
import org.apache.commons.codec.binary.Base64;
1312

1413
import javax.crypto.Mac;
1514
import javax.crypto.spec.SecretKeySpec;
@@ -27,7 +26,7 @@ public class WxMaInternetServiceImpl implements WxMaInternetService {
2726

2827
private String sha256(String data, String sessionKey) throws Exception {
2928
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
30-
SecretKeySpec secret_key = new SecretKeySpec(Base64.decodeBase64(sessionKey), "HmacSHA256");
29+
SecretKeySpec secret_key = new SecretKeySpec(sessionKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
3130
sha256_HMAC.init(secret_key);
3231
byte[] array = sha256_HMAC.doFinal(data.getBytes(StandardCharsets.UTF_8));
3332
StringBuilder sb = new StringBuilder();
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package cn.binarywang.wx.miniapp.api.impl;
2+
3+
import cn.binarywang.wx.miniapp.api.WxMaService;
4+
import org.mockito.ArgumentCaptor;
5+
import org.testng.annotations.Test;
6+
7+
import static org.assertj.core.api.Assertions.assertThat;
8+
import static org.mockito.ArgumentMatchers.anyString;
9+
import static org.mockito.ArgumentMatchers.eq;
10+
import static org.mockito.Mockito.mock;
11+
import static org.mockito.Mockito.verify;
12+
import static org.mockito.Mockito.when;
13+
14+
/**
15+
* 服务端网络相关接口签名测试.
16+
*/
17+
public class WxMaInternetServiceImplSignatureTest {
18+
@Test
19+
public void testGetUserEncryptKeySignatureUsesRawSessionKey() throws Exception {
20+
WxMaService wxMaService = mock(WxMaService.class);
21+
when(wxMaService.post(anyString(), eq(""))).thenReturn("{\"errcode\":0,\"errmsg\":\"ok\"}");
22+
23+
String openid = "ogu-84hVFTbTt-myGisQESoDJ6BM";
24+
String sessionKey = "9ny8n3t0KULoi0deF7T9pw==";
25+
WxMaInternetServiceImpl service = new WxMaInternetServiceImpl(wxMaService);
26+
27+
service.getUserEncryptKey(openid, sessionKey);
28+
29+
ArgumentCaptor<String> urlCaptor = ArgumentCaptor.forClass(String.class);
30+
verify(wxMaService).post(urlCaptor.capture(), eq(""));
31+
assertThat(urlCaptor.getValue())
32+
.contains("openid=" + openid)
33+
.contains("signature=A6782009C273FDF75CAD421C9D3EAF6CA8715C1B15CB1E130EF40FE7901A9772");
34+
}
35+
}

0 commit comments

Comments
 (0)